What are Loops in C++?
Loops in C++ are used to execute a block of code repeatedly as long as a given condition is true. Instead of writing the same code multiple times, loops allow us to run it again and again automatically.
A loop first checks a condition, and if it is true, the code inside the loop executes. This process continues until the condition becomes false. Loops help in making programs short, efficient, and easy to manage.
Types of Loops in C++
- while loop → Executes while condition is true
- do-while loop → Executes at least once
- for loop → Used when number of iterations is known
Why Do We Use Loops?
- To repeat a task multiple times.
- To reduce code repetition.
- To make programs easier and faster.
- To handle large data easily.
How Loop Works?
- First, a condition is checked.
- If the condition is true, the loop runs.
- After execution, the condition is checked again.
- This continues until the condition becomes false.
Note:If condition is always true, it becomes an infinite loop.
Simple Example
#include <iostream>
using namespace std;
int main() {
int n, i = 1;
cout << "Enter number: ";
cin >> n;
while (i <= n) {
cout << i << endl;
i++;
}
return 0;
}
Output:
Enter number: 5
1
2
3
4
5
Explanation:
- The user enters n = 5.
- The loop starts from i = 1.
- The condition i <= n is checked.
- Numbers from 1 to 5 are printed.
- i++ increases the value each time.
- After printing 5, i becomes 6.
- Now the condition 6 <= 5 becomes false, so the loop stops.
Summary:
- Loops are used to repeat a block of code.
- They reduce code length and improve efficiency.
- C++ provides while, do-while, and for loops.