+ 3

For loop and while loop.

1) #include <iostream> using namespace std; int main() { int x; while (x++<10) { x+=2; } cout<<x; return 0; } Output:13 2) #include <iostream> using namespace std; int main() { int i; for(i=0;i<=6;i++); i+=5; cout<<i; return 0; } Output: 12 Can anyone please explain how is the output 13 and 12?

7th Mar 2022, 12:06 PM
Neha Gawali
3 odpowiedzi
+ 2
May I know, how much you understood till now? Where is the difficulty in code? edit: int main() { int x; while (x++<10) { //initially x=0; 0<10 is true, next post increment x++ cause x=1 x+=2; //x = 1+2=3 now after 1st iteartion /* in 2nd iteration 3<10 is true, next post increment x++ cause x=4 x+=2; x = 4+2=6 now after 2nd iteartion in 3rd, 6<10 is true, next post increment x++ cause x=7 x+=2; x = 7+2=9 now Next, 9<10 is true, next post increment x++ cause x=10 x+=2; x = 10+2=12 now Next iteration 12<10 is false, loop stops here but x++ cause its value to be x=x+1=12+1=13. */ } //so at end x=13 after the loop, its printed cout<<x; return 0; }
7th Mar 2022, 12:38 PM
Jayakrishna 🇮🇳
+ 2
Jayakrishna🇮🇳 thank you so much!🙌 just my silly mistake between x++ and ++x got me confused. Thank you for clearing the doubt.💯
7th Mar 2022, 1:17 PM
Neha Gawali
+ 2
So you know how 2nd code works by for loop? Are you aware of semicolon after for loop, what is cause? If yes, then fine.. 👍👍 You're welcome..Neha Gawali
7th Mar 2022, 1:27 PM
Jayakrishna 🇮🇳