 Break and Continue statements in C

Break statement:  It is used to immediately or abruptly come out of the particular structure (maybe a looping structure, if block, switch block....)

Syntax

for (initialization; expression1; expression2)
{
if(condition)
break;
}
statement;

(or)

while(expression)
{
if (condition)
break;
}
statement;

(or)

do
{
if (condition)
break;
} while(expression);
statement;

Continue statement:  A continue statement skips the remainder of the current iteration and initiates the execution of the next iteration.

Syntax

for (initialization; expression1; expression2)
{
if(condition)
continue;
}
statement;

(or)

while(expression)
{
if (condition)
continue;
}
statement;

(or)

do
{
if (condition)
continue;
} while(expression);
statement;

Example: check whether the entered number is a positive number or a negative number. If it is negative, avoid adding that number to the sum, else add it.

a) using continue statement

int main( )
{
int i,n,x, sum=0;
printf("Fnter then value \n");
scanf("%d", &n);
for(i= ;i<=n;i++)
{
scanf("%d",&x);
if(x <0)
continue;
sum += x;
}
printf("Sum= %d",sum);
getch( );
return 0;
}

Here, once a negative value is given as input for 'x', the if condition becomes true and so the continue statement will be executed. That means the remaining statements in the for loop will be omitted. So, `sum+=x' will not be executed. But again the loop will be executed  for the next value of i and again 'x' value will be read and checked it is negative or not.

b) using break statement

int main()
{
int i, n, x, sum=0;
printf("Enter then value \n");
scanf("%d",&n);
for(i= 1 ;i <=n;i++)
{
scanf("%d",&x);
if(x<0)
break;
sum += x;
}
printf("Sum= %d",sum);
getch( );
return 0;
}

Once a negative value is inputted for x, the if condition becomes true and so the break statement will be executed. Hence the control will be brought out of the 'for', loop, once for all. So, the printf statement prints the 'sum' value only for the numbers inputted so far.

POST A NEW COMMENT

• Input (stdin)

Output (stdout)

Input (stdin)

Expected Output

Compiler Message

Input (stdin)

2    3