JAVA

All Languages C CPP JAVA HTML CSS JAVASCRIPT PYTHON

Loops In Java

Broadly classifying, there are three types of loops in Java programming which are:
1. while loop
2. for loop
3. do...while loop

while loop

while loop makes it quite easy.

Let's first look at the syntax of while loop.

while(condition)
  {
    statement(s)
  }

while loop checks whether the condition written in ( ) is true. If the condition is true, statements written in the body of the while loop i.e. inside the braces { } are executed.Then, again the condition is checked, and if found true, again the statements inside body of the while loop are executed. This process continues until the condition becomes false.

An example will make this clear.

class L1{
public static void main(String[] args){
  int n = 1;
  while( n <= 10){
    System.out.println(n);
    n++;
  }
}
}

Output

In our example, firstly, we assigned a value 1 to a variable 'n'.
while(n <= 10) checks the condition 'n <= 10'. Since the value of n is 1 which is less than 10, the statements within the braces { } are executed.
The value of 'n' i.e. 1 is printed and n++ increases the value of 'n' by 1. So, now the value of 'n' becomes 2.
Now, again the condition is checked. This time also 'n <= 10' is true because the value of 'n' is 2. So, again the value of 'n' i.e. 2 gets printed and the value of 'n' gets increased to 3.
When the value of 'n' becomes 10, again the condition 'n <= 10' is true and 10 gets printed for the tenth time. Now, n++ increases the value to 'n' to 11.
This time, the condition 'n <= 10' becomes false and the program terminates.
Quite interesting. Isn't it !

Let's see one more example of while loop

import java.util.*;

class L2{
public static void main(String[] args){
  Scanner s = new Scanner(System.in);
  int choice = 1;
  while(choice == 1){
	
    int a;

    System.out.println("Enter a number to check odd or even");
    a = s.nextInt();

    if(a%2==0){
      System.out.println("Your number is even");
    }

    else{
      System.out.println("Your number is odd");
    }

    System.out.println("Want to check more 1 for yes 0 for no");

    choice = s.nextInt();

  }

  System.out.println("I hope you checked all your numbers.");

}
}

Output

The loop will run until the value of 'choice' becomes other than '1'. So, for the first time, it will run since the value of 'choice' is '1'. Then it will perform the codes inside the loop. At last, it will ask the user whether he wants to check more or not. This can change the value of the variable 'choice' and may terminate the loop.
Initially, the value of 'choice' was 1, so the condition of while got satisfied and the statements inside it got executed. We were asked to give the value of choice and we gave 1 again. Things repeated and after that, we gave choice a value of 0. Then the condition of while was not satisfied and the loop terminated.

for loop

Another type of loop is for loop.
Let's go to our first example in which we printed the first 10 natural numbers using while loop. We can also do this with for loop.

Let's look at the syntax of for loop.

for(initialization; condition; propagation)
  {
    statement(s)
  }

class L3{
public static void main(String[] args){
  int n;
  for( n = 1; n <= 10; n++ ){
    System.out.println(n);
  }
}
}

Output

Now let's see how for loop works.
for(n=1; n<=10; n++)
n=1 - This step is used to initialize a variable and is executed first and only once. Here, 'n' is assigned the value of 1.
n<=10 - This is a condition which is evaluated. If the condition is true, the statements written in the body of the loop are executed. If it is false, the statement just after the for loop is executed. This is similar to the condition we used in 'while' loop which was being checked again and again.
n++ - This is executed after the code in the body of for loop has been executed. In this example, the value of 'n' increases by 1 every time the code in the body of for loop executes. There can be any expression here which you want to run after every loop.
In the above example, firstly 'n=1' assigns a value 1 to 'n'.
Then the condition 'n<=10' is checked. Since the value of 'n' is 1, therefore the code in the body of for loop is executed and thus the current value of 'n' i.e. 1 gets printed.
Once the codes in the body of for loop are executed, step a++ is executed which increases the value of 'n' by 1. So now the value of 'n' is 2.
Again the condition 'n<=10' is checked which is true because the value of 'n' is 2. Again codes in the body of for loop are executed and 2 gets printed and then value of 'n' is again incremented.
When the value of 'n' becomes 10, the condition 'n <= 10' becomes true and 10 gets printed. Now, when n++ increases the value to 'n' to 11, the condition 'n<=10' becomes false and the loop terminates.

