Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Control Structures: Loops in C++

Introduction

Loops are fundamental control structures that allow you to repeat a block of code multiple times. In C++, there are three types of loops:

  • for loop
  • while loop
  • do-while loop

For Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts:

  • Initialization
  • Condition
  • Increment/Decrement

Here is the syntax of a for loop:

for (initialization; condition; increment/decrement) {
    // Code to be executed
}
                

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 5; i++) {
        cout << "i = " << i << endl;
    }
    return 0;
}
                
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
                

While Loop

The while loop is used when the number of iterations is not known and depends on a condition. The syntax is:

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

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    while (i < 5) {
        cout << "i = " << i << endl;
        i++;
    }
    return 0;
}
                
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
                

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once. The syntax is:

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

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    do {
        cout << "i = " << i << endl;
        i++;
    } while (i < 5);
    return 0;
}
                
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
                

Nested Loops

Loops can be nested inside other loops. This means you can have one or more loops inside another loop. The inner loop is executed completely every time the outer loop is executed once.

Example:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            cout << "i = " << i << ", j = " << j << endl;
        }
    }
    return 0;
}
                
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
                

Infinite Loops

An infinite loop is a loop that never terminates. This occurs when the loop's condition never evaluates to false. Be cautious with infinite loops as they can cause your program to hang.

Example:

#include <iostream>
using namespace std;

int main() {
    while (true) {
        cout << "This is an infinite loop" << endl;
    }
    return 0;
}
                

Conclusion

Loops are a powerful feature in C++ that allow you to execute code repeatedly. Understanding the different types of loops and their use cases is crucial for efficient programming. Remember to use loops wisely to avoid infinite loops and ensure optimal performance.