0

Why are these different?

int x [] = {1,2,3,4}; for (int i=3; i>=0; i--) { cout << x [i] << endl; } Output: 4, 3, 2, 1 int x [] = { 10,20,30,40,50,69} for (int i=0; i <6; i=i+2) { cout << x [i] << endl; } Output: 10, 30, 50 My question is, what is this saying/what's the difference between the two for this part: for (int i=3; i>=0; i--) and for (int i=0; i <6; i=i+2)

22nd May 2017, 9:48 PM
Sami
7 Respuestas
+ 8
Well if you have an array lets say int x = {1,2,3,4,5} the first for, which is (i=4;i>=0;i--) will scan all the array from the last int to the first (5,4,3,2,1) the second for (i=0;i <6; i=i+2) will scan only the 1st the 3rd and the 5th (1,3,5)..
22nd May 2017, 9:59 PM
Basilhs Mixahl
Basilhs Mixahl - avatar
+ 8
well its about for syntax.. inside the for you declare the (initial; condition; increment) so in the for(i=0;i<6;i=i+2) your i becomes first 0 then i+2 which is 0+2=2, afterwards 2+2=4 and afterward 4+2=6 which makes the condition i < 6 false and cause of that the for loop stops.. so i in the for takes the values 0,2,4 which those index in the array got the values 1,3,5..
22nd May 2017, 10:18 PM
Basilhs Mixahl
Basilhs Mixahl - avatar
+ 1
Still not understanding... :\ Why is this scanning the 1st the 3rd and the 5th? for (i=0;i <6; i=i+2) will scan only the 1st the 3rd and the 5th (1,3,5)
22nd May 2017, 10:07 PM
Sami
+ 1
declaration loop for (A; B; C) A is the initial value, example i=0 B is the limit which break loop for, example i < 6 C is the step of increase or decrease of the value, example i=i+2 for (i=0;i <6;i=i+2) result i=0 after i=0+2, i =2 < 6 continue i=2 after i=2+2, i =4 < 6 continue i=4 after i=4+2, i =6 not < 6 break
22nd May 2017, 10:34 PM
MBZH31
MBZH31 - avatar
+ 1
you're welcome
22nd May 2017, 10:47 PM
MBZH31
MBZH31 - avatar
0
That's a little bit more helpful, thank you! But why is it 1,3,5? The array index for loop we are discussing is {5,4,3,2,1}. Shouldn't it be 5,3,1?
22nd May 2017, 10:32 PM
Sami
0
Thank you, MBZH31! That's very clear!
22nd May 2017, 10:40 PM
Sami