Home > Mobile >  Need Help Understanding While Loops Problem?
Need Help Understanding While Loops Problem?

Time:07-21

I got this question right. The Answer is 13. But I simply don't Understand the question at all. I've been trying to watch youtube videos but I can't seem to understand this. Could someone please help me?

What is the output after the following code segment is executed?

int x = 1;
int y = 0;
while (x < 10)
{
     y = 5;
     while (y > x)
     {
          y--;
     }
     x  = y;
}
System.out.println(x);

Answer: 13, But I need help understanding why.

CodePudding user response:

for easy understanding, you can add some println() in loops and get something like

1 5 (x, y=5)
1 4 (x, y--)
1 3 (x, y--)
1 2 (x, y--)
1 1 (x, y--)
2   (x y)

2 5 (x, y=5)
2 4 (x, y--)
2 3 (x, y--)
2 2 (x, y--)
4   (x y)

4 5 (x, y=5)
4 4 (x, y--)
8   (x y)

8 5 (x, y=5)
13  (x y)

CodePudding user response:

So, when we dry run the code provided:

Two variables are initialized -> x = 1,y = 0

1st Iteration

Next we go inside a while loop which will only fail when x will become greater 
than or equal to 10, which is not the case now as x=1

Next we are initializing y = 5

    Now the inner while loop condition says that until y becomes less than or equal 
    to current x value it will get execute and decrease the y value.
    Walkthrough: y = 5,x = 1 condition=true
                 y = 4,x = 1 condition=true
                 y = 3,x = 1 condition=true
                 y = 2,x = 1 condition=true
                 y = 1,x = 1 condition=false (loop break)
             
Finally we are adding y value to x : (x= x   y) For current walkthrough x = 1   1 = 2

2nd Iteration

Now as x is still not greater than or equal to 10
We again go inside the loop and each time one iteration will decrease because every time y value is initialized by 5, so now inner loop will break at 
y=2,x=2 condition=false 
x = x  y = 2   2 = 4

3rd Iteration

Again as x<10 i.e. (4<10)
Inner loop will break at 
y = 4,x = 4 condition=false
x = x   y = 4   4 = 8

4th Iteration

Again as x<10 i.e. (8<10)
Inner loop will break at  
y = 5,x = 8 condition=false
x = x   y = 8   5 = 13

5th Iteration

Outer loop condition fails as now x>10 i.e. (13>10)

Finally x value is printed on the console i.e. 13

CodePudding user response:

The code is shown above in the picture ,do trace this way.

first y:5 second y:4 second y:3 second y:2 second y:1 third x:2 first y:5 second y:4 second y:3 second y:2 third x:4 first y:5 second y:4 third x:8 first y:5 third x:13 finall x:13

  • Related