05 - Loops
05 - Loops
Lecture 5
Loops in C++
2
Types of Loops in C++
- C++ provides three primary loop constructs:
1. for loop
2. while loop
3. do-while loop
3
for Loop
- Example:
4
Example
- Reverse counting
5
Example
- Print even numbers from 1 to 20
6
Example
- Sum of squares
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i * i;
}
cout << "Sum of squares = " << sum;
7
while Loop
while (condition) {
// statements
}
- Example
int i = 1;
while (i <= 5) {
cout << "Count: " << i << endl;
i++;
}
- The number of iterations is not known in advance and depends
on a condition. 8
Example
int number;
cout << "Enter numbers (0 to stop): ";
cin >> number;
while (number != 0) {
cout << "You entered: " << number << endl;
cin >> number;
}
9
do-while Loop
do {
// statements
} while (condition);
- Example
int i = 1;
do {
cout << "Count: " << i << endl;
i++;
} while (i <= 5);
string password;
do {
cout << "Enter password: ";
cin >> password;
} while (password != "admin123");
11
Exercise
- Write a program to calculate the sum of numbers from 1 to n
using a loop.
12
Exercise
- Write a program to calculate the sum of numbers from 1 to n
using a loop.
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "Sum = " << sum;
13
Exercise
- Write a program to print the multiplication table of a number.
- Write a program to find the factorial of a given number using a
loop.
14