C Tutorial/Statement/Do While
Содержание
Nest for loop inside do while loop
<source lang="cpp">#include <stdio.h> int main() {
int start = 10; long delay = 1000; do { printf(" %d\n",start); start--; for(delay=0;delay<100000;delay++); /* delay loop */ } while(start>0); printf("Zero!\nBlast off!\n"); return(0);
}</source>
10 9 8 7 6 5 4 3 2 1 Zero! Blast off!
Read number in a range
<source lang="cpp">#include <stdio.h> int main(){
printf("Please enter the number to start\n"); printf("the countdown (1 to 100):"); int start; scanf("%d",&start); do { printf("%d",start); }while(start<1 || start>100);
}</source>
Please enter the number to start the countdown (1 to 100):12 12
Reversing the digits: do while loop
<source lang="cpp">#include <stdio.h> int main(void) {
int number = 123; int rightMostNumber = 0; int temp = 0; temp = number; do { rightMostNumber = 10*rightMostNumber + temp % 10; temp = temp/10; } while (temp); printf ("\nThe number %d reversed is %d\n", number, rightMostNumber ); return 0;
}</source>
The number 123 reversed is 321
The do...while loop
- The do...while loop checks the conditional expression only after the repetition part is executed.
- The do...while loop is used when you want to execute the loop body at least once.
The general form of the do...while loop is
<source lang="cpp">do {
repetition part; } while (expr);</source>