C++ break Statement
- In C++, two statements break; and continue; explicitly to change a program's normal flow.
- It is sometimes advantageous to miss the execution of a loop for a certain test condition, or to immediately terminate it without testing the condition.
- For example: You want to loop data from all aged people except those aged 65. And, you're looking to find the first person aged 20.
- The break; statement terminates a loop instantly when it occurs (for, while and do.. while loop) and a turn declaration.
Break Statement |
Example of C++ break Statement
C++ program to add all number entered by user until user enters 0.
// C++ Program to demonstrate working of break statement
#include <iostream.h>
int main()
{
float number, sum = 0.0;
// test expression is always true
while (true)
{
cout << "Enter a number: ";
cin >> number;
if (number != 0.0)
{
sum += number;
}
else
{
// terminates the loop if number equals 0.0
break;
}
}
cout << "Sum = " << sum;
return 0;
}
Expected Output:-
Enter a number: 4
Enter a number: 3.4
Enter a number: 6.7
Enter a number: -4.5
Enter a number: 0
Sum = 9.6