C - Statement break Statement

Introduction

You can use break statement in the switch statement.

The break statement can stop a loop-any kind of loop. For instance:

char answer = 0;
for( ;; )
{
  /* Code to read and process some data */
  printf("Do you want  to enter some more(y/n): ");
  scanf("%c", &answer);
  if(tolower(answer) == 'n')
    break;                               // Go to statement after the loop
}

Here we have a loop that will potentially execute indefinitely.

The scanf() function reads a character into answer, and if the character entered is n or N, the break statement will be executed.

The following example computes the average of an arbitrary number of values:

Demo

#include <stdio.h>
#include <ctype.h>                    // For tolower() function

int main(void)
{
      char answer = 'N';                  // Decision to continue the loop
      double total = 0.0;                 // Total of values entered
      double value = 0.0;                 // Value entered
      unsigned int count = 0;             // Number of values entered

      printf("\nThis program calculates the average of"
                                          " any number of values.");

      for( ;; )                           // Indefinite loop
      {/*  w  w  w.j  av  a2  s .  c  o m*/
        printf("\nEnter a value: ");      // Prompt for the next value
        scanf(" %lf", &value);            // Read the next value
        total += value;                   // Add value to total
        ++count;                          // Increment count of values

        // check for more input
        printf("Do you want to enter another value? (Y or N): ");
        scanf(" %c", &answer);            // Read response Y or N
    if(tolower(answer) == 'n')        // look for any sign of no
      break;                          // Exit from the loop
  }
  // Output the average to 2 decimal places
  printf("\nThe average is %.2lf\n", total/count);
  return 0;
}

Result

Related Topics

Exercise