5.5 Loop Interruption
break Statement
In C programming, the break statement is used to terminate the execution of a loop (such as for, while, or do-while) or a switch statement prematurely. When the break statement is encountered within the body of a loop , the program immediately exits that construct, and control is passed to the statement immediately following the loop block. A break statement is usually associated with if-condition.
Here's a simple example to demonstrate the break statement in a while loop:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d ", i);
if (i == 5) {
break; // Exit the loop when i reaches 5
}
i++;
}
printf("\nOutside the loop\n");
return 0;
}
Output:
1 2 3 4 5
Outside the loop
In this program:
The same program can be implemented in for-loop as:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d ", i);
if (i == 5) {
break; // Exit the loop when i reaches 5
}
}
printf("\nOutside the loop");
return 0;
}
Write a C program to check whether the given number is prime or not. [use break statement]
#include <stdio.h>
int main() {
int num,i;
printf("\nEnter a number to check: ");
scanf("%d", &num);
for (i = 2; i < num;i++)
{
if(num%i==0)
{
break;
}
}
if(i==num)
{
printf("\n%d is a prime number\n", num);
}
else
{
printf("\n%d is not a prime number\n", num);
}
return 0;
}
Output:
Enter a number to check: 17
17 is a prime number
Continue statement
In some programming situations, we may want to bypass the execution of the current statement in the body of the loop and pass the control to the beginning of the loop. In C programming, a continue statement is used to skip the execution of the current statement and take the control to the beginning of the loop. We usually associate the continue statement with the if-condition.
Write a C program to print all the numbers from 1 to 10, except 2 and 5
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if(i==2 || i==5)
{
continue; // for i =2 or 5 the continue statement, transfer the control to begining of the loop.
}
else
{
printf("%d ", i);
}
}
printf("\n");
return 0;
}