Nested While Loop in Java

It is pretty impossible to impose hundreds of words or numbers by just writing or putting into variable one by one. Instead, use a loop to avoid extra time.

This article gives an overview of nested while loop in Java and how to use them.

Why use loops?

Loops are the programming structure of an operation that repeats in a specific sequence until the particular condition or procedure is completed. Loops follow the don’t repeat yourself (DRY) principle for complete coding. According to the requirement, a programmer can execute the same line of code or block of code iteratively to a specific point. Instead of copying or pasting, the code block runs multiple times, either for variables or for files.
It’ll be more illustrative when the loop is in the form of code.

Output:
10
9
8
7
6
5
4
3
2

Here the while loop runs consisting of the condition i>10, where i initialize to 10.

So now the concept of loop is clear, let’s dive into the nested loops in Java.

Nested While Loop in Java

What do nested words signify? When similar objects are placed inside one another, context with the effective term is known as nesting. The same goes with the while loop. When one while loop is placed inside the other while loop, it is nested While Loop in Java.

In the nested while loop, the outer loop executes ones, and after that, execution of the inner loop starts. The implementation of the inner loop continues until the condition gets false. Once the last expression is false and the internal requirement satisfies, the inner loop get terminates, and the outer loop starts for the next iteration.

Syntax:

Let’s understand with the help of code.

Output:

1 outer loop

1 inner loop
2 inner loop
3 inner loop
4 inner loop

2 outer loop

1 inner loop
2 inner loop
3 inner loop
4 inner loop

3 outer loop

1 inner loop
2 inner loop
3 inner loop
4 inner loop

The outer loop executes once, and the inner loop starts with the condition and run until it satisfies the given requirement. Further, with increment in i value, the outer loop’s iteration starts and executes the inner loop. The outer loop terminates when the condition became false. Until the false state, the operation in the inner loop gets performed.

Apart from the while loop Java provides other loops like for and do while with almost the same iterative approach to execute several statements in a specific sequence.

Leave a Comment

Your email address will not be published. Required fields are marked *