Loops

Imagine, you have to show 1 to 100 as an output of your program. Using System.out.println() hundred times for this would be too dumb. That is where loops shines. Loop can shorten the code to 2 lines:

for(int i=1;i<=100;i++)
System.out.println(i);

Any loop has 4 parts:

  • Control variable: A variable, which starts with an initial value and determines number of iterations (repetitions).
  • Body of the loop: A set of statements executed within the loop.
  • Test Condition: Loops have test conditions. If the condition is satisfied then control enters the body of the loop else terminated.
  • Step value: It is variable which increments or decrements unless the test condition is false.

Types of loops and their usage:

For easy understanding, the example program I used here prints 1 to 100.

1. 'for' loop:

I’m sure you’ll love ‘for’ loop more than any other loop. In this the loop structure is fully specified in one line. This loop is used when number of iterations is fixed. Syntax:

for(initial value; test condition; step value)
{
    Body of the loop
}

Example:

for(int i=1;i<=100;i++)
{
    System.out.println(i);
}

If the body contains one statement only then there’s no need to put curly brackets.

2. 'while' loop:

‘while’ loop is used when number of iterations are not fixed. This is an entry controlled loop, that is, it checks the condition first and then execution begins. Syntax:

initialize;
while(condition)
{
    Statements
}

Example:

int i=1;
while(i<=100)
{
    System.out.println(i);
    i++;
}

3. 'do while' loop:

This loop is same as ‘while loop. Only difference is that it executes the loop once and then checks the condition. So, it is an exit controlled loop. Syntax:

initialize
do
{
    statements
}
while(condition)

Example:

int i=1;
do
{
    System.out.println(i);
}
while(i<=100)

Program:

Question: Print even numbers between 1 to 100.

Answer:

Through For loop:

public class Even

{
    public static void main()
    {
        for(int i=1;i<=100;i++)
        {
            if(i%2==0) // If i is divisible by 2 and have 0 as remainder then print i
            System.out.println(i);
        }
    }
}

Through While loop:

public class Even
{
    public static void main()
    {
        int i=1;
        while(i<=100)
        {
            if(i%2==0)
            System.out.println(i);
            i++;
        }
    }
}

Through do while loop:

public class Even
{
    public static void main()
    {
        int i=1;
        do
        {
            if(i%2==0)
            System.out.println(i);
            i++;
        }
        while(i<=100);
    }
}

Conclusion:

Now you know all types of loops, their syntax, and how to use them. You can shorten your code by using loops.