Learn one of the most powerful programming languages in the world and become a rockstar developer.
In this tutorial, you will learn how to use the break and continue statements to control the loop iteration.
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
C break
statement terminates any type of loop e.g., while loop, do while loop or for loop. The break statement terminates the loop body immediately and passes control to the next statement after the loop.
The break statement is only meaningful when you put it inside a loop body, and also in the switch casestatement.
We often use the break statement with the if statement, which specifies the condition to terminate the loop.
The following example illustrates how to use the 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; }
This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10 numbers? It's because if the user enters a negative number, the break statement is executed. This will end the for loop, and the sum is displayed.
C continue statement skips the rest of the current iteration in a loop and returns to the top of the loop. The continue statement works like a shortcut to the end of the loop body.
The following example illustrates the continue statement:
// 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; }
In this program, when the user enters a positive number, the sum is calculated using sum += number; statement.
When the user enters a negative number, the continue statement is executed and it skips the negative number from the calculation.