Monday 15 June 2020

Break Statement C Language

Break (Loop,Switch Case)




A break keyword is used to forcefully stop a loop. For example, you have set a loop to run 100 times and your requirement got fulfilled after 10 iterations then the loop will run 90 times which leads wastage of time and resource. So the break statement is used to stop the loop when need got complete.

Example: Write a program to input and sum ten numbers. Input will stop immediately when a user-entered number is dividing by 11 then the loop must be stopped.

#include<stdio.h>
#include<conio.h>
/*##########################
     Girfa Student Help
     Break Statement Example
  ##########################*/

void main()
{
     int a,b,sum;
     clrscr();
     for(a=1,sum=0;a<=10;a++)
     {
          printf("Enter number>> ");
          scanf("%d",&a);
          if(a%11==0)
              break;
          sum+=a;
     }
     printf("\nSum=%d",sum);
     getch();
}

Note : break should always be used with if statement otherwise loop will run only one time.

#include<stdio.h>
#include<conio.h>
void main()
{
     int a;
     clrscr();
     for(a=1,a<=10;a++)
     {
          printf("%d",a);
          break;
     }
     getch();
}

Break in Switch case


A break statement is optionally used to stop a switch case. All statements after break won’t be run.

#include<stdio.h>
#include<conio.h>
/*##########################
     Girfa Student Help
     print day of the week
  ##########################*/
void main()
{
     int n;
     clrscr();
     printf("Enter day of the week >> ");
     scanf("%d",&n);
     switch(n)
     {
          case 1:
              puts("Sun");
              break;
          case 2:
              puts("Mon");
              break;
          case 3:
              puts("Tue");
              break;
          case 4:
              puts("Wed");
              break;
          case 5:
              puts("Thu");
              break;
          case 6:
              puts("Fri");
              break;
          case 7:
              puts("Stu");
              break;
     }
     getch();
}



No comments:

Post a Comment