11 - Loop Statements of C++
11 - Loop Statements of C++
In C++, you can use loop statements to repeatedly execute a block of code as long as a specific
condition is met. C++ provides several types of loop statements, including:
for Loop:
Syntax:
for (initialization; condition; update)
{
// Code to repeat while the condition is true
}
Description: The for loop is commonly used for iterating over a range or sequence of values. It
includes an initialization step, a condition to check before each iteration, and an update step that is
executed after each iteration.
Example:
for (int i = 0; i < 5; ++i)
{
// Code to repeat 5 times
}
while Loop:
Syntax:
while (condition)
{
// Code to repeat while the condition is true
}
Description: The while loop repeatedly executes a block of code as long as the specified condition is
true. It does not require an initialization step, but it's crucial to ensure that the condition eventually
becomes false to avoid an infinite loop.
Example:
int count = 0;
while (count < 5)
{
// Code to repeat 5 times
++count;
}
do-while Loop:
Syntax:
do
{
// Code to repeat at least once
} while (condition);
Description: The do-while loop is similar to the while loop, but it guarantees that the code block is
executed at least once before checking the condition. The loop continues as long as the condition
remains true.
Example:
int count = 0;
do
{
// Code to repeat at least once
++count;
} while (count < 5);
Example:
int arr[] = {1, 2, 3, 4, 5};
for (int element : arr)
{
// Code to iterate over each element in the array
}
These loop statements allow you to control the flow of your program and repeat specific actions
based on conditions. Depending on the problem you're solving and the type of data you're working
with, you can choose the appropriate loop statement for the task at hand.