Saturday, May 4, 2019

Break Statement and Continue Statement in C

Break statement are used for terminates any type of loop e.g, while loop, do while loop or for loop. The break statement terminates the loop body immediately and passes control to the next statement after the loop. In case of inner loops, it terminates the control of inner loop only.

Use break statement

Break statement are mainly used with loop and switch statement. often use the break statement with the if statement.
  • with loop statement
  • with switch case
  • with if statement

Syntax

jump-statements (loop or switch case);
break;

Example of break

#include<stdio.h>
#include<conio.h>

void main()
{
char key;
 
printf("Press any key or E to exit:\n");
while(1)
{
scanf("%c", &key);
if (key == 'E' ||  key == 'e')
break;
}
printf("Good bye !\n");
}
Explanation:In the above code when user enter any character, if the user enters E or e, the break statement terminates the while loop and control is passed to the statement after the while loop that displays the Good bye !message.

Output

Press any key or E to exit
Good bye !

Continue Statement

Continue statement are used to skips the rest of the current iteration in a loop and returns to the top of the loop. The continue statement works like a shortcut to the end of the loop body.

Use break statement

Syntax

jump-statements (loop or switch case);
continue; 

Example of continue

#include<stdio.h>
#include<conio.h>

void main()
{    
int i=1;  
clrscr();    
  
for(i=1; i<=10; i++) 
{    
if(i==3)  //if value of i is equal to 3, it will continue the loop 
{  
continue;  
}  
printf("%d \n",i);  
}//end of for loop  
  
getch();    
}

Output

1
2
4
5
6
7
8
9
10

No comments:

Post a Comment

Why learning C Programming is a must?

C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as...