What makes computers so wonderful? They think quickly and never tire of repetitive tasks. Imagine having an array that contains the entire alphabet, and you want to print it line by line. Or even an array with 1000 or even a million values. If you had to manually print everything, I believe you would quickly grow tired of writing code. That's where loops come to the rescue!
In this topic, let's explore the most popular loop in programming: the for loop. It allows you to automate repetitive tasks and iterate over arrays or ranges of values without the need for manual repetition. With the for loop, you can harness the power of computers to handle large amounts of data effortlessly.
The basic for-loop syntax
The for-loop has the following basic syntax:
for (initialization; condition; modification) {
// do something
}
Parts of the loop:
- the initialization statement is executed once before the loop begins; usually, loop variables are initialized here;
- the condition is a Boolean expression that determines the need for the next iteration; if it's
false, the loop terminates; - the modification is a statement that changes the value of the loop variables; it is invoked after each iteration of the loop; usually, it uses increment or decrement to modify the loop's variable.
Inside the loop's body, the program can perform any correct C++ statements. It can even contain other loops.
The order of execution for any for-loop is always the same:
- the initialization statement;
- if the condition is
falsethen terminate the loop; - if the condition is
true, then the loop's body is executed; - the modification is performed;
- go to stage 2 (condition).
Let's write a loop for printing integer numbers from 0 to 9 on the same line.
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
std::cout << i << ' ';
}
return 0;
}
This code displays:
0 1 2 3 4 5 6 7 8 9
You declared the iterative variable i in the loop, and each time the loop is executed, you increase it by 1 (i++). And you will display its value on the screen when your variable is less than 10 (i < 10).
i, j, k, or index. Here's another example. Let's calculate the sum of the integer numbers from 1 to 10000 (inclusive) using the for-loop:
#include <iostream>
int main() {
int sum = 0;
for (int i = 1; i <= 10000; i++) {
sum += i;
}
std::cout << "The sum is: " << sum << std::endl;
return 0;
}
The code displays:
The sum is: 50005000
Here you carry out the same actions, only the termination conditions have changed a little (i <= 10000) and inside the loop, you do not display the result, but summarize it (sum += i;).
Let's take the problem a little more difficult and at the same time remember what you went through before. Let's write a loop for printing the English alphabet:
#include <iostream>
int main() {
char alphabet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int alphabetSize = sizeof(alphabet) / sizeof(alphabet[0]);
int lettersPerLine = 4;
for (int i = 0; i < alphabetSize; i++) {
std::cout << alphabet[i] << ' ';
if ((i + 1) % lettersPerLine == 0) {
std::cout << '\n';
}
}
return 0;
}
Do not rush to read further; carefully study the example. Do you understand everything? In this example, you have concentrated a large number of everything that you have already learned (if, %, size, array, cout). Play around with codes in your IDE. If everything is clear, let's move on.
Skipping parts
The initialization statement, the condition, and the modification parts are optional, the for loop might not have all of them.
It is possible to declare a variable outside the loop:
int i = 10;
for (; i > 0; i--) {
std::cout << i << " ";
}
Moreover, it is also possible to write an infinite loop without these parts at all:
for (;;) {
// do something
}
But be very careful with such experiments, you need to clearly understand what you are doing and how to stop it!
Nested loops
It's possible to nest one for-loop in another for-loop. This approach is used to process multidimensional structures like tables (matrices), data cubes, and so on.
For example, the following code prints the multiplication table of numbers from 1 to 9 (inclusive).
#include <iostream>
int main() {
for (int i = 1; i < 10; i++) {
for (int j = 1; j < 10; j++) {
std::cout << i * j << "\t";
}
std::cout << std::endl;
}
return 0;
}
It outputs:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
for loops (as well as other types of loops) is the off-by-one error. This error occurs when the loop iterates one time more or one time less than the desired number of iterations. It usually happens because an incorrect comparison operator is used in the loop condition (for example, > instead of >=, or vice versa). These errors are often difficult to detect as the compiler will not complain about them, and the program will run, but the results will be incorrect.
When writing for loops, it's important to remember that the loop will continue executing as long as the condition is true. It is recommended to test loops using different values to verify their functionality. It is good practice to test loops with various input data (numbers, characters, etc.) that force the loop to execute 0, 1, and 2 times. If the loop operates correctly in these scenarios, then everything is okay.
Range-based for loop in C++ (foreach)
In addition to the traditional for loop, C++ also provides a convenient alternative called the range-based for loop. The range-based for loop offers a simplified syntax for iterating over elements in a range, such as arrays, containers, or even custom data structures.
It simplifies the code and enhances readability, especially when dealing with complex data structures.
The syntax of the range-based for loop is as follows:
for (element_declaration : range) {
// Code to be executed for each element in the range
}
Here, element_declaration is a declaration that defines a variable to hold each element in the range. The range represents the collection or sequence of elements to be iterated over.
Here's an example that demonstrates the range-based for loop by iterating over an array of integers:
#include <iostream>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int number : numbers) {
std::cout << number << " ";
}
return 0;
}
In this example, the range-based for loop iterates over each element in the numbers array and prints its value. The loop automatically assigns each element to the variable number, which can be used within the loop body.
The range-based for loop offers several benefits:
- Simplicity: The loop syntax is concise and easy to read, reducing the chance of introducing errors associated with manual indexing.
- Automatic Iteration: The loop automatically iterates over each element in the range, making it ideal for scenarios where you want to access every element without worrying about indexes or iterators.
Foreach loop and auto keyword
Since the declared element in the foreach loop must be of the same type as the array elements, it is an ideal scenario to use the auto keyword, allowing C++ to deduce the data type of the array elements for us. For example:
#include <iostream>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (auto number : numbers) {
std::cout << number << " ";
}
return 0;
}
By utilizing the auto keyword, you simplify the process of iterating over array elements and eliminate the need for manual type declarations, making the code more readable and maintainable.
auto keyword appeared in C++11Conclusion
You've covered two of the four loops in C++ in detail.
The for loop provides a compact and structured way to iterate over a range of values, making it suitable for scenarios where the number of iterations is known or can be determined in advance.
Additionally, you explored the range-based for loop, also known as the foreach loop, which simplifies iterating over elements of an array or container. By utilizing the auto keyword, you allow the compiler to deduce the data type of the elements automatically, making the code more concise and flexible.
Understanding and effectively using loops in C++ is essential for writing efficient and organized code. By carefully designing loop structures and considering potential pitfalls such as off-by-one errors, you can harness the power of loops to automate repetitive tasks, process data collections, and create complex algorithms.
Remember to test your loops with various input values to ensure their correctness and efficiency. Regular practice and experience will further enhance your skills in working with loops and mastering the art of writing efficient and maintainable code.