AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

For loops in C++: for loops in C++

PARTAGEZ

For loops correspond to a fundamental concept in most programming languages. They allow you to execute blocks of code repeatedly. There are several variations of for loops in C++, but they all work more or less the same way.

How do for loops work in C++?

For loops are among the most important control structures in programming. They allow developers to execute specific blocks of code multiple times. Loop constructs are simply essential to iterative programming languages. For example, there are for loops in Java and for loops in Python. Other programming languages, mostly functional, prefer the concept of recurrence to loops.

for loops in C++

In C++, the most common for loops include three essential elements
:

  • The initialization part : it is used to initialize the loop variable, that is to assign it a starting value.
  • The conditional part: it is used to check a specified condition. If this one is filled, the “body” of the loop can be executed.
  • The instruction part : it allows to formulate any instruction. Generally, the loop variable is decremented or incremented.

All of these elements are separated by semicolons at the head of the loop, and are therefore executed before the loop body itself. Therefore, for loops in C++ are also referred to as header-controlled loops.

We will now show you a simple example of a for loop in C++, which displays the numbers from 0 to 5 on the screen:

for (int i = 0; i <= 5; i++) {
	std:cout << i << std:endl;
}

C++

In the sample code above, the first line contains the loop header. It allows us, once again, to clearly see the elements that make up a for loop in C++:

  • The initialization part: with the instruction “int i = 0”, a variable named “i” is created, and the value 0 is assigned to it.
  • The conditional part: specifying the condition “i <= 5" indicates that the body of the loop must be executed until the value of the variable i exceeds the number 5.
  • The instruction part: each time the loop is executed (called an “iteration”), the value of the variable i increases by 1.

Note that it is possible to leave out the conditional part of the for loop. If this is the case, the condition is assumed to apply in perpetuity, which makes it possible to create an infinite loop. These infinite loops can sometimes be useful, but beginners learning to master the C++ language often create them by mistake, resulting in program errors.

foreach loops in C++

In addition to the for loops that we have already presented to you, there exists in the C++ language, and this, since version C++11, another form of loop also introduced by the keyword “for”. In other programming languages ​​such as PHP or C++++, these constructs are also called “foreach loops”. These allow toeasily access each element of a data structure, without having to use indexing. We have also chosen an example to display the 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 loop header structure is not the same as the first code example. Only two parts are used, instead of initialization, condition and statement:

  • Element : this part contains the data type and the name of the variable.
  • Container : this part specifies the container on which the iteration must take place.

We started by creating an array containing the numbers from 0 to 5. Within the for loop in C++, each part of the array was then visualized using the “element” variable and then displayed on the screen in the body of the loop.

What are for loops in C++?

In principle, for loops are always used when the number of loop iterations is known beforehand. For example, if you want to display all multiples of the number 2 up to 100, your for loop in C++ could look like this:

for (int i = 2; i <= 100; i+=2) {
	std:cout << i << std:endl;
}

C++

Numerous sorting algorithms famous also use for loops. Compared to while loops, their main advantage is their writingGOOD more compact. In fact, you always have the option of replacing for loops with while loops.

The break statement: to end loops

There may be times when you want to abort your for loop in C++ early, especially if you want to create an infinite loop to display integers on the screen until the user-specified number is reached. The sample code below illustrates this situation:

int i = 0;
int entrée utilisateur = 0;
// L’utilisateur renseigne un nombre qui sera affecté à la variable « entrée utilisateur »
std::cin >> entrée utilisateur
for (;;) {
	std:cout << i << std:endl;
	++i;
	// La boucle est interrompue si la variable est supérieure au nombre renseigné par l’utilisateur
	if (i > entrée utilisateur) {
		break;
}
}

C++

In the sample code above, ” break is the keyword that ends the loop. With this keyword, every for loop in C++ is immediately interruptedand program execution simply continues after the loop.

The statement continues: skipping iterations of the loop

Of course, you might not want to terminate the whole loop directly, but rather just skip some of its iterations. If your goal is, for example, to display all even numbers until you reach 100, you can achieve this using the loop construct below:

for (int i = 0; i <= 100; i++) {
// Permet de passer à l’itération suivante en cas de nombre impair
if (i % 2 == 1) {
		continue;
}
std:cout << i << std:endl;
}

C++

You may have spotted the keyword “ keep on going in the sample code; this one is watching the current iteration is canceled and the program goes to the next iteration of the loop. If this instruction is advantageous, it is mainly because it avoids unnecessary calculations, which improves the efficiency of your programs.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact