C++ Learning Resource Network!

 
 
 C++ Tutorials  >  Variables, Construct & Looping  >  >  Loop Construct   > break and continue statements
 

break Statement

The break statement is used to terminate a case in a switch construct. The break statement is also for termination of a loop, bypassing the normal loop conditional test.

When a break is encountered inside a loop, the loop is terminated and control passes to the statement following the loop body.

The following program illustrates the usage of a break statement. In Program 2.5, if the user enters zero, the break statement causes immediate termination of the loop

//Program 2.5
//This program finds the inverse of a number
#include<iostream.h>
void main()
{
float fNum;
char cReply;
do
{
cout<<"Enter a number:";
cin>>fNum;
if(fNum == 0)
break;
cout<<"Inverse of the number is "<<1/fNum<<endl;
cout<<"Do you want to input another number(y/n)?";
cin>>cReply;
}
while(cReply != 'n');
}


continue Statment

The continue statement forces the next iteration of the loop to take place, skipping any code following the continue statement in the loop body. In the for loop, the continue statement causes the conditional test and then the re-initialization portion of the loop to be executed. In the while and do..while loops, program control passes to the coditional test.

The following program illustrates teh usage of the continue statement:

//Program 2.6
//This program finds the square of the numbers less than 100
#include<iostream.h>
void main()
{
int iNum;
char cReply = 'y';
do
{
cout<<"Enter a number:";
cin>>iNum;
if(iNum > 100)
{
cout<<"The number is greater than 100, enter another"<<endl;
continue;
}
cout<<"The square of the number is: "<<iNum * iNum<<endl;
cout<<"Do you want to enter another(y/n)?";
cin>>cReply;
}
while(cReply != 'n');
}

 
 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.