Unlocking the Power of Loops: Break and Continue Statements
When it comes to programming, loops are an essential tool for executing repetitive tasks. However, there are times when you need to interrupt or skip certain iterations within a loop. That’s where the break and continue statements come into play.
The Break Statement: A Loop Exit Strategy
Imagine you’re writing a program that calculates the sum of a series of numbers entered by the user. You want to set a limit on the number of inputs, let’s say 10. But what if the user decides to enter a negative number? You can use the break statement to exit the loop immediately and display the sum.
The syntax for the break statement is simple: break;
. It’s often used with an if-else statement inside a loop to specify the condition for exiting the loop.
Example: Breaking Out of a Loop
Here’s an example program that demonstrates the break statement:
int sum = 0;
for (int i = 0; i < 10; i++) {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number < 0) {
break;
}
sum += number;
}
printf("Sum: %d\n", sum);
In this example, if the user enters a negative number, the break statement is executed, and the loop ends. The sum is then displayed.
The Continue Statement: Skipping Iterations
Now, let’s say you want to skip certain iterations within a loop without exiting the loop entirely. That’s where the continue statement comes in.
The syntax for the continue statement is also straightforward: continue;
. Like the break statement, it’s often used with an if-else statement to specify the condition for skipping an iteration.
Example: Skipping Negative Numbers
Here’s an example program that demonstrates the continue statement:
int sum = 0;
for (int i = 0; i < 10; i++) {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number < 0) {
continue;
}
sum += number;
}
printf("Sum: %d\n", sum);
In this example, if the user enters a negative number, the continue statement is executed, and the current iteration is skipped. The loop continues with the next iteration, and the sum is calculated only for the positive numbers.
By mastering the break and continue statements, you’ll be able to write more efficient and effective programs that can handle complex scenarios with ease.