DEV Community

yaswanth krishna
yaswanth krishna

Posted on

While looping understand counts how to work and 10101 while using concept

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();
}

        }

Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution

  1. Initial State Variable Value no 1 count 1
  2. 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

  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

  4. 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.
Enter fullscreen mode Exit fullscreen mode

`output:

10101
`

Top comments (0)