The break;
continue;
and goto;
statements are used to alter the normal flow of a program.
Loops perform a set of repetitive task until text expression becomes false but it is sometimes desirable to skip some statement/s inside loop or terminate the loop immediately without checking the test expression. In such cases, break and continue statements are used.
In C programming, break statement is used with conditional if statement.
The break is used in terminating the loop immediately after it is encountered.
it is also used in switch...case statement. which is explained in next topic.
break;
The break statement can be used in terminating loops like for
, while
and do...while
//Write a C Program Which use of break statement.
#include<stdio.h>
#include<conio.h>
void main(){
int num, sum=0;
int i,n;
printf("Note: Enter Zero for break loop!\n");
printf("Enter Number of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0) {
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n");
}
sum=sum+num;
}
printf("Total is %d",sum);
getch();
}
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statement is used.
continue;
Just like break, continue is also used with conditional if statement.
//Write a C Program Which use of continue statment.
#include<stdio.h>
#include<conio.h>
void main(){
int i, n=20;
clrscr();
for(i=1;i<=n;++i){
if(i % 5 == 0) {
printf("pass\n");
continue; /*this continue the execution of loop if i % 5 == 0 */
}
printf("%d\n",i);
}
getch();
}
In C programming, goto statement is used for altering the normal sequence of program execution by transferring control to some other part of the program.
goto label;
.............
.............
.............
label:
statement;
In this syntax, label
is an identifier.
When, the control of program reaches to goto statement, the control of the program will jump to the label:
and executes the code below it.
//Write a C Program Which Print 1 To 10 Number Using goto statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count: //This is Label
printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
getch();
}
Though goto statement is included in ANSI standard of C, use of goto statement should be reduced as much as possible in a program.
Ask Question