Loops in C++
Loops are blocks of code that are repeated until a condition is met.
The different types of loops in C++ are:
- For Loop
- While Loop
- Do While Loop
- Infinite Loop
For Loop
For Loop is used when we know exactly how many times we want to loop through a block of code.
Syntax
for(initialization expression; test expression; update expression)
{
// statements to execute in the loop body
}
Here,
- The initialization expression is used to initialize variables and it is executed only once.
- The test condition is checked on every loop and it is executed until the condition is true. The body of the for loop is executed until the test condition is true and when the test condition is false, the for loop is terminated
- The update expression increments or decrements the value of the loop variable in the update expression on every loop.
Example
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 4; i++)
{
cout << " Hello World\n";
}
return 0;
}
Output
Hello World
Hello World
Hello World
While Loop
While loop is also called entry controlled loop, it verifies the condition specified before executing the loop body. While Loop repeats a statement while a given condition is true.
Syntax
initialization expression;
while (test_expression)
{
// statements to execute in the loop body
update_expression;
}
Example
#include <iostream>
using namespace std;
int main()
{
int i = 0; // initialization expression
while (i < 4) // test expression
{
cout << "Hello World\n";
i++; // update expression
}
return 0;
}
Output
Hello World
Hello World
Hello World
Do While Loop
Do while loop is an exit controlled loop meaning the condition is tested at the end of the loop body. Hence, the loop body executes at least once, regardless of the condition, whether it is true or false.
Syntax
initialization expression;
do
{
// statements to execute in the loop body
update_expression;
} while (test_expression);
Example
#include <iostream>
using namespace std;
int main()
{
int i = 2; // initialization expression
do
{
cout << " Hello World\n";
i++; // update expression
} while (i < 1); // test expression
return 0;
}
Output
In the above example, the test condition says It should be less than 1 that is i<1, but still, the loop executes at least once, before checking for the condition, hence giving us the output "Hello World" one time.
Infinite Loop
Infinite loop is an endless loop that does not have a proper exit condition for the loop, which makes it run infinitely. A loop becomes an infinite loop if a condition of the loop never becomes false.
Syntax
Example
#include <iostream>
using namespace std;
int main()
{
int i;
for (;;)
{
cout << "This loop runs indefinitely.\n";
}
}
In this example, we have not mentioned any test expression and have left it blank. Therefore this loop will run indefinitely until manually terminated.