Loops in C++
What is a loop?
Loops allow you to repeat a block of code multiple times. They are useful when you need to run the same instructions multiple times.
Types of Loops:
- For Loop – Best for a known number of repetitions.
- While Loop – Runs while a condition is true.
- Do-While Loop – Runs at least once, then checks the condition.
Example: For Loop
This prints numbers from 1 to 5:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Number: " << i << endl;
}
return 0;
}
Example: While Loop
This loop continues while the condition remains true:
#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "Count: " << count << endl;
count++;
}
return 0;
}
Example: Do-While Loop
This always runs at least once:
#include <iostream>
using namespace std;
int main() {
int num = 1;
do {
cout << "Number: " << num << endl;
num++;
} while (num <= 5);
return 0;
}