The C++ Programming Language

Reverse a number Example Program


Click below to go directly to a specific section:
Description | Source Code | Sample Run | Program Notes

Description

This program takes a number of three digit or less and reverse the order of the number using the C++ programming language by displaying the result.

Source Code

#include <stdlib.h>
#include <iomanip.h>
#include <iostream.h>
#include <math.h>

int number;
int reverse(int);

main()
{
    cout << "Please enter an Integer value of 3 digits or less = ";
    cin >> number;
    cout << "The number with its digits reversed is = ";
    number=abs(number);

    if (number<10)
        cout << setw(1) << setfill('0') << reverse(number) << endl;
    else if (number<100)
        cout << setw(2) << setfill('0') << reverse(number) << endl;
    else if (number<1000)
        cout << setw(3) << setfill('0') << reverse(number) << endl;
    else
        cout << "Sorry, number is not valid.";
        return 0;
}

int reverse(int number)
{
    int digit1, digit2, digit3, digit4;

    if (number<10)
        return number;
    else if (number<100)
    {
        digit1=div(number,10).quot;
        digit2=div(number,10).rem;
        return (digit2*10 + digit1);
    }
    else if (number<1000)
    {
        digit1=div(number,100).quot;
        number=div(number,100).rem;
        digit2=div(number,10).quot;
        digit3=div(number,10).rem;
        return (digit3*100 + digit2*10 + digit1);
    }

    return 0;
}

Sample Run

Please enter an Integer value of 3 digits or less =  123
The number with its digits reversed is =  321

Program Notes

This program ask the user to enter a number of 3 digit or less, it read in the number, send it through a nested If statement, than the number and its condition is sent to the reverse function that return it in its reversed order. It works perfectly without any errors or warnings.
[Back] [Home]

Last modified: 03:37 PM on 11/21/1996