Break statement in C with examples
Break statement is used inside the loops and switch cases statement.
- Break statement is used to terminate the loop immediately. If a break statement is found inside a loop, the control instantly comes out of the loop and the loop immediately gets ended. This statement is mostly used with the if statement, whenever utilized inside the loop.
- Break statement can also be used with a switch case control structure. Wherever break statement is discovered in the switch-case block, the control instantly comes out of the switch-case block.
Syntax of the break statement: "break;"
Example of break statement
#include<stdio.h> int main() { int x =0; while(x<=100) { printf("The value of variable x is: %d\n", x); if (x==2) { break; } x++; } printf("Out of while-loop"); return 0; }
Output:
The value of variable x is: 0 The value of variable x is: 1 The value of variable x is: 2 Out of while-loop
In the Above program, initiated a while loop and loop condition is valid till x`s value is not greater than 100. so in the first iteration, it will print 0 then in the next iteration it will print 1.
In the third iteration, the x`s value becomes 2 and the program runs the if condition block and execute the break statement and then the program comes out of the loop
Use of the Continue statement in C Language with example
Continue statement in C programming is used to skip the code in the loop block and jump to the beginning of the loop for the next iteration.
Syntax of the Continue statement: "continue;"
Well, it functions relatively like the break statement. Rather than moving to the termination process, continue statement functions to shift to the next iteration of the loop, skipping the current iteration.
Example of continue statement
#include<stdio.h> int main() { int m; double number, sum = 0.0; for (m = 1; m <= 5; ++m) { printf("Enter a number n%d: ", m); scanf("%lf", &number); if (number < 0.0) { continue; } sum += number; // sum = sum + number; } printf("Sum = %.2lf", sum); return 0; }
Output:
Enter a number n1: 10 Enter a number n2: -15 Enter a number n3: 28 Enter a number n4: 70 Enter a number n5: -35 Sum = 108.00
In the above example, if the user enters a positive number, then the sum is being calculated using sum += number; statement.
If the user enters a negative number, the continue statement is run and it ignores the negative value from the calculation.