C++ Loops


There are three basic types of loops which are:

  • for loop
  • while loop
  • do while loop

The for loop

The "for loop" loops from one number to another number and increases by a specified value each time.

The "for loop" uses the following structure:

 for (Start value; end condition; increase value)
     	{
	statement(s);
        }

Example

#include<iostream>
	using namespace std;
       int main()
	{
		int i;
		for (i = 0; i < 5; i++)
		{
			cout << "Hello" << endl;
		}
		return 0;
	}
Output
Hello
Hello
Hello
Hello
Hello

The while loop

The while loop can be used if you don't know how many times a loop must run.

Example

#include<iostream>
	using namespace std;
	int  main()
	{
         int  i = 0;
         while( i < 5)
         {
          cout << "Hello" << endl;
          }
         return 0;
	}

The do while loop

The "do while loop" is almost the same as the while loop.

do
  {
   do something;
   }
while (expression);

Do something first and then test if we have to continue.

The result is that the loop always runs once. (Because the expression test comes afterward).

Example

#include <iostream.h>
using namespace std;

int main()
{
int counter, num;
cin >> num;
counter = 0;
do
{
counter++;
cout << counter << '\n';
}
while ( counter < num);
return 0;
}

Share this article on