FOR LOOP IN Java

problem

You wish to use a repetition mechanism in your Java program and execute an action or set of actions more than once. One of the options is the vastly used for-loop. It helps us to use this mechanism when the number of iterations is known before hand. For example, we want to repeat an action 10 times or 100 times, etc. In this post we will see how to utilize it with examples.

SOLUTION

Let’s start by creating a simple for loop that iterates 10 times and prints the message stored in a String variable.

				
					package com.programmerabroad;

public class ForLoop {

    public static void main(String[] args) {

        String message = "Testing for loop";

        for(int i=0; i<10; i++) {
            System.out.println(message);
        }
    }
}

				
			
The code above will be executed 10 times and will print on the console the contents of the message variable followed by a new line each time. The for loop ends when the condition, in this case i < 10 becomes False. More specific, when i = 10 it will stop executing.
 
The output will look as follows:
 

OUTPUT

for-loop-output

NESTING loops

The for loops can also be nested, meaning that a for loop can appear inside a for loop resulting in more iterations. If for example insert the for loop above inside itself then it will be executed 100 times. That is because the inner one will be executed 10 times and the outer one 10 times each resulting in a multiplication of 10 x 10 = 100.

More depth about this analysis can be found in the asymptotic analysis of algorithms.

Nesting example of the two:

				
					package com.programmerabroad;

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

        for(int i=0; i<10; i++) {
            for (int k=0; k<10; k++) {
                System.out.print(k + "\t");
            }
            System.out.println();
        }
    }
}

				
			

OUTPUT

nested-for-loops

breaking loops

Let’s suppose a case that you wish to stop the loop sooner than it’s destined execution times. In the following example we will check when the counter reaches the value 5 and we will use the break keyword to “break” it. When the break is reached, the execution will jump right after the body of the for loop, in this case line 12.

				
					package com.programmerabroad;

public class BreakLoop {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
            if (i == 5) {
                break;
            }
        }
        System.out.println("For loop break");
    }
}

				
			

OUTPUT

break-for-loop

Using labels

On the for loops we can additionally add a label. A label can be used if for example we have a nested for loop and we wish to break the outer for loop. It can also be applied on the continue statement that appears below.

For example, below 2 labels are applied on the loops. The outer_loop on the outer for loop and the label inner_loop in the inner for loop. The if condition breaks the outer loop when the total iterations reaches 21.

				
					package com.programmerabroad;

public class LabelForLoop {

    public static void main(String[] args) {
        
        int iterations = 0;

        outer_loop:
        for (int i = 0; i < 10; i++) {
            inner_loop:
            for (int k = 0; k < 10; k++) {
                iterations = iterations + 1;
                if (iterations >= 21) {
                    break inner_loop;
                }
                System.out.print(iterations + "\t");
            }
            System.out.println();
        }
    }
}

				
			

OUTPUT

label-for-loop

continue in for loop

Another one keyword that can be used inside for loop (and other loops) is the continue statement. In the example below when the i is even number the continue is executed. This means that the program execution from line 11 it will jump at line 14 where the end of the for-loop body is and it will go up at line 9. If the condition i < 10 is True it will re-enter the for-loop body at line 10 and carry on line by line and so on.

				
					package com.programmerabroad;

public class ContinueForLoop {

    public static void main(String[] args) {

        int total = 0;

        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                continue;
            }
            total = total + 1;
        }
        System.out.println(total);
    }
}

				
			

Another one way of looking at the continue statement is that it will skip whatever follows it till the end of the for-loop body. In the case above it will skip the line 13 whenever the i is even. Since it’s iterating from 0 to 9 inclusive, the total will be added 5 times so the result will be simply 5. Without the continue statement it would have been 10.

OUTPUT

continue-for-loop

CONCLUSION

In this post we saw few examples of using the for-loop in Java. One of the most used repetition mechanisms in the language and in others. We also saw how for loops can be nested and additionally how the break and continue statements can be applied on the loop. If we’re done sooner with the action we can stop the for loop with the break keyword. If we wish to “skip” an iteration we can use the continue keyword.

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x