Dec 11, 2015

Use of Continue Statement

Using Continue Statement

Continue statement is used to skip the current iteration and force to execute next iteration by skipping any code after continue statement inside a loop.
In simple term whenever you encounter continue statement in a loop it will skip the current pass execute next pass and also it skip the other statement below the continue statement inside a loop.

Let check the following examples for better understanding:

Ex1: Print Odd Number
#include<iostream.h>
int main()
{
//Print odd number
for(int i=1; i<=10;i++)
 {
    if(i%2==0)
    continue;
/*
 Above two lines first line check if i is even or not, If its even then i%2 return zero
means condition is true for even number of i then continue statement will execute.
As you can see in output we are printing only odd numbers so whenever continue statement runs it will skip all next line inside a loop and go to next iteration that increment of i
*/
    cout << i<<endl;
 }
return 0;
}

OUTPUT





Ex2: Divide Two Numbers
#include<iostream.h>
int main()
{
//Divide Two Numbers
char ch;
float a,b;
do //Using Do While Loop
 {
  cout << "Enter First Number : "; 
  cin >> a; //Input First Number
  cout << "Enter Second Number : ";
  cin >> b; //Input Second Number
  if(b == 0) // Check for divisor for zero
   {
    cout << "Error: Number Cannot Divide by Zero"<<endl; //return error message
    continue; 
/*
In this whenever we encounter with divisor = 0 then error message is display
and continue statement will execute. Whenever Continue statement runs it will skip all the code after that inside a loop and start from next iteration. As in this example we are using Do while loop which check condition at the end but we already skip the statements after continue so we will don't check the condition and we will start loop from begin. As you can seen in Output
*/
   }
  cout << "Answer = " << a/b<<endl;
  
  cout << "Try Again(y/n): ";
  cin >> ch; 
 }while(ch != 'n');

 return 0;
}

Output



1 comment: