write the output of the following:
int a=5, b=25;
while(a<b)
{
b -=a
System.out.println(“a=”+a+ “ \tb=”+b);
}
Answers
The output for the given code is as follows:
a=5 b=20
a=5 b=15
a=5 b=10
a=5 b=5
Let us dry run our code to get the output.
When a = 5 and b = 25:
→ a < b is true. Loop executes.
> b -= a
> b = b - a
> b = 25 - 5
> b = 20
So, the output is: a=5, b=20
———————————————————————————
When a = 5 and b = 20:
→ a < b is true. Loop executes.
> b -= a
> b = b - a
> b = 20 - 5
> b = 15
So, the output is a=5, b=15
———————————————————————————
When a = 5 and b = 15:
→ a < b is true. Loop executes.
> b -= a
> b = b - a
> b = 15 - 5
> b = 10
So, the output is a=5, b=10
———————————————————————————
When a = 5, b = 10:
→ a < b is true. Loop executes.
> b -= a
> b = b - a
> b = 10 - 5
> b = 5
So, the output is a = 5, b = 5
Now, a < b is false. So, the loop is terminated.
So, the final output is:
a=5 b=20
a=5 b=15
a=5 b=10
a=5 b=5