Let's see an example for adding 10 numbers.

import java.util.*;

class L30{
public static void main(String[] args){

  int sum = 0, i, n;
  Scanner s = new Scanner(System.in);

  for(i = 0; i<10; i++){
    System.out.println("Enter number");
    n = s.nextInt();

    sum = sum + n;
  }

  System.out.println("Sum is "+sum);

}
}

Output

Initially, the variable 'sum' is 0. After the first iteration,
sum = sum + n; - the value of n is entered 4. So, the expression sum + n is 0+4. So, the expression becomes sum = 0 + 4;, thus making the value of sum as 4.
In the second iteration,
sum is 4 and n is entered 3. So, sum + n becomes 4 + 3 i.e. 7, thus making the value of sum as 7.
In this way, this loop will add all the 10 numbers entered by the user.
There are other ways also to write a program of for loop.
The first example of for loop in which we printed the first 10 natural numbers can also be written in other ways which are :

int n = 1;
for(; n <= 10; n++)
  {
    System.out.println(n);
  }

Another way is as follows.

int n;
for(n = 1; n <= 10;)
  {
    System.out.println(n);
    n++;
  }

There is also an another form of for loop which is discussed in the chapter 'array'.

do...while loop

This is another kind of loop. This is just like while and for loop but the only difference is that the
code in its body is executed once before checking the conditions.

Syntax of do...while loop is:

do{
  statement(s)
}
while(condition);

Consider the same example to print the first 10 natural numbers for which we wrote programs using while and for loop. Now, let's write its program using do...while loop.

class L5{
  public static void main(String[] args){
    int n = 1;
    do{
      System.out.println(n);
      n++;
    }while( n <= 10 );
  }
}

Output

Let's try to understand this.
At first, the code inside the body of the loop (i.e. within the braces { } following do ) are executed.
This prints the value of 'n' i.e. 1 and n++ increments the value of 'n' by 1. So now, the value of 'n' becomes 2.
Once the code inside the braces { } is executed, the condition 'n <= 10' is checked. Since the value of 'n' is 2, so the condition is satisfied.
Again the code inside the body of loop is executed and the value of 'n' becomes 2. When the value of 'n' is 10 and 10 is printed, n++ increases the value of 'n' to 11. After this, the condition becomes false and the loop terminates.
As you have seen, in do while loop, codes inside the loop got executed for the first time without checking any condition and then it started checking the condition from the second time.

Nesting of loop

Like 'if/else' we can also use one loop inside another. This is called nesting of loop. See this example to understend it.

class L6{
public static void main(String[] args){
  int i;
  int j;

  for(i = 12;i<=14;i++){/*outer loop*/

    System.out.println("Table of " + i);

    for(j = 1;j<=10;j++){/*inner loop*/

      System.out.println(i+"*"+j+" = "+(i*j));


    }
  }
}
}

Output

When the first for loop is executed, the value of i is 12 and then Table of 12 get printed. Now coming to the second for loop.
Initially, the condition ( j<=10 ) gets satisfied since the value of j is 1 ( j is less than 10 ). Thus the body of this for loop gets executed and i*j (which is 14*1) i.e. 14 gets on the screen and then j++ increases the value of j by 1, making its value equal to 2.
Again the condition of the loop gets satisfied since the value of j is 2 this time ( 2 is less than 10 ). Again its body gets executed and i*j (which is 14*2) i.e. 28 gets printed on the screen and j++ further increases its value by 1 thus making it 3. Again the condition of the loop gets satisfied and 42 gets printed.
When the value of j becomes 10, 140 gets printed and j++ makes its value equal to 11. So now, the condition of the loop ( j <= 10 ) is not satisfied and the loop stops.
Now, coming out of the inner loop, i becomes 13 and Table of 13 gets printed and again things will repeat again with i equals 13.
It's cool!

Infinite loop

There may exist some loops that iterate or occur infinitely. These are called Infinite Loop. These loops occur infinitely because their condition is always true. We can make an infinite loop by leaving its conditional expression empty. When the conditional expression is empty, it is assumed to be true. Let's see an example on how to make a for loop infinite.

class L7{
public static void main(String[] args){
  for(;;){
    System.out.println("This loop will never end");
  }
}
}

Output

To terminate an infinite loop, press Ctrl + C.