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 about Loops
consult the Introduction to Programming Course read more
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
: It is used to set the initial values of the variables that will control the loop. Typically, it is used to initialize a counter.Condition
: It is a boolean expression that is evaluated before each iteration. If the condition is true, the loop continues executing; if false, it exits the loop.Update
: An action is performed to modify the value of the loop control variables. It is generally 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 the 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 = 1
sets the initial value ofi
to 1. - The condition
i <= 10
ensures that the loop runs whilei
is less than or equal to 10. - The update
i++
incrementsi
by 1 after each iteration. - Inside the loop, we use
std::cout
to print the current value ofi
to the console.
The result is that the numbers from 1 to 10 will be displayed on the screen.
Modifying the Flow of the Loop
Skipping Iterations with continue
The continue
statement is used to skip the current iteration and jump 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;
}
Exiting 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 there is no need to continue iterating.
#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, multiple declarations can be included 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 the 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;
}
Iterating with a Different Step
The value of the update does not 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;
}
Decreasing for Loop
You can also use the for
loop to iterate in decreasing 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 aim to show how to use the FOR
loop. It does not mean that it is the best way to solve the problems they address. There are usually better alternatives.