Looping statements in C++ allow you to repeat a block of code multiple times based on a condition. There are three main types of loops in C++: for
, while
, and do-while
. Each serves a specific purpose and is useful in different scenarios.
Let’s explore each of these loops with explanations and real-life examples in code.
for
Loop
The for
loop is used when you know exactly how many times you want to repeat a block of code. It consists of three main parts:
- Initialization: Set the starting value of the loop variable.
- Condition: Define the condition for the loop to continue.
- Update: Update the loop variable after each iteration.
Syntax:
i = 1
and continues while i <= 5
. Each time, it prints the value of i
and then increments i
by 1.while
Loop
The while
loop is useful when you don’t know the exact number of iterations in advance, but you want to repeat a block of code as long as a specific condition is true
.
Syntax:
countdown
is greater than 0. Each iteration, it prints the countdown number and then decrements it by 1. When countdown
reaches 0, the loop exits, and "Liftoff!" is printed.do-while
Loop
The do-while
loop is similar to the while
loop, but it guarantees that the code block executes at least once. This is because the condition is checked after the code block has executed.
Syntax:
do-while
loop prompts the user to enter a password. Even if the password is correct on the first try, the loop runs at least once. If the password is incorrect, the loop repeats until the correct password is entered.Nested Loops
You can also place one loop inside another, which is known as nesting. Nested loops are useful for tasks that involve working with multi-dimensional data, such as printing a table.
Real-Life Example: Printing a 3x3 grid.
This code prints coordinates for a 3x3 grid, with each row printed on a new line. The inner loop completes all its iterations for each single iteration of the outer loop.
Infinite Loops
An infinite loop is a loop that never ends because the condition is always true
. These loops are useful for tasks that need to run continuously until a specific condition occurs, like waiting for user input or monitoring a sensor.
Example: Running a basic server continuously (hypothetically).
while (true)
loop creates an infinite loop that simulates a continuously running server. This loop will keep printing "Server is running..." indefinitely unless manually stopped.