The Syntax
break;The break statement terminates the loop (for, while, and do...while loop) immediately when it is encountered.
Example:
// 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.4Enter a n2: 4.5Enter a n3: 3.4Enter a n4: -3Sum = 10.30The Syntax
continue;The continue statement immediately checks the test condition to decide if it should continue or exit.
// Program to calculate the sum of a maximum of 10 numbers// Negative numbers are skipped from the calculation# 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(number < 0.0) { continue; } sum += number; // sum = sum + number; } printf("Sum = %.2lf",sum); return 0;}Output:
Enter a n1: 1.1Enter a n2: 2.2Enter a n3: 5.5Enter a n4: 4.4Enter a n5: -3.4Enter a n6: -45.5Enter a n7: 34.5Enter a n8: -4.2Enter a n9: -1000Enter a n10: 12Sum = 59.70These statements can used to get specific behaviors out of loops (for, while, and do...while). In C programming the break statement is also used with switch...case statements.