Explain for loop and give example in c++ , pythan and java with output

for loop

A for loop is a control flow statement that allows you to repeatedly execute a block of code for a specific number of times or until a certain condition is met. It is commonly used when you know the number of iterations you want to perform

The for loop consists of three essential parts:

  1. Initialization: This part is executed only once at the beginning of the loop. It is used to initialize the loop control variable or variables. The loop control variable is typically used to keep track of the current iteration.
  2. Condition: This part is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop is terminated, and the program continues with the next statement after the loop.
  3. Increment (or Decrement): This part is executed after each iteration of the loop body. It is used to update the loop control variable, usually by incrementing or decrementing its value. The loop control variable’s purpose is to control the flow and termination of the loop.

the general syntax of a for loop:

for (initialization; condition; increment/decrement) {
    // Code to be executed in each iteration
}

C++ example:

#include <iostream>

int main() {
    for (int i = 1; i <= 5; i++) {
        std::cout << "Iteration: " << i << std::endl;
    }
    return 0;
}

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

In this example, the for loop initializes i to 1. It continues executing as long as i is less than or equal to 5. After each iteration, i is incremented by 1. The loop prints the current value of i in each iteration.

Python example

for i in range(1, 6):
    print("Iteration:", i)

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

In Python, the range() function generates a sequence of numbers from the starting value (1) up to, but not including, the ending value (6). The for loop iterates over each value of i in the sequence and prints the corresponding iteration number.

Java example

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

This Java example is similar to the C++ example. The loop initializes i to 1, continues running while i is less than or equal to 5, and increments i by 1 after each iteration. The loop prints the current iteration number using System.out.println().

In all three examples, the loop executes five times, producing the output “Iteration: 1” through “Iteration: 5”.

Scroll to Top