THE DO WHILE STATEMENT
The do { } while statement allows a loop to continue
whilst a condition evaluates as TRUE (non-zero). The loop is
executed as least once.
/* Demonstration of DO...WHILE */ #include <stdio.h> main() { int value, r_digit; printf("Enter the number to be reversed.\n"); scanf("%d", &value); do { r_digit = value % 10; printf("%d", r_digit); value = value / 10; } while( value != 0 ); printf("\n"); }
The above program reverses a number that is entered by the user. It does this by using the modulus % operator to extract the right most digit into the variable r_digit. The original number is then divided by 10, and the operation repeated whilst the number is not equal to 0.
It is our contention that this programming construct is improper and should be avoided. It has potential problems, and you should be aware of these.
One such problem is deemed to be lack of control. Considering the above program code portion,
do { r_digit = value % 10; printf("%d", r_digit); value = value / 10; } while( value != 0 );
there is NO choice whether to execute the loop. Entry to the loop is automatic, as you only get a choice to continue.
Another problem is that the loop is always executed at least once. This is a by-product of the lack of control. This means its possible to enter a do { } while loop with invalid data.
Beginner programmers can easily get into a whole heap of trouble, so our advice is to avoid its use. This is the only time that you will encounter it in this course. Its easy to avoid the use of this construct by replacing it with the following algorithms,
initialise loop control variable while( loop control variable is valid ) { process data adjust control variable if necessary }
Okay, lets now rewrite the above example to remove the do { } while construct.
/* rewritten code to remove construct */ #include <stdio.h> main() { int value, r_digit; value = 0; while( value <= 0 ) { printf("Enter the number to be reversed.\n"); scanf("%d", &value); if( value <= 0 ) printf("The number must be positive\n"); } while( value != 0 ) { r_digit = value % 10; printf("%d", r_digit); value = value / 10; } printf("\n"); } Sample Program Output Enter the number to be reversed. -43 The number must be positive Enter the number to be reversed. 423 324