Help me out in this C++ with the while loop
When you run a C++ program, what will appear on the screen after following statements are executed?
int a=0,i=0;
while(a<=10){ a=a+i i=i+2; }
cout<<a<<endl;
The answer should be 30 but how come?
When you run a C++ program, what will appear on the screen after following statements are executed?
int a=0,i=0;
while(a<=10){ a=a+i i=i+2; }
cout<<a<<endl;
The answer should be 30 but how come?
Â
Hi  Tricia Klein !
Their is a logical error in your code , you can dry run your code and find out the logical error in your code.
Like I'm going to dry run it for you.
1. while(0<=10) Â { Â a=0+0 ; i=0+2;}
2. while (0<=10) {a=0+2; i=2+2}
3. while (2<=10) {a=2+4; i=4+2}
4. while (6<=10) {a=6+6; i=6+2}
5. while (12<=10)  false ….. And your output will be 12
But if you change while Condition to while (i<=10)
Now dry runÂ
1. Â while (0<=10) {a=0+0; i=0+2}
2. while (2<=10) {a=0+2; i=2+2}
3. while (4<=10) {a=2+4; i=4+2}
4. while (6<=10) {a=6+6; i=6+2}
5. while (8<=10) {a=12+8; i=8+2}
6. while (10<=10) {a=20+10; i=10+2}
7. while (12<=10) condition false and your desired output will be 30
Hope that you will understand .
Thanks