How to calculate this code ?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to calculate this code ??

int x = 0; int &y = x; y = 5; while(x<=5){ cout<<y++; x++; } cou<<x; the result are 57. but how ?

28th Dec 2016, 12:50 PM
Sofyan Maulana
Sofyan Maulana - avatar
6 Answers
+ 6
Hello again.. 😁 int &y=x creates an alias of x, i.e y and x point to same memory location. Then y=5 means the memory location which is pointing to is assigned value 5 that makes x also equal to 5. loop: x=5, cout<<y++, since its postfix so the value of y is given as output before it is incremented, so the output is 5. Now after y is incremented y=6, also recall that x points to same memory location as y, therefore x=6. Now again x is incremented so x=7 and y=7 since x is greater than 5 so the loop stops and the value of x is given as output, which is 7. Hence the result 57
28th Dec 2016, 2:07 PM
Saumya
Saumya - avatar
+ 6
1st the condition is checked whether x<=5 then it enters the loop and the whole block of codes within while, is executed before it again checks for the condition x<=5. At that time it is found that x=7 and the condition is not satisfied.
28th Dec 2016, 2:44 PM
Saumya
Saumya - avatar
+ 4
Welcome 😊
28th Dec 2016, 4:36 PM
Saumya
Saumya - avatar
+ 2
Hello too Saumya 😅 i think you're my fav person along my C++ lessons 😂 Why the loop wasn't stoped when the x value were 6 ?
28th Dec 2016, 2:24 PM
Sofyan Maulana
Sofyan Maulana - avatar
+ 2
Hope i have teacher like you 😄 thanks for guide my way 👍
28th Dec 2016, 2:55 PM
Sofyan Maulana
Sofyan Maulana - avatar
+ 1
int i, j, c; for(i=2; i<=100; i++) { c=0; for(j=2; j<=i; j++) { if(i%j==0) c++; } if(c<2) cout<<i; } How this loop code work ? i'm so confuse with the algorithm 😢
1st Mar 2017, 5:39 PM
Sofyan Maulana
Sofyan Maulana - avatar