Intro To Loops In Java

Home /

Table of Contents

In Java, loops are used to execute a block of code repeatedly until a certain condition is met. There are three types of loops in Java: the while loop, the do-while loop, and the for loop. The while loop checks the condition before executing the block of code, whereas the do-while loop executes the block of code at least once and then checks the condition. The for loop is a compact version of the while loop and is used when the number of iterations is known. Loops are an essential part of programming and are commonly used to iterate through arrays, process data, and perform repetitive tasks.

What is Loop?

Sometimes we want to repeat something. We need to do a task over and over again. Some real-world examples are:

  • Count from 1 to 10
  • Go through all the words in a dictionary to see whether they are five to seven letters long
  • For each customer that has an outstanding balance, send out an email reminder that payment is due

Now let us focus on a magical example. Do you remember that scene from Harry Potter and the Order of Phoenix – when he was serving detention, Dolores Umbridge forced Harry to write “I must not tell lies” using her own magical quill? The scene goes like this:

“I want you to write, ‘I must not tell lies’,” she told him softly.
“How many times?” Harry asked, with a creditable imitation of politeness.
“Oh, as long as it takes for the message to sink in,” said Umbridge sweetly. “Off you go.”

The words were instantly cut into the back of his hand and the words appeared on the paper with his own blood as the ink.

RDtf9JU4vXh0asIONWTapMBvuNcsoWkcCk7IM ARX fcpVLeg5P5wHhUPFnDFqiEo5 PUYA4A1zNqttG58Qa m2Xyj6iv2WlikXIL1C - Intro To Loops In Java

No, we will not(in fact can not) do something this harsh. Mostly because we are muggles and do not have magical quills. And it is a crime to physically harm someone. Instead, we will try to print this sentence 10 times in the console. One way to do this is to write 10 System.out.println() statements with “I must not tell lies” as their argument(More on argument later when we discuss methods).

APPROACH ONE:

System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");
System.out.println("I must not tell lies");

In the following LoopDemo program, we are going to print “I must not tell lies” 10 times on the console.

public class LoopDemo{
    public static void main(String[] args) {
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
        System.out.println("I must not tell lies");
    }
}

Output

I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies

The problem with this approach is that we have to write the same line 10 times. Even if we copy and paste the line 9 times, still we can not avoid doing the same task over and over again. So this approach is not an efficient and smart one.

How wonderful it would be to have some mechanism that helps us avoid repetitive tasks. Would not it be great if we could just instruct the computer to do a task over and over again? In our case, it would be more efficient if we could tell the computer to print “I must not tell lies” 10 times.

APPROACH TWO:

Repeat (System.out.println("I must not tell lies");) 10 times.

Compare the two approaches! Which one is more readable?

The first approach is without a loop(a concept you will be soon familiar with). If you want the computer to do something repeatedly, you could choose to type the same thing again and again and again.

Or you can choose the second approach and put it in a loop, mention how many times it needs to repeat(called target), sit back and let the computer do the hard work. It saves the time, effort, and frustration of any future code reviewer(including you).

The loop is a fundamental construct in programming. Looping is not required, it is possible to hard code the repeated task. But loops allow programs to do repetitive tasks, with little differences on every repetition, without repeating the code itself, reducing the code size while saving coding time.

You may have come across the word iteration. There may be a situation when you need to execute a block of code several times. Iteration means executing the same instruction, or set of instructions, repeatedly(doing a task again and again). It is implemented using an conditional branch where execution jumps backward and then resumes flowing forward toward the same jump point, resulting in a loop. You do not want to get struck in a loop, do you? You do not want to keep doing the same task over and over again for the rest of your life. Typically a condition will be included for terminating the loop. This means you can get out of the loop, or break the loop.

rGHRsUnPMwt oeG DRB2oNcVpDmPjiQOFaWtDP7ZibDStdEsLfJjkjM2ZS5yGm7EjADO - Intro To Loops In Java

Java mainly has three loop statements.

FOR LOOP IN JAVA

The first one we will discuss is the for loop. It allows one or more statements(blocks of codes) to be repeated. If you have programmed in any other programming language then the following tutorial may be familiar to you. In any case, the for loop behaves much like its equivalent in other languages.

Many Java programmers consider for loop to be the most flexible loop. The for loop allows a large number of variations. In this section, we will only discuss its most common form.

We use a for loop to repeat a statement or block of statements a specified number of times. The general form of a for loop to repeat a single statement is shown here:

for(initialization; conditional test; increment) statement;
2XZRb5ehGN8ndpNhimmrm9Pb8IA68yzFLKeGY97x5V38 jwhLYMW2HdqXeIc0yEjgh1rwugdqCClpdA3rfcmuWClhxlZMdJmA gdv2hecONlLNZgkpeExzUOfo rip0y JGzsinVVGBsjmKP 14 - Intro To Loops In Java

Initialization

