C Tutorial/Statement/Do While

Материал из C\C++ эксперт
Версия от 10:32, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Nest for loop inside do while loop

#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);
}
10
       9
       8
       7
       6
       5
       4
       3
       2
       1
      Zero!
      Blast off!

Read number in a range

#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);
}
Please enter the number to start
      the countdown (1 to 100):12
      12

Reversing the digits: do while loop

#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;
}
The number 123 reversed is  321

The do...while loop

  1. The do...while loop checks the conditional expression only after the repetition part is executed.
  2. 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


do {
       repetition part;
    } while (expr);