BREAK STATEMENT IN C
In C programming, jump statements are used to alter the flow of control within a program.
Break is a jump statement in C language. It is also a keyword in C i.e. it should be written in lowercase. If you want to get out of an iteration or loop early, you have to use the break statement.
Break is used in loops and switch statement.
If you use break in a statement other than loops or switch statement, it will give an error ❌. Using it in any of the conditional statements like if, if-else, else if, and switch block that doesn’t have a loop will also give error❌.
Whenever the control encounters a loop it automatically exits from the loop and executes whatever is after the loop.
For Example
#include <stdio.h>
int main()
{
int a, sum = 0;
for(int i=0; i<=5; i++)
{
printf("Enter a value: ");
scanf("%d", &a);
if (a<0)
break;
sum = sum + a;
}
printf("\n");
printf("%d", sum);
return(0);
}
Here this program prints the sum of five numbers. The variable a was declared, same with sum, but sum was initialized to 0.
The for loop initialized i to 1, and passed a terminating condition, if i(1) is less than 5 then the fir loop will be evaluated.
Entering the for loop because the condition is true, (i.e 1 is less than 5).
The control then asks the user to enter a number, after entering a number, it asks again till the user enters five numbers.
Then the sum is calculate this way:
sum = sum + a; // The sum is equals 0 because
// it's been initialized already
// Supposing the inputted values are 14, 33, 56, 98, 20
sum = 0 + 14 // sum = 14
sum = 14 + 33 // sum = 47
sum = 47 + 56 // sum = 103
sum = 103 + 98 // sum = 201
sum = 201 + 20 // sum = 221
// The value of sum is 221 and it will be
// outputted on the console.
If the user enters any negative number, the control exits the loop immediately and prints the sum of the previous numbers entered before the negative number.
Don’t say we’re using a break statement inside the if block. The if block is a child of the for loop statement .