break and continue goto statement

A break is a keyword in C program which is used to bring the program control out of the loop. The break statements are used inside the loops or switch statements. It breaks the loops one by one i. e, in the case of nested loops, it breaks the inner loop first and then proceeds to the outer loops


Syntax:
   
          break ;

Flowchart:

 

Program:

         
#include <stdio.h>
int main() {
   int a =10;
   while(a<20){
       printf("value of a : %d /n", a);
       a++;
   if (a>15){
    break;
   }
}
return 0;
}



      When the above code is compiled and executed, it produces the following output

Value of a : 10
Value of a : 11
Value of a : 12
Value of a : 13
Value of a : 14
Value of a : 15

The continue statement in C program works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place.

continue:


Syntax:
   
       continue ;

Flowchart:

       


Program:
 
          
#include <stdio.h>
int main() {
int a =10 ;
do {
    if (a==15) {
         a=a+1;
         continue;
         }
printf ("value of a : %d /n", a);
a++;
}
while (a<15);
return 0;
}



   
When the above code is compiled and executed , it produces the following output.


Value of a : 10      
Value of a : 11
Value of a : 12
Value of a : 13
Value of a : 14
Value of a : 15

Goto is a jumping statement in C language, which transfer the program's control from one statement (where the label is defined). It transfers the programs within the same block and there must be a label where you want to transfer program's control.

Syntax :

       goto label_name ;

Flowchart :

        


Two styles of goto statement :

Style 1 : (Transferring the control from down to top )

 // style 1
label_name:
      Statement 1;
      Statement 2;
       . . . 
        
       if (any-test-condition)
           goto label_name;

Note : here if any test condition is true , goto will transfer the program's control to the specified label_name.


Program:
#include<stdio.h>
int main()
{
int number;
number =1;
repeat:
   printf ( "%d /n", number);
   number++;
   if (number<=5)
     goto repeat;
     return 0;
}

When the above code is compiled and executed it produces the following output.

1       
2
3
4
5


Style 2 : ( Transferring the control from top to down)

// style 2
statements ;
      if (any-test-condition)
      goto label_name;
      statement 1;
      statement 2;
      label_name:
            other statements;

Program:

#include<stdio.h>
int main()
{
int number;
printf ("Enter an integer number:");
scanf ("%d", & number);
if (number<=0);
     goto end;
     printf("Number is :  %d",number);
end:
     printf (" Hi!!");
     return 0;
}

When the above code is compiled and executed it produces the following output.

First run :
Enter an integer number : 1
Number is 1
Hi!!

Second run :
Enter an integer number : 0
Hi!!



No comments:

Post a Comment