Skip to main content

Control Flow

For Loop

for loop is also used to iterate a specific part of the code multiple times. When you know the exact number of iterations in advance, it is recommended to use for loop.

It's syntax is as follows -

for (initialization; condition; increment/decrement) {
    // code to be executed.
}

Let's try to understand the above syntax.

It starts with an initialization phase where a variable is set to a specific value. Then, it checks a condition, typically involving that variable. If the condition is true, it executes the code inside the loop. Afterward, there's an update phase where the variable is changed or incremented in some way.

The loop then reevaluates the condition. If it's still true, the loop continues, and the code inside is executed again. This cycle keeps repeating until the condition becomes false. Once the condition is false, the loop stops, and the program moves on to the next section of code.

If you find this concept difficult, don't worry! let's walk through an example using a for loop, similar to the one we explored with the while loop, to enhance your understanding.

We will use a for loop to achieve the same goal as before

class Main {
    public static void main(String[] args) {
 
        // declare numberOfTimes variable. 
        int numberOfTimes = 1;
    
        // code inside for loop will run 3 times.
        for (int numberOfTimes = 1; numberOfTimes <= 3; numberOfTimes++) {
            System.out.println("Code inside for loop is running.");
        }
    }
}

Output

Code inside for loop is running.
Code inside for loop is running.
Code inside for loop is running.

Explanation

Iteration i i <= 3< th> Body of Loop
1 1 true Code inside the loop is executed.
i++ increases i to 2.
2 2 true Code inside the loop is executed.
i++ increases i to 3.
3 3 true Code inside the loop is executed.
++i increases i to 4.
4 4 false The loop terminates.

Practice Problem

Write a code to to print odd numbers till number n using a for loop.

Java code
import java.util.*;

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

        System.out.println("Enter a number:");
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();

        System.out.println("Result -");
        for(int i = 1; i <= n; i = i + 2) {
            System.out.println(i);
        }
        
    }
}
Output
Enter a number:
10
Result -
1
3
5
7
9

Write a program to find a factorial of number n.

Factorial - The Factorial of a whole number 'n' is defined as the product of that number with every whole number less than or equal to 'n' till 1. For example, the factorial of 4 is 4 × 3 × 2 × 1, which is equal to 24. It is represented using the symbol '! ' So, 24 is the value of 4!.

Java code
import java.util.*;

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

        // calculate factorial of number.
        int number=5;   
        int fact=1;
        for(int i=1;i<=number;i++){    
            fact=fact*i;    
        }    
        System.out.println("Factorial of "+number+" is: "+fact);    
    }
}
Output
Factorial of 4 is: 24
Explanation
Iteration i factorial Operation
1 1 1 factorial = factorial * i (1 * 1 = 1)
2 2 1 factorial = factorial * i (1 * 2 = 2)
3 3 2 factorial = factorial * i (2 * 3 = 6)
4 4 6 factorial = factorial * i (6 * 4 = 24)

Here's the code explanation for each iteration:

  1. Iteration 1: The factorial is initially 1. With i equal to 1, factorial is updated to 1 * 1 = 1.
  2. Iteration 2: The factorial is 1 from the previous iteration. With i equal to 2, factorial is updated to 1 * 2 = 2.
  3. Iteration 3: The factorial is 2 from the previous iteration. With i equal to 3, factorial is updated to 2 * 3 = 6.
  4. Iteration 4: The factorial is 6 from the previous iteration. With i equal to 4, factorial is updated to 6 * 4 = 24.

By the end of the loop, the factorial of 4 is calculated as 24.Here's the code explanation for each iteration:

  1. Iteration 1: The factorial is initially 1. With i equal to 1, factorial is updated to 1 * 1 = 1.
  2. Iteration 2: The factorial is 1 from the previous iteration. With i equal to 2, factorial is updated to 1 * 2 = 2.
  3. Iteration 3: The factorial is 2 from the previous iteration. With i equal to 3, factorial is updated to 2 * 3 = 6.
  4. Iteration 4: The factorial is 6 from the previous iteration. With i equal to 4, factorial is updated to 6 * 4 = 24.

By the end of the loop, the factorial of 4 is calculated as 24.


Using if statement inside a loop

We will try to understand how can we use if statement inside a loop with the help of an example -

class Main {
    public static void main(String[] args) {
 
        // iterate from n = 1 to 9
        for (int n = 1; n < 10; n++) {
            
            // check if n is odd
            if (n % 2 == 1) {
                System.out.println(n);
            }
        }
    }
}

In the above example, we have a for loop that iterates from 1 to 9. Within each iteration, the code checks whether the current value of 'n' is an odd number. To perform this check, the condition 'n % 2 == 1' is used. If the condition evaluates to true, indicating that 'n' is indeed an odd number, the program proceeds to print the value of 'n' to the console. This process continues until the loop has iterated through all the values from 1 to 9. The output shows the odd numbers within this range: 1, 3, 5, 7 and 9.