package hlo;
public class while5times {
public static void main(String[] args) {
int times=1;
while(times<=5) {
int no = 1;
int count = 1;
while (count <= 5) {
no = no - 1;
System.out.println(no + "");
if (count== 5)
break;
no=no+1;
System.out.println(no + "");
count=count+2;
}
times=times+1;
System.out.println();
}
}
Step-by-Step Execution
- Initial State Variable Value no 1 count 1
-
First Iteration (count = 1, while condition true)
no = no - 1; → 1 - 1 = 0
System.out.println(no); → Prints 0
if (count == 5) → count is 1, so break does not execute
no = no + 1; → 0 + 1 = 1
System.out.println(no); → Prints 1
count = count + 2; → 1 + 2 = 3 -
Second Iteration (count = 3, while condition true)
no = no - 1; → 1 - 1 = 0
System.out.println(no); → Prints 0
if (count == 5) → count is 3, so break does not execute
no = no + 1; → 0 + 1 = 1
System.out.println(no); → Prints 1
count = count + 2; → 3 + 2 = 5 -
Third Iteration (count = 5, while condition true)
no = no - 1; → 1 - 1 = 0
System.out.println(no); → Prints 0
if (count == 5) → Yes! break executes
The while loop terminates.
Additional Explanation
The value of no keeps alternating between 0, 1, 0, 1, 0.
The value of count increases as 1 → 3 → 5.
When count becomes 5, the break statement stops the loop.
`output:
10101
`
Top comments (0)