A for loop in C++ is a control structure that allows executing a block of code a specific number of times. It is one of the most commonly used control structures.
If you want to learn more, check out the Introduction to Programming Course
Basic Syntax
The syntax of a for loop in C++ consists of three main parts: initialization, condition, and update.
These parts are specified within the parentheses of the for loop and are separated by semicolons.
for (initialization; condition; update)
{
// Instructions to execute in each iteration
}
Initialization: Used to set the initial values of the variables that will control the loop. Typically, it’s used to initialize a counter.Condition: A boolean expression that is evaluated before each iteration. If the condition is true, the loop continues executing; if false, the loop exits.Update: An action performed to modify the value of the loop control variables. Usually used to increment or decrement a counter.Instructions to execute: Here, the actions to be performed in each iteration of the loop are specified.
Basic Example
Let’s look at a simple example where we use a for loop to print numbers from 1 to 10:
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++)
{
std::cout << i << std::endl;
}
return 0;
}
In this example:
- The initialization
int i = 1sets the initial value ofito 1. - The condition
i <= 10ensures the loop executes whileiis less than or equal to 10. - The update
i++incrementsiby 1 after each iteration. - Inside the loop, we use
std::coutto print the current value ofito the console.
The result is that numbers from 1 to 10 will be displayed on the screen.
Modifying Loop Flow
Skipping Iterations with continue
The continue statement is used to skip the current iteration and proceed directly to the next iteration of the loop.
#include <iostream>
int main() {
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
std::cout << i << std::endl;
}
return 0;
}
Breaking the Loop with break
The break statement allows exiting the loop before the condition is met. This is useful when a specific value is found and further iteration is unnecessary.
#include <iostream>
int main() {
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i is 5
}
std::cout << i << std::endl;
}
return 0;
}
Special Cases
Using External Variables
It is possible to use a variable declared outside the for loop as the control variable. This can lead to confusion if not handled properly:
#include <iostream>
int main() {
int i = 0;
for (i = 0; i < 5; i++)
{
std::cout << i << std::endl;
}
std::cout << "Value of i after the loop: " << i << std::endl;
return 0;
}
In this case, i retains its value after the loop has finished, which will be 5.
Multiple Declarations
In the initialization and update sections, you can include multiple statements separated by commas. This is useful when multiple control variables are needed:
#include <iostream>
int main() {
for (int i = 0, j = 10; i < j; i++, j--)
{
std::cout << "i: " << i << ", j: " << j << std::endl;
}
return 0;
}
Practical Examples
Generate a Multiplication Table
In this example, we generate a multiplication table for a specific number using a for loop.
#include <iostream>
int main() {
int number = 5; // Number for which the multiplication table is generated
for (int i = 1; i <= 10; i++) // Iterate from 1 to 10
{
std::cout << number << " x " << i << " = " << number * i << std::endl; // Print the multiplication of the number by 'i'
}
return 0;
}
Iterating Over Arrays
One of the most common applications of the for loop is iterating over the elements of an array. Here is an example that sums all elements of an array:
#include <iostream>
int main() {
int numbers[] = { 1, 2, 3, 4, 5 }; // We declare the array
int sum = 0; // Variable to store the sum
for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
{
sum += numbers[i]; // Add each element of the array to 'sum'
}
std::cout << "The sum of the elements is: " << sum << std::endl;
return 0;
}
Iteration with a Different Step
The update value doesn’t always have to be an increment of one. It can be any expression that modifies the control variable. For example, iterating in steps of two:
#include <iostream>
int main() {
for (int i = 0; i < 10; i += 2) // Increment 'i' by 2 in each iteration
{
std::cout << i << std::endl; // Print the current value of 'i'
}
return 0;
}
Decrementing For Loop
The for loop can also be used to iterate in descending order:
#include <iostream>
int main() {
for (int i = 10; i > 0; i--) // Decrement 'i' by 1 in each iteration
{
std::cout << i << std::endl; // Print the current value of 'i'
}
return 0;
}
Searching for an Element in an Array
#include <iostream>
int main() {
int numbers[] = { 1, 2, 3, 4, 5 }; // We declare the array
int search = 3; // Number to search for
bool found = false; // Variable to indicate if the number was found
for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
{
if (numbers[i] == search) // Compare each element with the searched number
{
found = true; // Mark that the number was found
break; // Exit the loop
}
}
if (found)
{
std::cout << "The number " << search << " is found in the array." << std::endl;
}
else
{
std::cout << "The number " << search << " is not found in the array." << std::endl;
}
return 0;
}
These examples are intended to show how to use the FOR loop. This does not mean it’s the best way to solve the problem they address. Usually, there are better alternatives.
