w3resource

C++ Exercises: Display the number in reverse order

C++ For Loop: Exercise-30 with Solution

Write a program in C++ to display the numbers in reverse order.

Visual Presentation:

C++ Exercises: Display the number in reverse order

Sample Solution:-

C++ Code :

#include <iostream> // Including input-output stream header

using namespace std; // Using standard namespace to avoid writing std::

int main() // Start of the main function
{
    int num, r, sum = 0, t; // Declaration of integer variables: 'num' (input number), 'r' (remainder), 'sum' (stores the reversed number), 't' (temporary variable)

    cout << "\n\n Display the number in reverse order:\n"; // Displaying a message on the console
    cout << "-----------------------------------------\n";
    cout << " Input a number: "; // Asking the user for a number
    cin >> num; // Reading the number from the user

    for (t = num; num != 0; num = num / 10) // Reversing the number using a loop
    {
        r = num % 10; // Getting the rightmost digit of the number
        sum = sum * 10 + r; // Constructing the reversed number by adding digits one by one from the original number
    }

    cout << " The number in reverse order is : " << sum << endl; // Displaying the reversed number
}

Sample Output:

 Display the number in reverse order:                                  
-----------------------------------------                              
 Input a number: 12345                                                 
 The number in reverse order is : 54321  

Flowchart:

Flowchart: Display the number in reverse order

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find LCM of any two numbers using HCF.
Next: Write a program in C++ to find out the sum of an A.P. series.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/for-loop/cpp-for-loop-exercise-30.php