indefinite loop and break : For Break « Language Basics « C / ANSI-C






indefinite loop and break



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

void main()
{
   char answer = 'N';  /* Records yes or no to continue the loop */
   double total = 0.0; 
   double value = 10.0; /* Value entered                          */
   int count = 0;      /* Number of values entered               */

   printf("\nThis program calculates the average of"
                                       " any number of values.");
   /* Indefinite loop */
   for( ;; ) {
     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 );   

     if( tolower(answer) == 'n' )    
       break;                         /* Exit from the loop      */
   }
   /* output the average to 2 decimal places */
   printf ("\nThe average is %.2lf\n", total/count ); 
}


           
       








Related examples in the same category

1.Break a infinite loop
2.Use break to terminate a for loop
3.Use break in for loop to exit
4.Nested for loop and break