Loops in C++

Written by

Vaaruni Agarwal

There are situations in real life where one has to do the same task again and again. 

For Example: When you entered late in class, your teacher tells you to write: I will never be late 50 times.

So, in the above example, the student is doing the same task that is he is writing the sentence I will never be late again and again. 

Similarly, in the programming languages also, there are some situations in which a similar task has to be performed, but for this, the programmer has to write the same code again and again. Let us assume that the teacher asks the student to write the above statement using C++.

In such a case what will the student do?

He could write 

cout<< “I will never be late”;

50 times and then compile the program and show the result to the teacher.

However, C++ provides us with the facility of loops, using the loops one can easily perform the same task by writing a few statements only.

C++ provides the use of following types of loops:

  1. While loop
  2. For loop
  3. Do While Loop

Let us discuss them in detail:

While Loop:

The while loop evaluates a condition and executes the statements as long as the test condition holds true.

Syntax:

while(condition)

{

Statement(s); //executed if condition is true

}

Example:

int n = 1;

while( n <= 3 )

   {

      cout << "C++ while loops" <<endl;

      n++;

   }

Output:

C++ while loops

C++ while loops

C++ while loops

For  Loop:

The most commonly used loop, for loop, is used to execute the given statements until the given condition holds true. 

So, the for loop is used only when the coder knows that how many times the loop needs to execute.

Syntax:

for (initialization; condition; updation )

{

Statement(s); //executed if condition is true

}

In for loop, firstly the counter variable is initialized, then the condition provided is checked if the condition is true then the loop statements are executed. After that, the updation updates the value of the loop counter and then the condition is again checked with the updated values.

Example:

for (int n = 1; n <= 3; n++ )

   {

      cout << "C++ for loops" <<endl;

   }

Output:

C++ for loops

C++ for loops

C++ for loops

 

Do While Loop:

This loop is similar to the while loop but here first the loop statements are executed and after that, the condition is checked. So, even if the condition is false for the first time the do-while loop will execute once.

Syntax:

do

{

Statement(s);

}while(condition);

 

Example:

int a =10;

do

{

cout<< “The number is smaller than 5”;

}while(a<5);

Output:

The number is smaller than 5

 

Loops in C++