+ 1

Someone please help me with this code. How did the output work?

int i [] = {1,2,3,4,5,6,7}; int j = 4; cout<<i[++j]; // my answer is 5.But output says 6.

27th Jun 2018, 4:10 AM
Prashant Soni
Prashant Soni - avatar
6 ответов
+ 3
That's because you did Pre-increment j, before passing it to the array. It works like this:: int i[]={1,2,3,4,5,6,7} int j=4; cout<< i[++j]; The reason you got 6,is because you first of all added 1 to j >>[++j]<< This makes j= 5, not 4. Then the compiler now sees the command as :: cout<<i[5]; And i[5] =6;
27th Jun 2018, 4:30 AM
Dlite
Dlite - avatar
+ 2
its 6 cause ++j will be 5 not 4 so 5 index is 6 in the array j++ = 4 ++j = 5
27th Jun 2018, 4:25 AM
Kawaii
Kawaii - avatar
+ 2
well idk c# but in c++ is like that, if you use ++j it will increment the variable and then use it, if you use j++ it will use the variablen and then increment it (maybe you are just confused as far as i know is the same in c# and c++)
27th Jun 2018, 4:29 AM
Kawaii
Kawaii - avatar
+ 1
step:1 int i[] = {1,2,3,4,5,6,7}; step:2 that means i[0]=1, i[1]=2, i[3]=4, i[4]=5, i[5]=6, i[6]=7; step:3 now int j=4; step:4 then step:5 cout<<i[++j]; step:6 in the step:5 ++j means j=1+j step:7 so from the step:3 j=4 step:8 apply step 7 (i.e j value) in step 6 step:9 so we get the value of ++j means j=1+4 atlast we get the j value as 5 step:10 so insert the j value in step:5 step:11 cout<<i[++j]; changed as cout<<i[5] step:12 i[5]=6 this is from step:2 step:13 so the output says 6
27th Jun 2018, 4:33 AM
S. Selvakumar
S. Selvakumar - avatar
0
but its pre ++ not post so it should be 4. actually i know pre and posr from C#. is there any difference?
27th Jun 2018, 4:27 AM
Prashant Soni
Prashant Soni - avatar
0
Lol 😂 This differnce of c# and C++ costed me my challenge win. Thanks for replying so soon . you guys help a lot
27th Jun 2018, 4:34 AM
Prashant Soni
Prashant Soni - avatar