English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
We learned about loops in the previous tutorial. In this tutorial, we will learn to use break and continue statements with the help of examples.
The break statement immediately ends the loop when encountered. Its syntax is:
break;
The break statement is almost always used with the if...else loop statements.
//The program calculates the maximum10sum of the 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 n%d: ", i); scanf("%lf", &number); //If the user enters a negative number, the loop ends if (number < 0.0) { break; } sum += number; //It is equivalent to sum = sum + number); } printf("Total = %.2f",2lf", &sum); return 0; }
Output Result
Input n1: 2.4 Enter n2: 4.5 Enter n3: 3.4 Enter n4: -3 Sum = 10.30
This program calculates the maximum10numbers sum. Why maximum10numbers? This is because if the user enters a negative number, the break statement will be executed. This will end the for loop and display sum (total).
In C, break is used with the switch statement. This will be discussed in the next tutorial.
continue statement syntax in C
continue;
The continue statement is almost always used with the if...else statement.
//The program calculates the maximum10sum of the numbers //Skip negative numbers from the calculation # include <stdio.h> int main() { int i; double number, sum = 0.0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i); scanf("%lf", &number); if (number < 0.0) { continue; } sum += number; //It is equivalent to sum = sum + number); } printf("Total = %.2f",2lf", sum); return 0; }
Output Result
Input n1: 1.2 Input n2: 3.4 Input n3: 6.7 Input n4: 4.5 Input n5: -3.8 Input n6: -48.8 Input n7: 34.9 Input n8: -4.6 Input n9: -1000 Input n10: 18 Sum = 68.70
In this program, when the user enters a positive number, use sum += number; statement calculates the sum (sum).
When the user enters a negative number, the continue statement is executed and the negative number is skipped from the calculation.