C programming break and continue statements

Till now, we have learned about the looping with which we can repeatedly execute the code such as, for loop and while & do … while loop.

Just think what will you do when you want to jump out of the loop even if the condition is true or continue repeated execution of code skipping some of the parts?

For this C provides break and continue statements. By the help of these statements, we can jump out of loop anytime and able continue looping by skipping some part of the code.

The Break Statement in C

The break statement is used to exit the loop irrespective of whether the condition is true or false. Whenever a “break” is encountered inside the loop, the controls are sent outside the loop.

It interrupts the flow of the program by breaking the loop and continues the execution of code which is outside the loop.

The common use of break statement is in switch case where it is used to skip remaining part of the code.

Structure of break Statement

In while loop

while (test_condition)
{
  statement1;
  if (condition )
     break;
  statement2;
}

In do…while loop

do
{
  statement1;
  if (condition)
     break;
  statement2;
}while (test_condition);

In for loop

for (int-exp; test-exp; update-exp)
{
  statement1;
  if (condition)
     break;
  statement2;
}

Let us see with an example:

for (i=0; i<1000; i++){
printf("%d\n",i);
if (i==5){
break;
}
}

Output: 0, 1, 2, 3, 4, 5 and not 0 to 100

The continue statement in c

The continue statement in c is used to immediately move to the next of the loop. The control is taken to the next iteration, thus skipping everything below continue inside the loop for that iteration.

Unlike break statement, continue statement when encountered doesn’t terminate the loop, rather interrupts a particular iteration.

Structure of continue statement

In while loop

while (test_condition)
{
  statement1;
  if (condition )
     continue;
  statement2;
}

In do…while loop

do
{
  statement1;
  if (condition)
     continue;
  statement2;
}while (test_condition);

In for loop

for (int-exp; test-exp; update-exp)
{
  statement1;
  if (condition)
     continue;
  statement2;
}

Let us look at an example:

int  skip=5;
int i=0;
while(i<10){	
if(i  != skip)	
continue;
else
printf(%d”,i);
}

Output: 5 and not 0…………….9

Notes:

1. Sometimes, the name of the variable might not indicate the behavior of the program.

2. Break statement completely exits the loop

3. Continue statement skips the particular iteration of the loop

Was this article helpful?
YesNo

Leave a Comment

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