C/Language Basics/For Break — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
|
(нет различий)
|
Версия 17:20, 25 мая 2010
Содержание
Break a infinite loop
<source lang="cpp">
- include <stdlib.h>
- include <stdio.h>
int main(void) {
for(;;) if(getchar()=="A") abort(); return 0;
}
</source>
indefinite loop and break
<source lang="cpp">
- 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 );
}
</source>
Nested for loop and break
<source lang="cpp">
- 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;
}
</source>
Use break in for loop to exit
<source lang="cpp">
- 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;
}
</source>
Use break to terminate a for loop
<source lang="cpp">
- include <stdio.h>
int main(void) {
int t; for(t = 0; t < 100; t++) { printf("%d ", t); if(t == 11) break; } return 0;
}
</source>