Breaking out of a loop using break.

When we want an exit from loop then we use a break statement in C.

We can provide a specific condition if the condition matches then we can exit from the loop using the break statement.

In all the C loops we have a way to break out of a loop at any point in time, immediately, regardless of the conditions set fo the loop.

This is done using the break keyword. This is useful in many cases. You might want to check for the value of a variable,

for example:

for (int i = 0; i <= 10; i++) {
if (i == 4 && someVariable == 10) {
break;
}
}

Having this option to break out of a loop is particularly interesting for while loops .

(and do while too), because we can create seemingly infinite loops that end when a condition occurs, and you define this inside the loop block:

int i = 0;
while (1) {
/* do something */
i++;
if (i == 10) break;
}

Simple example of Break in C

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
{
if(i==4)
{
break;
}
printf(“Welcome %dn”,i);
}
printf(“Exit from loop here”);
getch();
}

Output:
welcome 1
welcome 2
welcome 3
Exit from loop here

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Break in C Programming Language

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Explore Tutorials By Categories

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password