Loop Control Statements in C++

Written by

Vaaruni Agarwal

Loop Control Statements

Now, we know about the different types of loops in C++ and how to use them.

However, many times a situation occurs when the coder has to break out of the loop before the condition becomes false or the coder may not want to execute the loop at certain values of the counter variable.

In such a case, the C++ provides the facility of the various loop control statements, through which we can easily achieve the above-mentioned cases.

These loop control statements are also known as the jumping statements in C++. 

The following Loop Control Statements are provided by C++:

  1. break
  2. continue
  3. goto

Let us discuss them in detail.

Break statement:

Break statement is used when there is a need to terminate the loop.

The break statement causes the loop to terminate and begins execution with the very next statement outside the loop.

Example:

int x;

cin>>x;

switch(x)

{

case 1:

cout<< “You have entered ONE\n”;

break;

case 2:

cout<< “You have entered TWO\n”;

break;

case 3:

cout<< “You have entered THREE\n”;

break;

default:

cout<< “You have entered more than THREE\n”;

break;

}

cout<< “Outside Switch\n ”;

Input:

2

Output:

You have entered TWO

Outside Switch

Here, the break statement is used to prevent falling through of cases.

Continue Statement:

Continue is also a jumping statement, it is used to prevent the current iteration of the loop and starts execution with the very next iteration of the loop.

Example:

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

{

if(i%2==0)

{

cout<< “\nEven Number: ”<<i;

}

else

{

continue;

}

}

Output:

Even Number: 2

Even Number: 4

The above program only prints even numbers from 1 to 5.

Goto statement:

Goto statement uses a label and jumps the control where the label is defined in the C++ program.

Example:

for(int i=0;i<=5;i++)

{

if(i==3)

goto val_label;

}

val_label:

cout<< “Value is THREE”;

Loop Control Statements in C++