break Statement
The break statement is used with in switch statement to transfer program control out of switch statement after executing a set of statements mentioned in a particular case.
break statement can also be used in looping statements to transfer program control out of the loop. This will help to terminate a loop when a particular condition is met.
Example:
This program will check whether the given number contain digit 0.It is noted that when the number contain first 0, we can stop doing the process and print that the number contains 0.There is no point in continuing the loop and hence computation time can be saved.
#include <stdio.h>
main()
{
int n,digit;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
digit= n % 10;
n = n/10;
if (digit==0) {
printf("number contains 0\n");
break;
}
}
}
Enter an integer:23045
continue statement
continue statement is used inside loop to skip the execution of remaining statement and continue the iteration.
Example:
The following program will print numbers from 1 to 15 except the numbers which are divisible by 3. When the number is divisible by 3, the loop is continued skipping the print statement. The continue statement will make the program control to jump to the beginning of the loop .
#include <stdio.h>
main()
{
int i;
for(i=1;i<=15;i++)
{
if(i%3==0)
continue;
printf("%d\n",i);
}
}
1
2
Difference Between break and continue in C
S.No. | break | continue |
1. | break statement is used in switch and loops. | continue statement is used in loops only. |
2. | When break is encountered the switch or loop execution is immediately stopped. | When continue is encountered, the statements after it are skipped and the loop control jump to next iteration. |
3. | Example: #include<stdio.h> main() { int i; for(i=0;i<5;++i) { if(i==3) break; printf(“%d “,i); } Output: 0 1 2 | Example: #include<stdio.h> main(){ int i; for(i=0;i<5;++i) { if(i==3) continue; printf(“%d “,i); } } Output: 0 1 2 4 |
goto statement
... .. ...
... .. ...
... .. ...
label:
statement;
main()
{
int number,sum=0;
begin: printf("Enter numbers give -ve number to stop\n");
scanf("%d",&number);
if( number <0) goto end;
sum=sum+number;
goto begin;
end:printf("sum=%d\n",sum);
}
void exit(int status);
status argument passed to exit() is returned to O.S. to inform that whether or not program succeeded normally. Notice that this status argument is as same as status main() passes to O.S. Pre defined symbols EXIT_SUCCESS and EXIT_FAILURE are used to pass successful and failure status to O.S respectively. EXIT_SUCCESS is represented with 0 and EXIT_FAILURE with value 1.exit() function is prototyped in stdlib.h header file.
#include <stdlib.h>
#include <math.h>
main()
{
int n;
printf("enter a number\n");
scanf("%d",&n);
if (n<0) {
printf("cant find root of -ve numbers\n");
printf("terminating the program\n");
exit(1);
}
printf("sqrt=%f\n",sqrt(n));
}
Comments
Post a Comment