There is a clear limit for the break in the while loop, but why does it result in two different conditions?

I'm curious why placing the array before and after the increment affects this code and causes it to panic?

The code below will not cause a panic:

fn main(){
     
     let array_a = [3, 4, 5, 6, 7, 8];
     let mut index_a = 0;

     while index_a != 6 {
        println!("Nilai array secara berurutan: { }", array_a[index_a] ); //placed before increment
        index_a +=1;

     }     
}

When I tried placing the entire println! section after the increment, it caused a panic:


while index_a != 6 {
        index_a +=1;
        println!("Nilai array secara berurutan: { }", array_a[index_a] ); //placed after increment
     }

I have read the material in The Book, and of course, the position greatly matters because before (the index starts from 0) and after (it starts from 1). But I’m curious, why does this have an impact when it is already explicitly clear? while index_a != 6 The loop will stop when it reaches the number 6, clearly out of bounds and will cause a panic.

I thought that as long as there is a clear limit, index_a != 6, it shouldn't matter whether we start from index 0, 3, or 4.

Sorry, I’m a bit confused about how to express it too. What I mean is, when the maximum value is != 6, as long as it doesn’t exceed that, the result will be true.

think twice, for the last iteration, what's the index value? and what would happen if you add 1 to it?

3 Likes

I just realized that this placement affects the final value. The position after the increment makes me call index 6. If I place the println! before the increment, I will never encounter index 6 because the loop stops, so I only get up to the maximum index value, which is 5 .

1 Like

This is why for loops are often preferred over while loops: They're a little less powerful because you can't mess with the iterator from within the loop, but that also makes them less prone to this kind of bug:

     let array_a = [3, 4, 5, 6, 7, 8];

     for index_a in 0..6 {
        println!("Nilai array secara berurutan: { }", array_a[index_a] );
     }     

-- or --

     let array_a = [3, 4, 5, 6, 7, 8];

     for index_a in 0..(array_a.len()) {
        println!("Nilai array secara berurutan: { }", array_a[index_a] );
     }     

-- or --

     let array_a = [3, 4, 5, 6, 7, 8];

     for element_a in array_a {
        println!("Nilai array secara berurutan: { }", element_a );
     }     
1 Like

Thank you, this is win2win solution.