Repetitive structures (or loops) in C++ are used to repeatedly execute a block of code as long as a condition is true.
for loops are used when you know exactly how many times you want to execute a block of code.
for (initialization; condition; increment)
{
// code to be executed in loop
}#include
using namespace std;
int main()
{
for (int i = 0; i < 5; ++i)
{
cout << "Value of i: " << i << endl;
}
return 0;
} while loops are used when you want to execute a block of code as long as a condition is true. The block of code may not execute at all if the condition is false from the start.
while (condition)
{
// code to be executed in loop
}
#include
using namespace std;
int main()
{
int i = 0;
while(i < 5)
{
cout << "Value of i: " << i << endl;
++i;
}
return 0;
} do-while loops are similar to while loops, but ensure the execution of the block of code at least once, as the condition is checked at the end of the loop.
do
{
// code to be executed in loop
} while (condition);#include
using namespace std;
int main()
{
int i = 0;
do
{
cout << "Value of i: " << i << endl;
++i;
} while(i < 5);
return 0;
}