Loops in c++
Loops in C++ – Complete Guide for Beginners
1. What is a Loop?
A loop is used to execute a block of code again and again until a condition becomes false.
Real-life example:
Brushing teeth every day until the day ends
Attending classes every day until semester ends
In programming, loops save time and reduce code repetition.
2. Why Loops Are Important in C++?
Avoid writing same code multiple times
Make programs shorter and cleaner
Required for arrays, patterns, searching, sorting
Used in almost every real program
3. Types of Loops in C++
C++ provides 3 main types of loops:
for loop
while loop
do-while loop
4. for Loop in C++
Syntax:
for(initialization; condition; update) {
// code
}
How it works:
Initialization runs once
Condition is checked
Code executes if condition is true
Update runs
Steps 2–4 repeat
Example:
for(int i = 1; i <= 5; i++) {
cout << i << endl;
}
Output:
1
2
3
4
5
When to use for loop?
When number of iterations is known
5. while Loop in C++
Syntax:
while(condition) {
// code
}
Example:
int i = 1;
while(i <= 5) {
cout << i << endl;
i++;
}
When to use while loop?
When number of iterations is unknown
6. do-while Loop in C++
Syntax:
do {
// code
} while(condition);
Example:
int i = 1;
do {
cout << i << endl;
i++;
} while(i <= 5);
Important Point:
Executes at least once even if condition is false
7. Difference Between Loops
| Feature | for | while | do-while |
|---|---|---|---|
| Condition check | Before | Before | After |
| Executes at least once | No | No | Yes |
| Best use | Known count | Unknown count | Menu programs |
8. Nested Loops
A loop inside another loop.
Example:
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
cout << "* ";
}
cout << endl;
}
Output:
* * *
* * *
* * *
9. Infinite Loop
A loop that never ends.
Example:
while(true) {
cout << "Hello";
}
How to stop?
Use
break
10. break Statement
Stops the loop immediately.
for(int i = 1; i <= 10; i++) {
if(i == 5) break;
cout << i << endl;
}
11. continue Statement
Skips current iteration.
for(int i = 1; i <= 5; i++) {
if(i == 3) continue;
cout << i << endl;
}
12. Common Mistakes by Beginners
Forgetting update statement
Wrong condition
Infinite loops
Using wrong loop type
13. Practice Questions
Print numbers from 1 to 100
Print even numbers
Reverse a number
Check prime number
Print star patterns
14. Interview Questions
Difference between while and do-while?
What is infinite loop?
When to use for loop?
What is nested loop?
15. Conclusion
Loops are the backbone of programming. Mastering loops makes you confident in C++ and prepares you for advanced topics like arrays, functions, and algorithms.

Comments
Post a Comment