Continue and break Statement

  • Post author:
Download PDF
Advertisement

Continue and break Statement

‘continue’ Statement

The continue statement is used in the body of the loop. It is used to move the control to the start of the loop body. When this statement is executed in the loop body, the remaining Statements of the current iteration are not executed. The control directly moves to the next iteration.

Example

  int x;
	for(z = 1; x<=5; x++)
	{
	  cout<<”Hello Zitoc \n”;
	  continue;
	  cout<<”Knowledge is power”;
	}

Explanation

The above example has two court statements. One statement is before the continue statement and one is after continuing statement. The second statement is never executed This is because each time the continue statement is executed, the control moves back to the start of the body. So “Knowledge is power” is never displayed.

Program:

Write a program that displays the sum of the following series. 1+3+5+7+…….100

  #include <iostream>
  #include <conio.h>
  using namespace std;
  void main() 
  {
	int sum = 0;
	for(int i =1; i<100; i++)
	{
	   if(i % 2 ==0)
	     continue;
	  sum = sum +i;
	}
	cout<<”The sum is ”<<sum;
	getch();
   }

Output:

The sum is 2500

Advertisement

‘break’ Statement

The break statement is used in the body of the loop to exit from the loop. When this statement is executed in the loop body, the remaining iterations of the loop are skipped. The control directly moves outside the body and the statement that comes after the body is executed.

Example

  for(int x= 1; x<=5; x++)
     {
      cout<<”ZITOC\n”;
	 break;
      cout<<”knowledge”;
      }
	cout<<”By”;

Explanation

The above program uses a break statement in for loop. The counter variable x indicates that the loop should execute for five times. But it is executed only once. In the first iteration, the tout statement in the loop displays “Questioning” and control moves to break statement. This statement moves the control out of the loop. So the message appears only once.

 

Loops in C++

Advertisement