do...while loop

Hello guys ok I am terribly bad with loops. There is this question which I do not understand at all.

1
2
3
4
5
6
7
 int x = 0;
int y = 1;
do {
y *= 10; //here is also y= y*10 so y is 10
y = y + x; //y= 10 + 0??
x = x + 1; // ???
} while( y <= 1000 );

x= ? y=?
would be awesome if someone could explain this bit. Thanks!
Last edited on
Line 5: yes, if y==10 and x==0, then y becomes 10+0
Line 6: if x==0, then x+1==1

You could convert your code into a program that you can run. Add printout commands inside the loop and after the loop so that you can see the values of x and y within each iteration and after the loop. That could help you trace the events.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

int main()
{
    int x = 0;
    int y = 1;

    do
    {
        std::cout << "\nenter do-while loop: y == " << y << "  x == " << x << '\n' ;

        y *= 10;
        std::cout << "    after y *= 10: y == " << y << "  x == " << x << '\n' ;

        y = y + x;
        std::cout << "    after y = y + x: y == " << y << "  x == " << x << '\n' ;

        x = x + 1;
        std::cout << "    after x = x + 1: y == " << y << "  x == " << x << '\n' ;

        std::cout << "condition y <= 1000  ie. ( " << y << " <= 1000 )? " << std::boolalpha << ( y <= 1000 ) << '\n' ;
    }
    while( y <= 1000 );
    std::cout << "condition evaluates to false; exit do-while loop\n" ;
}

enter do-while loop: y == 1  x == 0
    after y *= 10: y == 10  x == 0
    after y = y + x: y == 10  x == 0
    after x = x + 1: y == 10  x == 1
condition y <= 1000  ie. ( 10 <= 1000 )? true

enter do-while loop: y == 10  x == 1
    after y *= 10: y == 100  x == 1
    after y = y + x: y == 101  x == 1
    after x = x + 1: y == 101  x == 2
condition y <= 1000  ie. ( 101 <= 1000 )? true

enter do-while loop: y == 101  x == 2
    after y *= 10: y == 1010  x == 2
    after y = y + x: y == 1012  x == 2
    after x = x + 1: y == 1012  x == 3
condition y <= 1000  ie. ( 1012 <= 1000 )? false
condition evaluates to false; exit do-while loop

http://coliru.stacked-crooked.com/a/e41b1490f33e5928
Topic archived. No new replies allowed.