How do C++ for loops work?
For loops are a fundamental concept of most programming languages. They are used to execute blocks of code repeatedly. There are several variants of C++ for loops, but they all work similarly.
What are C++ for loops?
A for loop is one of the most important control structures within programming. It allows developers to execute certain blocks of code multiple times. It is impossible to imagine iterative programming languages without loop constructs, for example for loop in Java as well as for loops in Python. Other programming languages, especially functional ones, use the concept of recursion instead of loops.
C++ for loops
The most common C++ for loops consist of three main elements:
- Initialization: This is where the loop variable is initialized. This means that an initial value is assigned to it.
- Condition: Here a condition is checked. As long as this condition is true, the loop body is executed.
- Statement: Here you can formulate any statement. Normally, the loop variable is decremented- or incremented.
All these elements are specified in the loop header where they are separated by semicolons. C++ for loops are also referred to as head-driven loops since all the elements are completed before the actual loop body is even executed.
A simple example of a C++ for loop, with which the numbers from 0 to 5 are output on the screen, could look like the following:
for (int i = 0; i <= 5; i++) {
std:cout << i << std:endl;
}
C++The first line of this code example contains the loop header. Here it becomes clear which elements a C++ for loop consists of:
- Initialization: By specifying the statement “int i = 0”, a variable named “i” is created and assigned the value 0.
- Condition: By specifying the condition “i <= 5”, it is indicated that the loop body should be executed until the value of “i” exceeds the number 5.
- Instruction: Within each loop pass (referred to as an iteration) the value of “i” is incremented by 1.
It is possible to omit the condition part of the for loop. In these cases, the condition is assumed to always be true, and you create an infinite loop. Sometimes infinite loops can be helpful, however, infinite loops can sometimes be created by mistake, resulting in errors. This often happens when learning C++.
C++ foreach loops
C++11 introduced another loop form in C++, which is created with the keyword “for”. In other programming languages such as PHP or C# or C++++, such constructs are also known as “foreach loops”. With these loops, you can conveniently access any element of a data structure without having to use indexing. The example below outputs numbers from 0 to 5:
int intArr[] = {0, 1, 2, 3, 4, 5};
for (int element: intArr) {
std:cout << element << std:endl;
}
C++As you can see, the structure of the loop header has changed when compared with the first code example. Instead of initialization, condition and statement, there are only two components:
- Element: Here you specify the data type and a variable name.
- Container: Here you specify which container should be repeated.
In our example, we first created an array that contains the numbers from 0 to 5. Then, inside the C++ for loop, using the variable named “element”, each element of the array was looked at and output to the screen in the loop body.
Use the IONOS Webspace to put all your C++ programs online. Comprehensive backups ensure that your programs are always protected against data loss.
What are C++ for loops used for?
For loops are used whenever the number of loop passes is known in advance. For example, if you want to output all multiples of the number 2 to 100, your C++ for loop might look like this:
for (int i = 2; i <= 100; i+=2) {
std:cout << i << std:endl;
}
C++Many well-known sorting algorithms also work with for loops. The main advantage compared to while loops is the compact notation. You can replace for loops with while loops at any time.
How to break loops with the break statement
There may be times when you want to exit your C++ for loop prematurely. This can happen, for example, if you want to create an infinite loop that outputs integers to the screen until a number entered by the user is reached. As the following code example illustrates:
int i = 0;
int user input = 0;
// User enters a number that is assigned to the variable named user input
std::cin >> user input
for (;;) {
std:cout << i << std:endl;
++i;
// Abort if the loop variable is greater than the number entered by the user
if (i > user input) {
break;
}
}
C++The keyword that causes the loop to end in the code example above is “break”. With break, any C++ for loop is terminated immediately. The program then simply continues after the loop.
How to skip loop passes with the continue statement
You may not want to directly terminate the entire loop, but instead only skip individual loop passes. For example, if you want to output all even numbers up to the number 100, you could use the following loop construct:
for (int i = 0; i <= 100; i++) {
// Jump to next iteration if number is odd
if (i % 2 == 1) {
continue;
}
std:cout << i << std:endl;
}
C++The keyword “continue” in the code example ensures that the current loop pass is aborted, and the program jumps to the next loop pass. This allows you to avoid unnecessary calculations, which improves the efficiency of your programs.