C/Language Basics/For Break

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Break a infinite loop

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
  for(;;)
    if(getchar()=="A") abort();
  return 0;
}


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 ); 
}


Nested for loop and break

  
#include <stdio.h>
int main(void)
{
  int i, j;
  for( i = 0; i < 5; i++) {
    for(j = 0; j < 100; j++) {
      printf("%d", j);
      if(j == 5) 
          break;
    }
    printf("\n");
  }
  return 0;
}


Use break in for loop to exit

  
#include <stdio.h>
int main(void)
{
  int i;
  for(i = 1; i < 100; i++) {
    printf("%d ", i);
    if(i == 10) 
        break; /* exit the for loop */
  }
  return 0;
}


Use break to terminate a for loop

#include <stdio.h>
int main(void)
{
  int t;
  for(t = 0; t < 100; t++) {
     printf("%d ", t);
     if(t == 11) 
        break;
  }
  return 0;
}