The break Statement

The break Statement

The break statement can be placed only in the body of a for loop, while loop, or do while loop. (It’s valid in a switch statement, too, but that topic isn’t covered until later today.) When a break statement is encountered, execution immediately exits the loop. The following is an example:

for ( count = 0; count < 10; count++ ) {
   if ( count == 5 )
      break;
    }

Left to itself, the for loop would execute 10 times. On the sixth iteration, however, count is equal to 5, and the break statement executes, causing the for loop to terminate. Execution then passes to the statement immediately following the for loop’s closing brace.

Flow of Break Statement

break statement flow in c AndroWep-Tutorials

Example

  # include <stdio.h>
  int main()
  {
      int i;
      double number, sum = 0.0;
      for(i=1; i <= 10; ++i)
      {
          printf("Enter a n%d: ",i);
          scanf("%lf",&number);
          // If the user enters a negative number, the loop ends
          if(number < 0.0)
          {
              break;
          }
          sum += number; // sum = sum + number;
      }
      printf("Sum = %.2lf",sum);

      return 0;
  }

Output

  Enter a n1: 2.4
  Enter a n2: 4.5
  Enter a n3: 3.4
  Enter a n4: -3
  Sum = 10.30

Continue Statement

# include <stdio.h>
int main(){

    int x;
    printf(“Printing only the even numbers from 1 to 10\n”);
    for( x = 1; x <= 10; x++ )

    {
        if( x % 2 != 0 )    /* See if the number is NOT even */
        continue;      /* Get next instance x */
        printf( “\n%d”, x );

    }
}

Example

#include <stdio.h>

  int main () {

     /* local variable definition */
     int a = 10;

     /* do loop execution */
     do {

        if( a == 15) {
           /* skip the iteration */
           a = a + 1;
           continue;
        }

        printf("value of a: %d\n", a);
        a++;

     } while( a < 20 );

     return 0;
  }

Output

  value of a: 10
  value of a: 11
  value of a: 12
  value of a: 13
  value of a: 14
  value of a: 16
  value of a: 17
  value of a: 18
  value of a: 19

Why we use break statement in C?

break statement in C. When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).

Can we use break in if statement in C?

break statement shall appear only in or as a switch body or loop body. A break statement terminates execution of the smallest enclosing switch or iteration statement. It can be used to terminate a case in the switch statement.