One or more variable(s) is(are) declared and initialized here. We can declare the variable(s) beforehand and initialize them here in this initialization section. Or like above we can declare and initialize the variable(s) in this section. In this initialization portion, we basically give an initial value to the variable(s) that controls the loop. This variable(s) is(are) usually referred to as the loop-control variable. The initialization section is executed only once before the loop begins.

Conditional Test

As its name suggests a conditional operation is performed in this section. This portion of the loop tests the loop-control variable(s) against a target value. The conditional test evaluates to a boolean value: true or false. If it evaluates to true, the loop repeats. If it evaluates to false, the loop stops, and program execution picks up with the next line of code that follows the loop. The conditional test is performed at the start or top of the loop each time the loop is repeated.

Increment

This portion of the for loop is executed at the bottom of the loop. The increment portion is executed after the statement or block that forms its body has been executed. The purpose of the increment portion is to increase(or decrease) the loop-control value by a certain amount.

As a simple example, we will write our previous program using a for loop.

public class ForLoopDemo{
    public static void main(String[] args) {
        for(int i=0; i<10; i++){
            System.out.println("I must not tell lies");
        }
    }
}

Output

I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies
I must not tell lies

The ForLoopDemo program is an improved version of the LoopDemo program. It requires less lines of coding, is more readable, and is more understandable.

Now let us give another demo to fully realize the working of a FOR Loop. The following PrintNumbers program prints the numbers from 1 to 10 on the console.

public class PrintNumbers{
    public static void main(String[] args) {
        
        int num;
        /*counts the number and prints the number repeatdely until the conditional statment
        is evaluated to false*/
        for(num=1;num<11;num++){
            System.out.print(num+" ");
        }
        System.out.println();//this line executes after the loop block finsishes executing
        System.out.println("Numbers counted and printed");
    }
}

Output

1 2 3 4 5 6 7 8 9 10
Numbers counted and printed

Explanation

First we declare a variable num to keep track of the loop. This is the so called loop-control variable. Then in the initialization section of the for loop we initialize num to 1.
In the conditional test section we test if the num is less than 11.
In the increment section we increment num by 1.

After the initialization the expression num<11 is evaluated. The for loop starts to run as the expression evaluates to true. In the for loop block, first, the value of num is loaded from the main memory and then the value of num is printed by System.out.println(). Next, when the for loop block is complete then the value of num is incremented by 1 and the conditional test is evaluated again. This process continues until the value of num equals 11. When the value of num equals 11 then the conditional test num<11 is evaluated as false and for loop stops. Then the control goes to the next line, the line right after the for loop blocks. An empty line is printed followed by a line “Numbers counted and printed”. Note that the initialization section is only executed once when the loop is first entered. The conditional test is performed at the start of each iteration. The loop will not execute even once if the conditional test is evaluated as false, to begin with. The following program demonstrates this.

public class PrintNumbers2{
    public static void main(String[] args) {
        
        int num;//variable declaration

        /*counts the number and prints the number repeatedly until the conditional statement
        is evaluated to false*/
        for(num=11;num<11;num++){
            System.out.print(num+" ");
        }

        System.out.println(); //this line executes after the loop block finishes executing, i.e. loop breaks
        System.out.println("Numbers counted and printed");
    }
}

Output:

Numbers counted and printed
Imagine a scenario: You have to compute the product and sum of numbers 11 to 20. How do you do it?

SUM

One simple way is, first take 0 as the sum of zero numbers. Next you add the first number 11 to it. We will denote the first number simply as number.
                 sum = 0
                 number = 11
Add the first number to sum and store the result to a variable called result. Next substitute the value stored in sum with the value stored in result.
              result = sum + number
              sum = result
This is the sum of 1 number. The sum of 1 number is 11.



Next you consider 12 as the first number. You add this to the sum of 1 number. So the steps become:
              sum = 11
              number = 12
Add the first number to sum and store the result to a variable called result. Next substitute the value stored in sum with the value stored in result.
              result = sum + number
              sum = result
This is the sum of 2 numbers. The sum of first 2 numbers is 33.



Next you consider 13 as the first number. You add this to the sum of 2 numbers. So the steps become:
              sum = 11
Add the first number to sum and store the result to a variable called result. Next substitute the value stored in sum with the value stored in result.
              result = sum + number
              sum = result
This is the sum of 3 numbers. The sum of the first 3 numbers is 46.



Repeat these steps until the first number i.e the number equals to 21.

To compute the product the same steps may be followed, substituting the additional parts with the multiplication.

The following program demonstrates this.

public class SumAndProductDemo{
    public static void main(String[] args) {
        int number;
        int sum = 0;//sum of zero number
        int product = 1; //product of 1 number

        for(number=11; number<20; number++){
            sum = sum + number;
            product = product * number;
            System.out.println(product);
        }

        System.out.println("Sum and Product :" + sum + " " + product);

    }
}

Output:

Sum and Product :135 -837609728

