SOURCE FILE: 6.09ReverseNum.cpp
//
// Example 6.09. Program to print the digits of a
// nonnegative input integer in reverse order
//
#include <iostream.h>
int main(void)
{
int ReadNum(void);
void PrintReverse(int num);
int num; // nonnegative input integer
num = ReadNum();
PrintReverse(num);
return 0;
}
//
// Function to print instructions and repeatedly read
// integers until the user enters a nonnegative integer,
// which the function returns
// Pre: none
// Post: A nonnegative integer has been returned.
//
int ReadNum(void)
{
int num; // nonnegative input integer
cout << "This program prints a nonnegative integer backwards.\n\n";
do
{
cout << "Enter a nonnegative integer: ";
cin >> num;
}
while (num < 0);
return num;
}
//
// Function to print the digits of a nonnegative integer
// in reverse order.
// Pre: num is a nonnegative integer.
// Post: The digits of num have been displayed in reverse order.
//
void PrintReverse(int num)
{
int RightmostDigit; // rightmost digit of num
cout << num << " backwards is ";
do
{
RightmostDigit = num % 10;
cout << RightmostDigit;
num /= 10; // move next digit into rightmost position
}
while (num > 0);
cout << endl;
}