When break is encountered inside any loop, control automatically passes to the first statement after the loop.
A break statement is usually associated with an if.
Example program
//program to print first 6 numbers only
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=0;i<=10;i++)
{
printf("%d\n",i);
if(i==6)
break;
}
getch();
return 0;
}
output:
0
1
2
3
4
5
6
Though we wrote the program to print 10 numbers, the numbers after 6 are not printed because of the break statement. Here the moment the system encounters the break statement, control automatically passes to the next statement after the loop.
//program to determine whether a number is prime or not
#include<stdio.h>
#include<conio.h>
int main()
{
int num, i;
printf("enter a number\n");
scanf("%d",&num);
i=2;
while(i<=num-1)
{
if(num%i==0)
{
printf("not a prime number");
break;
}
i++;
}
if(i==num)
printf("prime number");
getch();
return 0;
}
output:
enter a number
9
not a prime number
A break statement is usually associated with an if.
Example program
//program to print first 6 numbers only
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=0;i<=10;i++)
{
printf("%d\n",i);
if(i==6)
break;
}
getch();
return 0;
}
output:
0
1
2
3
4
5
6
Though we wrote the program to print 10 numbers, the numbers after 6 are not printed because of the break statement. Here the moment the system encounters the break statement, control automatically passes to the next statement after the loop.
//program to determine whether a number is prime or not
#include<stdio.h>
#include<conio.h>
int main()
{
int num, i;
printf("enter a number\n");
scanf("%d",&num);
i=2;
while(i<=num-1)
{
if(num%i==0)
{
printf("not a prime number");
break;
}
i++;
}
if(i==num)
printf("prime number");
getch();
return 0;
}
output:
enter a number
9
not a prime number
No comments:
Post a Comment