For Loops
A for
loop in C++ is a control structure used to repeat a block of code a fixed number of times.
It is ideal when the number of iterations is known in advance, such as iterating over array elements or performing a calculation a set number of times.
The for
loop consists of three parts: initialization, condition, and update.
These are placed inside parentheses and separated by semicolons.
Syntax
for (initialization; condition; update) {
// loop body
}
- Initialization: Sets up a loop control variable, such as
int i=0
- Condition: Evaluated before each iteration; loop continues with this is true
- Update: Modifies the loop control variable after each iteration
For example, to count from 1 to 5:
#include <iostream>
using namespace std;
int main(void){
for(int i=1; i <= 5; i++){
cout << i << " ";
}
cout << endl;
}
Prints this line:
1 2 3 4 5
Iterating over an Array
You can use a loop to access each element of the array values
using the index i
:
int values[4] = {10, 20, 30, 40};
for (int i = 0; i < 4; i++) {
cout << values[i] << endl;
}
Loop Control and Scope
The loop control variable, like int i
, is scoped to the loop if declared inside the for
statement.
It cannot be accessed outside the loop body:
for (int i = 0; i < 3; i++) {
cout << i << endl;
}
// i is not accessible here
If declared outside the loop, the variable persists after the loop ends.
Infinite Loops
If the condition is always true, the loop will run forever:
for (;;) {
// infinite loop
}
This is equivalent to while(true)
and should be used with caution.
Nested Loops
You can place one for
loop inside another to iterate over multi-dimensional data:
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
cout << "(" << row << "," << col << ") ";
}
cout << endl;
}
This prints a 3×4 grid of coordinates.
Reading Questions
- What are the three components of a
for
loop? - Write a
for
loop that prints the numbers from 10 down to 1. - How many times does the loop
for (int i = 0; i < 7; i++)
execute? - What happens if the condition in a
for
loop is always false? - Can you declare the loop control variable outside the
for
loop? What are the implications? - Write a nested for loop that prints a 2×3 grid of asterisks (
*
). - How would you use a
for
loop to sum the elements of an array?