﻿ C++ Exercises: Display the number in reverse order - 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:

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:

C++ Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

﻿