For Looping

“For loop” is one of the most popular and significant concepts in Java.A “for” loop is a control flow statement in Java that is used to continually run a code block in response to a given condition. It’s similar to having a machine that keeps working on the same thing until a predetermined number of times or a specific condition is reached. It offers a clear and organized method for carrying out routine activities in your code. When you know how many iterations are needed, you can use the for loop.

In Java, a “for” loop has the following syntax:

for (initialization; condition; increment/decrement) {

// Code block to be executed repeatedly

}

Let’s dissect the various components of the “for” loop:

  1. Initialization: At the start of the loop, this section is only performed once. It is employed to initialize and set up the loop control variable(s) to a particular value. Usually, this is where you declare and initialize the loop control variable.
  2. Condition: Prior to each loop iteration, the condition is assessed. If the condition evaluates to true, the loop’s code block is executed; if not, the program moves on to the statement that comes after the loop.
  3. Update: Following each loop iteration, the update section is carried out. It is employed to change the loop’s control variable or variables in order to move the loop closer to ending. In this part, for instance, you can increase or decrease the loop control variable(s).
  4. Code block: As long as the condition evaluates to true, this code block will be run repeatedly. Any Java statements can be found in the code block, which will be run throughout each loop iteration.

Let’s look at a basic Java “for” loop example that publishes the numbers 0 through 5

public class For_Loop { 
     public static void main(String[] args) {
        for (int i = 0; i <= 5; i++) { 
           System.out.println(i);
        }
     }
}

Output:

0

1

2

3

4

5

Explanation:

  • The loop control variable i is initialized to 1 by using the formula int i = 1. If the value of i is less than or equal to 5, the condition “i <= 5” is met. The loop ends if this condition is not met; else, it continues
  •  Update: i++ raises the value of i by 1 after each iteration. The loop prints the values for each iteration for i = 1, i = 2, i = 3, i = 4, and i = 5 until the condition i <= 5 becomes false, at which point the loop breaks.

“For” loops can be used to iterate across collections and arrays as well as carry out other operations that call for repeated execution under particular conditions. It is possible to change the condition and the loop control variable(s) to suit your program’s needs.

Another Example:

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

Output:

2
4
6
8
10

Explanation:

for(int i = 2; i <= 10; i = i + 2): This for loop sets the value of a variable called i to 2. The loop will keep going as long as i is less than or equal to 10. After each iteration, the value of i will be incremented by 2 (due to i = i + 2). Because i = i + 2, the value of i will increase by 2 after each repetition. Within the body of the loop: Println(i) from System.out; Every time this line is executed, the value of i is printed to the console.

Let’s see what happens in each iteration:

Initial value of i: 2

2 is printed to the console.

Value of i: 4

4 is printed to the console.

Value of i: 6

6 is printed on the console.

Value of i: 8

8 is printed on the console.

Value of i: 10

10 is printed on the console.

Why is the for loop used?

  1. Iterating across a range of values: A for loop is a handy option when you need to carry out a particular task a predetermined number of times. A for loop makes it simple to define the range of values and repeat the code, for instance, if you want to print numbers between 1 and 10 or process data for a predetermined number of iterations.
  2. handling items in collections or arrays: Many times, arrays and collections contain several elements that you want to handle individually. It is easy to go through all the items and apply the identical operations to each one using a for loop. Minimizing repetitious code: You can include repetitious code inside a for loop to avoid writing it repeatedly. This makes your code less redundant and easier to maintain. It’s an application of the DRY (Don’t Repeat Yourself) philosophy.
  3. Counter-controlled looping: The number of iterations in the loop can be managed by using a loop control variable, which is typically an integer. This lets you carefully manage the program’s progress by enabling you to create a termination condition based on the value of the counter variable.
  4. Simplifying difficult jobs: By breaking up difficult activities into smaller, more manageable parts, a for loop can make the logic of addressing problems in more complicated settings simpler. It assists in decomposing the issue into manageable chunks and addressing each chunk inside the loop.
  5. Improving the readableness of code: Your code becomes more legible and expressive when you use a for loop. The loop’s structure makes it obvious that a repetitive activity is being carried out, which helps other developers understand the purpose of the code.

break and continue on with the keyword in the for loop:

break:

To entirely exit and terminate the loop early, utilize the break statement. When a loop hits a break statement, it ends immediately, and the program continues from the statement that comes after the loop.

Here’s an example of using break to put an end to a for loop when a specific condition is met:

public class For_Loop { 
   public static void main(String[] args) { 
      for (int i = 1; i <= 10; i++) { 
        if (i == 5) {
         break; // Terminate the loop when i is 5 
        } 
        System.out.println(i); 
      } 
   } 
}

Output:

1
2
3
4

In this example, the loop ends instantly when I reach 5. This is accomplished by executing the break command. Consequently, only the digits 1 through 4 are displayed.

continue:

By passing the remaining code in the current loop iteration and moving straight on to the next, one can utilize the continue statement. A loop skips the remaining code for the current iteration when it comes across a continue statement and starts the next iteration (if any) right away.

Here’s an example of how to bypass printing even numbers in a for loop by using continue:

public class For_Loop { 
  public static void main(String[] args) { 
     for (int i = 1; i <= 10; i++) { 
       if (i % 2 == 0) { 
       continue; // Skip even numbers 
       } 
      System.out.println(i); 
    } 
  } 
}

Output:

1
3
5
7
9

In this example, the System.out.println(i) statement is skipped and the continue statement is run when i is even. Only the odd numbers are printed as a result. It’s crucial to utilize continue and break sparingly to prevent writing complicated, difficult-to-maintain code.

When used correctly, these statements can help regulate the flow of the loop and increase the code’s efficiency.

Visited 1 times, 1 visit(s) today

Comments are closed.

Close