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.