C++ Control Statement - For Loop
The for
loop is a control statement that allows a block of code to be repeated a fixed number of times. It is also known as a counting loop, as it executes a preset number of iterations, specified by the user.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed repeatedly
}
initialization
: initializes the loop counter variablecondition
: specifies the condition for loop terminationincrement/decrement
: updates the loop counter variable after each iteration
Example:
#include <iostream>
using namespace std;
int main() {
for(int i=1; i<=5; i++) {
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5
Explanation:
In the above example, the loop is initialized with i=1
. The condition i<=5
specifies that the loop should continue until i
is less than or equal to 5. After each iteration, i
is incremented by 1 using i++
. The output shows the values of i
from 1 to 5.
Use:
The for
loop is commonly used in programs for iteration and repetition of certain actions. It is used in situations when we know the exact number of times a block of code should be executed.
Important Points:
- The initialization, condition, and increment/decrement are all optional.
- The body of the loop can contain any valid C++ statements, including nested loops and other control statements such as
if
andswitch
. - The
break
statement can be used to terminate the loop early, while thecontinue
statement can be used to skip a certain iteration.
Summary:
- The
for
loop is a control statement that executes a block of code a fixed number of times. - It has an initialization, condition, and increment/decrement.
- It is commonly used in situations when we know the exact number of times a block of code should be executed.
- Other control statements such as
if
andswitch
can be nested within afor
loop. - The
break
andcontinue
statements can be used to terminate the loop early or skip a certain iteration.