Loops and Nested Loops

After having discussed a lot about arrays, inheritance, interfaces and access and non-access modifiers in Java, there is still one concept of Java that we haven’t explored and that is of ‘Loops and Nested Loops’.

Loops in Java are constructs that we iterate through to achieve a result.

There are three types of loops in Java…they are:

  1. for(……) loop
  2. do…..while loop
  3. while….. loop

Let us see these loops in greater detail:

  1. do…while loop

The syntax of the do…while loop is as follows:

do
{
     statements to be executed;

} while(expression == true);

The statements in the do…while loop will get executed as long as the expression is ‘True’. Once the expression becomes ‘false’, the statements will not be executed any further.

Important point:

The do…while loop will get executed at least once irrespective of the expression

 

 

The statements below the ‘do’ loop will get executed once before it comes to the condition which is specified in the ‘while’ loop. 

Since the condition in the ‘while’ loop in our example becomes false instantly when x becomes 1, it quits the loop after printing the message once. 

2. while…loop

The syntax of the ‘while’ loop is as follows:

while (condition == true){

//execute statements

}

As long as the condition with the ‘while’ loop is true, the statements within the loop will be executed. Once the condition becomes false, the loop stops executing.

Here is an example to illustrate this further:

 

In our example, the loop will execute for as long as x <5 and print the corresponding message. Once, x==5, the loop quits.

3. for…loop

In the ‘for’ loop, the iteration is done for a fixed period of time. The group of statements below the ‘for’ statement are executed for those times.

The syntax of the ‘for’ loop is as follows:

for(beginning condition; ending condition; incrementing/decrementing condition)
{
    //statements to be executed;
}

There can be nested for loops as well.

This is illustrated in the following example:

 

In the above example, we have nested ‘for’ loops. The inner ‘for’ loop(with the ‘j’ variable) iterates for 3 times for every outer ‘for’ (with the ‘i’ variable) loop. So, totally the loop iterates and prints the message for 9 times.

If it is confusing, try tinkering with the code mentioned above – it will make things look clear! 🙂

Have a delightful day and see you again tomorrow! 🙂

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 55 times, 1 visits today)

Related Posts

Leave a Reply