Good weekend everyone! I really hope you are enjoying your free time!
In case you are feeling bored, feel free to deep dive into this new episode of Learn2Code.
Last time, we talked about arrays. Today, our side quest in the world of coding brings us to familiarize with iterations. What are they? How do they work? Which are the different types of iterations available to C++ programmers?
Let’s dive in!
Overview
As the name suggests, iterations allow a programmer to repeat the same piece of code multiple times without having to write the same lines hundreds of time.
Let’s make a very simple example. Suppose we would like to add 1 to our variable 100 times. Without iterations, our code would look something like this:
// 1st
var = var + 1;
// 2nd
var = var + 1;
.
.
.
// 100th
var = var + 1;Not super user-friendly, right? That’s why many programming languages, C++ included, created special statements to run the same lines over and over.
Consider supporting this newsletter by using one of my affiliate links. These are not sponsorships, just products I use everyday. Thank you!
Iterations in C++
There are three main kinds of iterations in C++: for, while and do-while loops.
For Loops
This type of loop iterates through a collection of values, for example and array or a vector. for is usually used when the number of iterations is known before-hand.
A classic example is iterating through an array:
int array[3] = { 1, 5, 7};
for(int i = 0; i < 3; i++) {
std::cout << "Array value: " << array[i] << std::endl;
} The console output would read:
Array value: 1
Array value: 5
Array value: 7While Loops
This type of loop enables the execution of a certain code until a certain condition remains true. A real-life example could be “While there are still dirty dishes in the sink, pick one and clean it”.
From the coding standpoint, it could look like this:
std::vector dirty_plates(5);
while (dirty_plates.size() != 0 ) {
cleanPlate();
removePlateFromVector();
}The code will exit the while loop once the dirty_plates size reaches 0.
Do-While Loops
This final type of loop is very similar to the previous one, but with a slight difference. The do-while loop always allows for a first execution of the statement (do) before checking the condition (while).
std::vector dirty_plates(5);
do {
cleanPlate();
removePlateFromVector();
} while (dirty_plates.size() != 0 );It is not very different, but keep in mind that you have to be sure that dirty_plates contains at list one element, otherwise you will encounter an error.
Aaaand that’s it for today.
We will do a proper deep dive of each loop type in the next episodes of Learn2Code, so that we will be able to properly understand their functioning.
Cheers!
Let’s keep in touch:
Check out my writings on btc++ insider edition
Try my new app Sats Tracker, an expense tracker app for people living in the Bitcoin standard.
Zap me a coffee and leave me a message: tuma@wallet.yakihonne.com


