Give the output of the following program snippets
Rewrite the program snippets in to while loop
for(j=2;j<=20;j=j+2)
{
if (j==10)
break;
System.out.println(" " +j);
}
Answers
for(int j=2;j<=20;j=j+2){
if (j==10)
break;
System.out.println(" "+j);
}
After converting it into while loop:
int j=2;
while(j<=20){
if(j==10)
break;
System.out.println(" "+j);
j=j+2;
}
2
4
6
8
Let us dry run our program so as to predict the output.
When j = 2:
> j == 10 returns false.
> if block is not executed.
2 is printed and a new line is inserted.
The value of j is incremented by 2.
——————————————————————————
When j = 4:
> j == 10 returns false.
> if block is not executed.
4 is printed and a new line is inserted.
The value of j is incremented by 2.
——————————————————————————
When j = 6:
> j == 10 returns false.
> if block is not executed.
6 is printed and a new line is inserted.
The value of j in incremented by 2.
——————————————————————————
When j = 8:
> j == 10 returns false.
> if block is not executed.
8 is printed and a new line is inserted.
The value of j in incremented by 2.
——————————————————————————
When j = 10:
> j == 10 returns true.
> if block is executed.
> loop is terminated using break statement.
——————————————————————————
So, the final output of the program is:
2
4
6
8
See the attachment for verification.
Answer: