Learn break statement in easy way possible

break statement in C

Using break statement we can get out of loop when certain condition is matched.

In C program break statement is used in 2 ways.

  1. To get out of loop when given condition is matched
  2. It is also used in switch case to get out of case, and preventing next from execution.
break-statement-itvoyagers
ITVoyagers

Example of break statement with while loop

  #include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
i++;
if(i == 3)
{
break;
}
printf("%d ITVoyagers n",i);
}
}

Output:

  1 ITVoyagers
2 ITVoyagers

In above example while loop will starting iterating  because initial condition is valid and it will print value of i followed by ITVoyagers, but when value of i reaches to 3 then condition for inner if statement gets true and this will execute break statement, which will force while loop to stop iterations and get out of loop, hence loop execution stops after “2 ITVoyagers”.

ITVoyagers

Example of break statement with do-while loop

  #include<stdio.h>
void main()
{
int i=0;
do
{
i++;
if(i == 3)
{
break;
}while(i<=5);
printf("%d ITVoyagers n",i);
}
}

Output:

  1 ITVoyagers
2 ITVoyagers
ITVoyagers

Example of break statement with for loop

  #include<stdio.h>
void main()
{
int i;
for(i=0; i<=5; i++)
{
if(i == 3)
{
break;
}
printf("%d ITVoyagers n",i);
}
}

Output:

  0 ITVoyagers
1 ITVoyagers
2 ITVoyagers
ITVoyagers

Example of break statement with switch case

  #include<stdio.h>
void main()
{
int i=1;
switch(i)
{
case 0:
printf("%d ITVoyagers",i);
break;
case 1:
printf("%d ITVoyagers",i);
break;
case 2:
printf("%d ITVoyagers",i);
break;
default:
printf("%d ITVoyagers",i);
break;
}
}

Output:

  1 ITVoyagers

Try this practice quiz

CHECKOUT OTHER RELATED TOPICS

CHECKOUT OTHER QUIZZES

PRACTICALS IN C PROGRAM

We are aiming to explain all concepts of C in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment