Loops

 

There are three kinds of loops; while, do while and for. These are used to repeat a particular code of block multiple times until the condition satisfies.

 

While loop

 

syntax

 

while ( condition )
{
  //code block
}

 

The following loop runs till 5 after i=6 the loop's condition becomes false and it no longer works.

 

Example:

 

#include <iostream>

using namespace std;

int main() 
{
  int i = 0;
  while (i < 6) {
     cout << i << "\n";
     i++;
  }

  return 0;
}

 

Output

0
1
2
3
4
5

 

The Do while Loop

 

This loop will execute the code block once before checking if the condition is true, then for the second time it will repeat the loop as long as the condition is true. Hence the condition is tested after execution

 

Syntax

 

do 
{
  //code block
}
while (condition);

 

 

 

 

Example

 

#include <iostream>

using namespace std;

int main()
{
   int i = 0;
   do {
      cout << i << "\n";
      i++;
   } while (i < 6);

   return 0;
}

 

Output

0
1
2
3
4
5

 

For Loop

This is the most used loop

 

Syntax

 

for (Variable value; Condition; increment/decrement operator)
{
  //code block
}

 

Example:

#include <iostream>

using namespace std;

int main() {
 for (int i = 0; i <= 5; i++) {
   cout << i << "\n";
 }
 return 0;
}

 

Output:

0
1
2
3
4
5