How do cycles work in C++?
Cycles are a fundamental tool in programming languages, and in C++ they allow us to iterate a block of code over a list or a numerical range. For example, if we want to perform an operation on each element of a list of numbers, cycles facilitate this repetitive process. Here I will guide you through the basics of for-cycles in C++.
What is a for loop?
A for loop is an instruction that allows you to repeatedly execute a block of code a specified number of times. In C++, this structure is useful for iterating over numeric ranges or over lists, allowing us to execute the same code multiple times efficiently.
Basic syntax of a for loop
The basic structure of a for loop in C++ is as follows:
for(int i = 0; i < 10; i++) { }
- Initialization: We declare and initialize a variable, usually
int i = 0
.
- Condition: We evaluate a condition (e.g.
i < 10
) that must be true for the loop to continue.
- Increment: We increment the value of the variable (e.g.
i++
is i = i + 1
).
Within the code block, we can use this variable for specific operations. For example, print its value at each iteration:
std::cout << i << std::endl;
How to iterate with a variable limit?
Sometimes, the limit of iterations is not a fixed number. We can use variables to set this limit, which adds flexibility to the loop.
int limit;std::cout << "Limit: ";std::cin >> limit;
for(int i = 0; i < limit; i++) { std::cout << i << std::endl;}
With this structure, the program asks the user how many iterations to perform.
How to iterate over lists?
For cycles also help us to perform operations on each element of a list. Let's see how to multiply each element by two:
int list[] = {100, 200, 300};
for(int i = 0; i < sizeof(list)/sizeof(list[0]); i++) { std::cout << list[i] * 2 << std::endl;}
Here, we use sizeof
to determine the size of the list by dividing it by the size of an element in bytes.
How to break a for loop?
We can use the break
statement to exit a for loop under certain conditions. For example, we want to stop when we find the number 200:
for(int i = 0; i < sizeof(list)/sizeof(list[0]); i++) { if(list[i] == 200) break; std::cout << list[i] << std::endl;}
When the number 200 is encountered, the loop is interrupted thanks to the break
instruction.
How can I practice?
A great way to practice is to do practical exercises that challenge you to implement what you have learned. For example, try writing a loop that only displays even numbers from a list using conditionals.
With these basics of C++ for loops, you are ready to continue exploring the possibilities this language has to offer. Keep learning and experimenting with these structures!
Want to see more contributions, questions and answers from the community?