Loops
Loops are essential programming constructs that allow repeated execution of a block of code. They enable automation and help reduce redundant code. In C++, there are three main types of loops: the for loop, the while loop, and the do-while loop. In this tutorial, we will explore each of these loops and provide examples to illustrate their usage.
For Loop
The for loop is often used when you know the number of iterations beforehand. It consists of an initialization expression, a condition, and an increment or decrement expression. Here is the syntax:
for(initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
Let's consider an example where we want to print the numbers from 1 to 5:
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
In this example, the loop initializes `i` to 1, checks if `i` is less than or equal to 5, and increments `i` by 1 after each iteration. The loop will execute five times, printing the numbers 1 to 5.
While Loop
The while loop is used when the number of iterations is unknown but depends on a condition. The condition is checked before each iteration. Here is the syntax:
while(condition) {
// code to be executed in each iteration
// make sure to include an update in the code block
// to avoid an infinite loop
}
Let's use a while loop to print the even numbers from 2 to 10:
#include <iostream>
using namespace std;
int main() {
int i = 2;
while(i <= 10) {
cout << i << " ";
i += 2;
}
return 0;
}
In this example, the loop checks if `i` is less than or equal to 10, and as long as this condition is true , it prints the current value of `i` and increments it by 2. The loop will execute five times, printing the numbers 2, 4, 6, 8, and 10.
Do While Loop
The do-while loop is similar to the while loop, but the condition is checked after each iteration. This guarantees that the code block is executed at least once, even if the condition is initially false. Here is the syntax:
do {
// code to be executed in each iteration
} while(condition);
Let's use a do-while loop to take input from the user until a valid number is entered:
#include <iostream>
using namespace std;
int main() {
int num;
do {
cout << "Enter a positive number: ";
cin >> num;
} while(num <= 0);
return 0;
}
In this example, the loop prompts the user to enter a positive number and reads the input. The loop continues to execute as long as the entered number is less than or equal to zero. Once a valid number is entered, the loop terminates.
Loops are powerful tools that enable you to automate repetitive tasks and make your programs more efficient. Understanding when and how to use each loop construct will greatly enhance your programming skills.
Basic Topics
- Introduction to C++
- Basic Syntax and Structure
- Variables
- Data Types
- Operators
- Output and Input
- Conditional Statements
- Loops
- Break and Continue Statements