Programming in C

(Barry) #1
The doStatement 61

do
program statement
while ( loop_expression);


Execution of the dostatement proceeds as follows: the program statementis executed
first. Next, the loop_expressioninside the parentheses is evaluated. If the result of eval-
uating the loop_expressionis TRUE, the loop continues and the program statement
is once again executed. As long as evaluation of the loop_expressioncontinues to be
TRUE, the program statementis repeatedly executed.When evaluation of the expres-
sion proves FALSE, the loop is terminated, and the next statement in the program is exe-
cuted in the normal sequential manner.
The dostatement is simply a transposition of the whilestatement, with the looping
conditions placed at the end of the loop rather than at the beginning.
Remember that, unlike the forand whileloops, the dostatement guarantees that the
body of the loop is executed at least once.
In Program 5.8, you used a whilestatement to reverse the digits of a number. Go
back to that program and try to determine what would happen if you typed in the
number 0 instead of 13579.The loop of the whilestatement would never be executed
and you would simply end up with a blank line in your display (as a result of the display
of the newline character from the second printfstatement). If you use a dostatement
instead of a whilestatement, you are assured that the program loop executes at least
once, thus guaranteeing the display of at least one digit in all cases. Program 5.9 shows
this revised program.


Program 5.9 Implementing a Revised Program to Reverse the Digits of a Number


// Program to reverse the digits of a number


#include <stdio.h>


int main ()
{
int number, right_digit;


printf ("Enter your number.\n");
scanf ("%i", &number);

do {
right_digit = number % 10;
printf ("%i", right_digit);
number = number / 10;
}
while ( number != 0 );

printf ("\n");

return 0;
}

Free download pdf