Problem with executing simple code

There are no errors while compiling, but when execute i've got this:

cargo clean && cargo run
           Compiling exercise1 v0.1.0 (/home/eyegor/mytmp/rust/misc/exercise1)
            Finished dev [unoptimized + debuginfo] target(s) in 0.28s
             Running `target/debug/exercise1`
        thread 'main' panicked at 'index out of bounds: the len is 7 but the index is 7', /rustc/4560ea788cb760f0a34127156c78e2552949f734/src/libcore/slice/mod.rs:2717:10
        note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. 

my code:

fn main() {
    let v:Vec<u8> = vec![1,2,3,6,7,8,9];
    let a = exercise1(v);
    println!("average - {}, middle - {}, max.count data - {}",a[0],a[1],a[2])
}

pub fn exercise1(v: Vec<u8>) -> [u8; 3] {
    let mut i=0;
    let mut b: u8 = v[0];
    let mut a: [u8; 3]=[0,0,0];
    for _k in &v {
        i=i+1;
        b=b+v[i];
    }
    a[0]=b/i as u8;
    return a;
}

The problem is in this section:

for _k in &v {
    i=i+1;
    b=b+v[i];
}

When you call exercise1(v) in main, you're iterating over all 7 elements in the Vec you passed in. The issue is that i is incremented first in the for loop, so that on the first iteration you access v[1], the second iteration accesses v[2], and so on, until on the seventh iteration you access v[7]. v is only 7 elements long, so v[7] is out of bounds, which causes the panic you see.

The fix is rather easy actually, just flip the order of the lines in the for loop so that i is incremented second.

for _k in &v {
    b=b+v[i];
    i=i+1;
}

Hope that makes sense!

Thank You! Its work!!!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.