C break and continue Example

C break and continue statement; In this tutorial, i am going to show you what is break and continue statement in c and how to use break and continue statements with the help of examples.

C break and continue Example

  • C break Statement
  • C Continue Statement

C break Statement

Break Statement is a loop control statement that is used to terminate the loop.

Syntax of Break Statement in C

See the following syntax of break statement in c; as shown below:

break;

Note that:- The break statement is almost always used with if...else statement inside the loop.

Example 1 – C break statement with For Loop

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

Output

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

Example 2 – Use of C break Statement in a while loop

#include <stdio.h>
int main()
{
     int num =0;
     while(num<=100)
     {
        printf("value of variable num is: %d\n", num);
        if (num==2)
        {
            break;
        }
        num++;
     }
     printf("Out of while-loop");
     return 0;
}

Output:

value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Out of while-loop

C continue Statement

The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.

Syntax of C continue Statement

See the following continue statement in c; as shown below:

continue;

Note that:- The continue statement is almost always used with the if...else statement.

Example 1 – c continue statement inside for loop

#include <stdio.h>
int main() {
   int i;
   double number, sum = 0.0;
   for (i = 1; i <= 5; ++i) {
      printf("Enter a n%d: ", i);
      scanf("%lf", &number);
      if (number < 10) {
         continue;
      }
      sum += number; // sum = sum + number;
   }
   printf("Sum = %.2lf", sum);
   return 0;
}

Output

Enter n1: 1.1
Enter n2: 2.2
Enter n3: 5.5
Enter n4: 4.4
Enter n5: -3.4
Enter n6: -45.5
Enter n7: 34.5
Enter n8: -4.2
Enter n9: -1000
Enter n10: 12
Sum = 59.70

Example 2 – c continue statement with While loop

#include <stdio.h>
int main()
{
    int counter=10;
    while (counter >=0)
    {
	 if (counter==7)
	 {
	      counter--;
	      continue;
	 }
	 printf("%d  ", counter);
	 counter--;
    }
    return 0;
}

Output

10 9 8 6 5 4 3 2 1 0

More C Programming Tutorials

Leave a Comment