In this program, we are going to share reverse a number using stack with the output. If you are a C++ beginner and want to start learning the C++ programming, then keep your close attention in this tutorial as I am going to share how to write reverse a number using the stack.
Copy the below C++ program and execute it with the help of C++ compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <bits/stdc++.h> using namespace std; stack <int> st; void push_digits(int number) { while (number != 0) { st.push(number % 10); number = number / 10; } } int reverse_number(int number) { push_digits(number); int reverse = 0; int i = 1; while (!st.empty()) { reverse = reverse + (st.top() * i); st.pop(); i = i * 10; } return reverse; } int main() { int number = 987654321; cout << reverse_number(number); return 0; } |
123456789
Liked this program? Do Like & share with your friends 🙂
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: algorithm to reverse a string using stack, c programs, c programs with output, c++ program to reverse a number, c++ programs with example, How to reverse a number using stack