## 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?

Asked By
0 points
N/A
Posted on - 03/07/2012

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,

In your program to get 30 as the output the condition in the while statement should be as " i<=10 " not " a<=10 "

The solution is as follows, consider while loop with condition statement i<=10

- Initially a=0 & i=0, so while loop gets executed(since i<=10)

a=0+0==>0 & i=0+2==>2

- Then for next step a=0 & i=2, so the following occurs

a=0+2==>2 & i=2+2==>4

- This occurs until " i " becomes 10 on the 6th time of loop where loop gets exited.

a=2+4==>6 & i=4+2==>6

a=6+6==>12 & i=6+2==>8

a=12+8==>20 & i=8+2==>10

a=20+10==>30 & i=10+2==>12

- Finally the output a=30 is printed.

Best Answer

Best Answer

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