Skip to main content

Loops

Introduction

Loops are essential in any programming language, including C++. They allow for the repetition of a block of code until a specified condition is met. In C++, there are three types of loops:

  1. for loop
  2. while loop
  3. do while loop

This tutorial will introduce you to these loops, how they work, and when to use each type.

for Loop

The for loop is used when you know how many times you want to iterate a block of code. Here is the syntax:

for(initialization; condition; increment/decrement) {
// code to be executed
}
  • initialization: This statement is executed only once at the beginning. It's generally used to initialize the counter variable.
  • condition: This is the test condition that is evaluated before each loop iteration. If the condition is true, the body of the loop is executed. If it's false, the body of the loop doesn't execute and flow of control jumps to the next statement after the for loop.
  • increment/decrement: It is executed each time after the block of code has been executed.

Here is an example of a for loop:

for(int i = 0; i < 5; i++) {
cout << i << "\n";
}

In this example, the loop will print the numbers 0 through 4.

while Loop

The while loop is used when you want to repeat a block of code an unknown number of times until a specific condition is met. Here is the syntax:

while (condition) {
// code to be executed
}

Here is an example of a while loop:

int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}

In this example, the loop will print the numbers 0 through 4, same as the for loop example.

do while Loop

The do while loop is similar to the while loop but with a key difference - the do while loop will execute the block of code once before checking the condition. Then it will repeat the loop as long as the condition is true. Here is the syntax:

do {
// code to be executed
} while (condition);

Here is an example of a do while loop:

int i = 0;
do {
cout << i << "\n";
i++;
} while (i < 5);

Again, this will print the numbers 0 through 4.

Conclusion

Loops in C++ are a powerful tool that let you repeat a block of code as many times as you need. The for loop is best when you know ahead of time how many times the loop needs to run, while the while and do while loops are better when the number of iterations depends on a condition that will change over the course of the program. The key difference between while and do while is that do while executes the block of code at least once before checking the condition.