KnowledgeBoat Logo

Output Questions for Class 10 ICSE Computer Applications

Give the output of the following Java program snippet based on nested loops:

int x,y; 
for(x=1; x<=5; x++)
{
for(y=1; y<x; y++)
{
if(x == 4)
    break; 
    System.out.print(y);
}
System.out.println( );
}

Java

Java Nested for Loops

ICSE

21 Likes

Answer

 
1
12
 
1234

Working

1st iteration of outer for
x = 1
Inner for loop doesn't execute as y = 1 so the condition y\<x is false
Just a newline is printed to the console due to System.out.println( );

2nd iteration of outer for
x = 2
Inner for loop executes once printing 1 to the console

3rd iteration of outer for
x = 3
Inner for loop executes twice printing 12 to the console

4th iteration of outer for
x = 4
if(x == 4) becomes true inside inner for loop. break is executed, just a newline is printed to the console.

5th iteration of outer for
x = 5
Inner for loop executes 4 times printing 1234 to the console

Answered By

10 Likes