Try to figure out why the product is a negative number.

A for loop can run negatively. This means we can decrement the loop control variable. Look the following code fragment:

for(number = 20; num > 0; num = num - 1)
{

}

Moreover, the loop control may be incremented or decremented by more than one. The following program counts to 100 by fives:

public class CountByFive{
    public static void main(String[] args) {
        int num;
        for(num=0; num<101; num=num+5){
            System.out.print(num+" ");
        }
    }
}

Output:

0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

WHILE LOOP

We know Loops are used to avoid repeating code without having to type it over and over again. We already covered for loops. In this segment, we will cover the while loop. Though they are both loops they have different syntaxes in each programming language and they have different purposes.

The for loop runs until the conditional test evaluates to FALSE. The for loops keep running for a specific number of times. On the other hand, the loop keeps running while the condition is TRUE.

The while loop is considered by many as the simplest of all the loops. The while loop has the following form:

initialize;
while(condition){
statement;
increment or decrement;
}

Look at the following program:

public class PrintNumbers3{
    public static void main(String[] args) {
        
        int num=1;
        /*counts the number and prints the number repeatedly until the conditional statement
        is evaluated to false*/
        while(num<21){
            System.out.print(num+" ");
            num++;
        }
        System.out.println();//this line executes after the loop block finishes executing
        System.out.println("Numbers counted and printed");
    }
}

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Numbers counted and printed

This program prints the number from 1 through 20 until the number is 21 and the conditional test becomes false(num<21).

There is a special case used for a while loop which is called an infinite loop. It is used for things that need to keep running without a stop. For example, servers need to keep running without stopping.

Please do note that while loop and for loops can be used interchangeably. There is really no missing feature from one over the other. The logic of a while loop can also be applied to a for a loop. The main reason to use one over the other is basically readability. You will typically use a for a loop when there is a known number of iterations. A while loop is best used when the iterations are unknown.

DO WHILE LOOP

Do you remember the working of for loop and while loop? First, the loop control variable is initialized. Then the conditional test happens, if it evaluates to true then the code block of the for/while loop executes. If the test evaluates to false then the code block associated with the for/while loop does not execute. In simple words, the condition is evaluated before the execution of the loop’s body. But the do-while loop condition is evaluated after the execution of the loop’s body.

The basic format of a do-while loop statement is:

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

The consequence of a do-while loop is that its body always executes at least once in contrast to a for loop or a while loop. A for loop or a while loop will execute zero times if the initial condition evaluates to false. You use a do…while loop in the situation in which the code block needs to execute at least once before doing anything meaningful.

To give you a real-world example imagine the ATM Booth scenario. If you want to withdraw the money you have to insert the ATM Card and enter the PIN Number. The PIN must be entered once prior to testing. The following pseudo-code illustrates this situation.

DO  
    PRINT “Please Enter Your PIN”;
    GET pinNumber;
    VALIDATE pinNumber;
    SET numberOfAttempts = numberOfAttempts + 1;  
WHILE (pinNumber NOT VALID AND numberOfAttempts < 3) 

Where the loop will iterate a maximum of three times to allow the entry of a valid PIN number. A while loop could also be used here.

So what is the difference? It simply depends upon whether the algorithm requires that the body of the loop needs to run once first before deciding whether the loop will continue. If so, use a do…while loop, otherwise you should use a while loop.

Working Of do-while Loop

First, the statements inside the loop execute. After the first iteration, the condition gets evaluated. If the condition evaluates to true the control is transferred to the “do” else it breaks the loop and jumps to the next statement after do-while.

JemwjuUrbRUy9A28HjravJj9T2SpL9vr33VGJH2M QLJi053jazVFM8rOZzbXNyUfDwKPpTTBzp0j DMLpsE F9ROMc3H7z8Qkgilfhffcj pl1QF7P80VZlZ02qFNNHs0IRLRinoGYmYu0i9N4 - Intro To Loops In Java

The following program demonstrates a do…while loop. It is an application of the ATM Booth scenario.

import java.util.Scanner;

public class dowhileDemo{
    public static void main(String[] args) {
        int numbersOfAttemptsLeft = 3;//You have a maximum number of three attempts
        Scanner scan = new Scanner(System.in);//To take input from keyboard
        String pin;

        do{
            System.out.print("Enter PIN Number:");
            pin = scan.next();
            
            if(pin.equals("1245")){
                /*1245 is the PIN Number associated with your account. This PIN Number is
                saved in some database. For simplication we have assumed that the PIN Number is 1245 */
                System.out.println("Login Successful");
            }else{
                System.out.println("Incorrect PIN.");
            }
            numbersOfAttemptsLeft--;
        }while(!pin.equals("1245") && numbersOfAttemptsLeft>0);
        scan.close();
    }
}

Output

Enter PIN Number:1234
Incorrect PIN.
Enter PIN Number:1290
Incorrect PIN.
Enter PIN Number:1245
Login Successful
Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article