C Tutorial/Statement/While Loop
Содержание
Between a while loop and a for loop
<source lang="cpp">for(A;B;C){
printf("%d\t",i);
} It becomes
A; while(B) {
printf("%d\t",i); C;
}</source>
Put function into while loop condition statement
<source lang="cpp">#include <stdio.h>
int main() {
puts("Start typing."); puts("Press ~ then Enter to stop"); while(getchar() != "~") ; printf("Thanks!\n"); return(0);
}</source>
Start typing. Press ~ then Enter to stop a a a a a a~ Thanks!
The while loop
The general format for a while loop is
<source lang="cpp">while (condition) {
simple or compound statement (body of the loop); }</source>
While loop and sum integers
<source lang="cpp">#include <stdio.h> int main(void) {
long sum = 0L; int i = 1; int count = 0; printf("\nEnter the number of integers you want to sum: "); scanf(" %d", &count); while(i <= count){ sum += i++; } printf("Total of the first %d numbers is %ld\n", count, sum); return 0;
}</source>
Enter the number of integers you want to sum: 1 Total of the first 1 numbers is 1
while loop nested in a for loop
<source lang="cpp">#include <stdio.h> int main(void) {
long sum = 1L; int j = 1; int count = 10; int i; for(i = 1 ; i <= count ; i++) { sum = 1L; j=1; printf("\n1"); while(j < i){ sum += ++j; printf("+%d", j); } printf(" = %ld\n", sum); } return 0;
}</source>
1 = 1 1+2 = 3 1+2+3 = 6 1+2+3+4 = 10 1+2+3+4+5 = 15 1+2+3+4+5+6 = 21 1+2+3+4+5+6+7 = 28 1+2+3+4+5+6+7+8 = 36 1+2+3+4+5+6+7+8+9 = 45 1+2+3+4+5+6+7+8+9+10 = 55