Java

For Loop In Java

Until a certain condition returns false, a for loop is used to continually carry out a collection of statements. For, while, and do-while are the three forms of fundamental loops available in Java. You will discover Java’s for loop in this course. With examples, you will also learn about endless for loops, nested for loops, and for loops that are upgraded.

Syntax of for loop:

for(initialization; condition ; increment/decrement)
{
   statement(s);
}

Initialization: Variables like the loop counter (often represented by I and j in loops) are initialized during the startup phase. Given that the variables may be initialized before the loop, this portion of the code is unnecessary. This just runs once at the beginning of the loop.

Condition: One of the key components of the loop is this. This condition specifies how long the loop should continue. Till the condition is false, the loop iterates endlessly.

Increment/Decrement: You can specify the increment or decrement of the loop counter in this section of the loop declaration. With this change, the loop counter value will eventually reach false, causing the loop to stop.

Statement: Until the loop comes to an end, the statements included in the loop body continue to run.

Flow of Execution of the for Loop

The interpreter constantly maintains track of which statement is scheduled to be executed when a program runs. This is referred to as the control flow or the program execution flow.

Step1: The initialization phase of the for loop only executes once since initialization occurs first in the for loop.

Step2: If the condition in the for loop is true, the statements inside the for loop body are performed. This evaluation occurs after each iteration. Once the condition returns false, the statements in the for loop are not executed, and control is instead passed to the statement that follows the for loop in the program.

Step3: The increment/decrement portion of the for loop, which changes the loop counter, runs after each execution of the for loop’s body.

Step4: The control moves directly to step two after the third step and reevaluates the condition.

Example: Simple for loop

This is a basic illustration of a for loop. In this section of the loop body, the value of the variable I is being shown. The loop ends when the condition i>1 returns false because we are employing the decrement operator, which causes the value of I to drop by one after each iteration of the loop.

class ForLoopExample {
    public static void main(String args[]){
         for(int i=10; i>1; i--){
              System.out.println("The value of i is: "+i);
         }
    }
}

This program’s output is:

The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

In the aforementioned program:
Initialization expression is int i=1.
condition i>1 (Boolean expression)
i- Operation of reduction

Java Nested for loop

Nested for loops are for loops inside other for loops. To further grasp the idea of a nested for loop, let’s look at an example. In this illustration, a nested for loop is being used to print a pattern.

public class JavaExample {
  public static void main(String[] args) {
    //outer loop
    for(int i=1;i<=6;i++){
      //inner loop
      for(int j=1;j<=i;j++){
        System.out.print("* ");
      }
      // this is to move the cursor to new line
      // to print the next row of the pattern
      System.out.println();
    }
  }
}

Output:

For Loop In Java

Infinite for loop

Unending loops are referred to as infinite loops. When the condition expression specified in the loop never returns false, this occurs. You may better see the significance of Boolean expression and coordination between increment and decrement operations by using the example below:

class ForLoopExample2 {
    public static void main(String args[]){
         for(int i=1; i>=1; i++){
              System.out.println("The value of i is: "+i);
         }
    }
}

Since the condition would never return false, this is an infinite loop. Since we are incrementing the value of I the initialization step sets the value of I to 1 so that it will always be greater than 1 (the Boolean expression: i>1) and never return false. This would ultimately result in the infinite loop scenario. In order to know if the loop will end at some point or not, it is crucial to observe the coordination between the Boolean expression and increment/decrement action.

Another instance of an endless for loop is as follows:

// infinite loop
for ( ; ; ) {
    // statement(s)
}

Example: Iterate an array using for loop

Here is another another for loop illustration. Here, the for loop is being used to iterate and show array items.

class ForLoopExample3 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0 too
         for(int i=0; i<arr.length; i++){
              System.out.println(arr[i]);
         }
    }
}

Output:

2
11
45
9

Enhanced For loop

Another approach to describe a loop is an enhanced for loop. This is particularly helpful if you wish to cycle through classes for arrays, ArrayLists, and other collections. Writing and reading this are simple.

Let’s use the same illustration as what we saw earlier. It is being rewritten using an improved for loop.

class ForLoopExample3 {
   public static void main(String args[]){
      int arr[]={2,11,45,9};
      for (int num : arr) {
         System.out.println(num);
      }
   }
}

Output:

2
11
45
9

Note: In the extended for loop in the example above, I specified the num as an int. Depending on the array’s data type, this will alter. For instance, the improved for loop for the string type might seem as follows:

String arr[]={"hi","hello","bye"};
for (String str : arr) {
         System.out.println(str);
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button