break statement in C
break statement in C language is the keyword known to the compiler.
The break
statement is used to break from any kind of loop. Let us understand the use of break statement using an example.
Example:
for(i=0;i<10;i++) { /*block of statement*/ }
Let us suppose that we want to come out of for loop when the value of i equals to 5. The solution to this is using break statement. The problem can be solved using break
statement as follows:
for(i=0;i<10;i++) { /*block of statement*/ if(i==5) break; }
When the break statement in C is executed the control is transferred to the statement present immediately after the for loop.
please describe us with some good example so that it can be very much clear to us pls try to understand we are beginner 🙂
for(i=0;i<10;i++){
/*block of statement*/
if(i==5)
break;
}
printf(“%d”,i);
getch();
output:
5.
#include
int main()
{
int i;
printf(“enter the value of i:”);
scanf(“%d”,i)
for(i=1;i5
error
the output is 01234 not 5
for(i=0;i<10;i++){
/*block of statement*/
if(i==5)
break;
}
printf(“five:%d.”,i);
output:
five:5.
Nice example Pavel
Whats the mistake in my programme. Its an infinit loop:
#include
int main()
{
int x,y;
printf(“Enter a No.:”);
scanf(“%d”, &x);
for(x=0;;x++)
{
printf(“Enter No:”);
scanf(“%d%”, &y);
if(y==679)
{
break;
}
}
return 0;
}
there is a mistake in declaration of ur for statement,since there is no test condition or limiting condition,i mean when x=0 it wil execute the loop 1c, after that it wil increment the value of x n again execute the loop n again it wil increment n so on..it wont stop coz u havent mentioned any condition.
is it clear?
Where are they used?
mainly used in switch condition
can u plz correct this program & paste here????
#include
int main()
{
int x,y;
printf(“Enter a No.:”);
scanf(“%d”, &x);
for(x=0;;x++)
{
printf(“Enter No:”);
scanf(“%d%”, &y);
if(y==679)
{
break;
}
}
return 0;
}
In given example if we want to come out of loop at i=5 then why not run the loop for i<5.I mean for(i=0;i<5;i++). Please tell me purpose of break with another example.
and whether the loop will continue after i=5.Please provide some program to understand usage of break with output.
Here’s another example that uses break
#include
int main(void)
{
int x, y;
for (x = 1; x <= 5; x++) {
/* y gets set to x * x (changes each iteration of the for loop) */
y = x * x;
printf(“x=%d\n”, x);
/* as long as y < 7, we won't do anything further in the for loop */
if (y < 7) {
continue;
}
/* print the current value of x and y (y will be >= 7) */
printf(“x=%d y=%d\n”, x, y);
}
}
output:
x=1
x=2
x=3
x=3 y=9
x=4
x=4 y=16
x=5
x=5 y=25