Programming in C

(Barry) #1

60 Chapter 5 Program Looping


Program 5.8 Reversing the Digits of a Number
// Program to reverse the digits of a number

#include <stdio.h>

int main (void)
{
int number, right_digit;

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

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

printf ("\n");

return 0;
}

Program 5.8 Output
Enter your number.
13579
97531

Each digit is displayed as it is extracted by the program. Notice that you did not include
a newline character inside the printfstatement contained in the whileloop.This forces
each successive digit to be displayed on the same line.The final printfcall at the end of
the program contains just a newline character, which causes the cursor to advance to the
start of the next line.

The doStatement


The two looping statements discussed so far in this chapter both make a test of the con-
ditions beforethe loop is executed.Therefore, the body of the loop might never be exe-
cuted at all if the conditions are not satisfied.When developing programs, it sometimes
becomes desirable to have the test made at the endof the loop rather than at the begin-
ning. Naturally, the C language provides a special language construct to handle such a
situation.This looping statement is known as the dostatement.The syntax of this state-
ment is as follows:
Free download pdf