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
`

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️