hello

header ads

Loops

 

Loop

In computer programming, loops are used to repeat a block of code.

For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.

There are 3 types of loops in C++.

§  For loop
§  While loop
§  Do…While loop

 

for loop

The syntax of for-loop is:

for (initialization; condition; update) {

    // body of-loop

}


Flowchart of for Loop in C++






 

Example 1: Printing Numbers From 1 to 5

#include <iostream>

 

using namespace std;

 

int main() {

        for (int i = 1; i <= 5; ++i) {

        cout << i << " ";

    }

    return 0;

}

Output

1 2 3 4 5


Example 2: Display a text 5 times

// C++ Program to display a text 5 times

 

#include <iostream>

 

using namespace std;

 

int main() {

    for (int i = 1; i <= 5; ++i) {

        cout <<  "Hello " << endl;

    }

    return 0;

}

Output

Hello

Hello

Hello

Hello

Hello


While Loop

while loop statement repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in C++ is −

while(condition) {
   statement(s);
}

 

Flow Chart



Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

#include <iostream>
using namespace std;
 
int main () {
   int a = 10;
 
   // while loop execution
   while( a < 20 ) {
      cout << "value of a: " << a << endl;
      a++;
   }
 
   return 0;
}
 
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

 

 

 

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.




Syntax

do {
  
// code block to be executed
}

while (condition);

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Example

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


 

 

Post a Comment

0 Comments