# C++ program to extract and print digits in reverse order of a number

**Extracting digits in C++**: Here, we are going to learn **how to extract and print the digits in reverse order of a number in C++?**

Submitted by Anuj Singh, on June 04, 2019

Here, we are going to use some mathematical base while programming. The problem is, when you ask a number from the user, the user would give input as multiple digit number (considering integer only). So it is easy to find the type of number but it’s not easy to find the number of digits in the number.

So, in the following problem, we are going to use the mathematical trick of:

- Subtracting the remainder after dividing it by 10 i.e. eliminating the last digit.
- Dividing an integer by 10 gives up an integer in computer programming (the above statement is only true when the variables are initialized as int only).

**Example:**

Input: 12345 Output: 54321

### C++ code to extract and print digits of a number in reverse order

#include <iostream> using namespace std; int main() { int num; int a = 0; cout << "Enter a number: "; cin >> num; cout << "\n"; for (int i = 1; num > 0; i++) { a = num % 10; cout << a; num = num / 10; } return 0; }

**Output**

Enter a number: 123456 654321

Here we are first using a loop with condition num>0, and the last digit of the number is taken out by using simple % operator after that, the remainder term is subtracted from the num. Then number num is reduced to its 1/10^{th} so that the last digit can be truncated.

The cycle repeats and prints the reverse of the number num.

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

**Ad:**
Are you a blogger? Join our Blogging forum.

Learn PCB Designing: PCB DESIGNING TUTORIAL