Sunday, 31 March 2019

C Programming Break and Continue statements

The break and continue statements in C language are used to alter the normal flow of execution of program.
Break statement
  • Used with loops and switch statements
  • When encountered, it breaks the execution of block in which break statement is used and program execution starts from the first statement flowing the block in which break statement is used.
Example:
#include<stdio.h>
int main(){
            int arr[5]={10,8,9,6,5};
            int i,key=9;
           
            //use of break statement
            for(i=0;i<5;i++){
                        if(arr[i]==key){
                                    printf("Element %d found at index %d.\n",key,i);
                                    break;
                        }
            }
            return 0;
}
Output:


Continue statement
  • Used with loops.
  • Usually used with if statement
  • When encountered, it breaks the execution of current iteration and start next iteration.
Example:
#include<stdio.h>
int main(){
            int arr[5]={10,8,9,6,5};
            int i,key=9;
            //use of continue statement
            for(i=1;i<=10;i++){
                        if(i%2==0){
                                    continue;
                        }
                        printf("\n%d",i);
            }
            return 0;
}
Output:


Please comment if you find anything incorrect, or you want to improve the topic discussed above.

No comments:

Post a Comment