Code About Us Tutorial


  Statements & Expression
    The while Statement
    The do ... while Statement
    The for Statement
    The break Statement
    The continue Statement
    The goto Statement
    The switch Statement
    Keywords
    Scope Resolution (::)
    Arithmatic Operators


   
 

Home > Statements & Expression > The break Statement

November 27, 2009 4:15 am

   

The break Statement

This next example is a more advanced for loop, using the break keyword. The break keyword is used to break off in a loop. The break statement jumps over all the rest of the statements in the loop's block and goes to the next statement after the loop. Here is the example:

 
 
#include <iostream.h>

void main() { int n, count = 0, sum = 0; cout <<"Enter positive integers. Terminate input with 0:n"; for (;;) { cout << "t" <<count + 1 << ": "; cin >> n; if(n ==0) break; ++count; sum += n; } cout <<"The average of the " << count << " numbers is " << (float) sum / count << endl; }

In this example, we still used a for loop, but we excluded all three control parts of the loop, this would have caused an infinite loop but we added the break keyword to stop it. The line that calculates the average is, << (float) sum / count << endl; this line takes the sum and divides it by count and converts it to float, so you get a decimal answer.Please Rate this Code:


    Comments for: The break Statement
Annonymouse User says:
I keep on getting error C2043 which says it is an illegal break. Everything seems to be fine! I see nothing wrong. Someone please help me.

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
The code looks fine to me!

It might be a bit more readable to use a while loop:

 
 
while( true ) {
	cout << \"\t\" << count + 1 << \": \";
	cin >> n;
	if(n == 0) 
	  break;
	++count;
	sum += n;
}

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
The code looks fine to me!

It might be a bit more readable to use a while loop:

 
 
while( true ) {
	cout << \"\t\" << count + 1 << \": \";
	cin >> n;
	if(n == 0) 
	  break;
	++count;
	sum += n;
}
says:
if I have a double for loop, will the break statement leave both for loops or just the one it is in?

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
The code looks fine to me!

It might be a bit more readable to use a while loop:

 
 
while( true ) {
	cout << \"\t\" << count + 1 << \": \";
	cin >> n;
	if(n == 0) 
	  break;
	++count;
	sum += n;
}
says:
if I have a double for loop, will the break statement leave both for loops or just the one it is in? says:
Hi, I am doing porting of one of our client . He written the code in C. while compiling I am facing Illegal break statement. He used break in the simple staement insted of switch-case, while, for loop.

What is the equivalent of above break.





Add Comment:
Name:
Email:


 «12» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.