In C++, a for loop is used to repeat a block of code a certain number of times. It consists of three main parts:
Note :- The most common form of loop is the for loop.
1. Initialization: This part is executed once at the start of the loop. It usually initializes a counter variable.
2. Condition: This is evaluated before each iteration. If it evaluates to true, the loop continues; if false, the loop terminates.
3. Increment/Decrement: This part is executed after each iteration. It typically updates the counter variable.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
Example:
#include <iostream>
using namespace std;
int main() {
// for loop starts with initialization of i = 1, continues while i <= 5, and increments i by 1 each time
for (int i = 1; i <= 5; i++) {
cout << i << endl; // prints the value of i in each iteration
}
return 0;
}
Output:
2
3
4
5
Explanation:
- Initialization: int i = 1 initializes the loop variable i to 1 before the loop starts.
- Condition: i <= 5 checks whether i is less than or equal 5. If this condition is true, the loop executes; if false, the loop exits.
- Increment: i++ increases the value of i by 1 after each iteration.
Example: Print the table of 2 through for loop
#include <iostream>
using namespace std;
int main() {
for (int i = 2; i <=20; i=i+2)
{
cout << i << endl;
}
return 0;
}
Output:
4
6
8
10
12
14
16
18
20
C++ for loop – Interview Questions
Q 1: What is a for loop?
Ans: A loop used for fixed number of iterations.
Q 2: How many parts does a for loop have?
Ans: Initialization, condition, increment/decrement.
Q 3: Can initialization be skipped?
Ans: Yes.
Q 4: Can we use multiple variables in for loop?
Ans: Yes.
Q 5: Is for loop entry-controlled?
Ans: Yes.
C++ for loop – Objective Questions (MCQs)
Q1. What is the correct syntax of a for loop in C++?
Q2. How many times will this loop execute?
for(int i = 0; i < 5; i++)
cout << i;
Q3. Which of the following statements about the for loop is TRUE?
Q4. What will be the output of the following code?
for (int i = 1; i <= 3; i++)
cout << i << " ";
Q5. What happens if the condition in a for loop is always true?