break is important keyword used to alter the flow of a program. break is jump statement used to terminate a switch. break statement ends the loop immediately when it is encountered. break statement is almost always used with if...else statement inside the loop.
The break statement in C Programming is very useful to exit from any loop such as for Loop, while Loop, and do-while Loop. While executing these loops, if the C compiler finds the break statement inside them, then the loop will stop executing the statements and immediately exit from the loop.
break is jump statement used to terminate a switch or loop on some desired condition. On execution, it immediately transfer program control outside the body of loop or switch. In the case of nested switch or loop, it terminates the innermost switch or loop.
Basically break statements are used in the situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition.
How to use break statement
You must follow some rules while using break statement.
break statement in switch-case
break statement in for loop
break statement in while loop
break statement in do-while loop
break statement with nested loops
Example of break statement
// Program to calculate the sum of a maximum of 10 numbers
// If a negative number is entered, the loop terminates
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
// If the user enters a negative number, the loop ends
if(number < 0.0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30