CPP Tutorial



C++ LOOPS


Loops in C++

Loops allow you to execute a block of code repeatedly based on a condition. They help avoid code duplication and make your programs efficient and easier to maintain. C++ provides several types of loops for different scenarios.

Why Use Loops?

  • Repeat code multiple times without rewriting it.
  • Process data collections like arrays, lists, or ranges.
  • Create infinite loops for servers or event-driven programs (carefully!).

Types of Loops in C++

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

1. For Loop

The for loop is used when you know beforehand how many times you want to repeat a block of code.

Syntax:

for (initialization; condition; update) {
    // statements to repeat
}
  

Example:

#include <iostream>
using namespace std;

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

- i = 1 initializes the loop counter.
- i <= 5 is the loop continuation condition.
- i++ increments the counter after each iteration.


2. While Loop

The while loop repeats a block of code as long as a specified condition is true. It is useful when the number of iterations is not known in advance.

Syntax:

while (condition) {
    // statements to repeat
}
  

Example:

#include <iostream>
using namespace std;

int main() {
    int count = 1;
    while (count <= 5) {
        cout << "Count: " << count << endl;
        count++;
    }
    return 0;
}
  

- The loop runs while count is less than or equal to 5.
- Increment count inside the loop to avoid infinite loops.


3. Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body executes at least once before the condition is checked.

Syntax:

do {
    // statements to repeat
} while (condition);
  

Example:

#include <iostream>
using namespace std;

int main() {
    int number = 1;
    do {
        cout << "Number: " << number << endl;
        number++;
    } while (number <= 5);

    return 0;
}
  

- The code inside do runs once before the condition is checked.
- The loop continues as long as the condition is true.


Additional Notes:

  • Break Statement: You can use break; inside loops to exit the loop immediately.
  • Continue Statement: continue; skips the current iteration and jumps to the next iteration.
  • Infinite Loops: Loops without a terminating condition can cause your program to freeze. Always make sure loops eventually end.

Summary

Loop Type Use When Runs At Least Once?
for Known number of iterations No
while Unknown iterations, condition-checked before No
do-while Unknown iterations, condition-checked after Yes

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review