Tag Archives: func
C++ || Snippet – How To Reverse An Integer Using Modulus & While Loop
This page will consist of a simple program which demonstrates how to reverse an integer (not an int array) using modulus and a while loop.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
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 |
#include <iostream> using namespace std; // function prototype int ReverseNumber(int number); int main() { // declare variables int number = 0; int numReversed = 0; // get data from user cout << "Enter a number: "; cin >> number; // function call which will return the reversed number numReversed = ReverseNumber(number); // display new data to user cout <<endl<< number << " reversed is: "<< numReversed <<endl; return 0; }// end of main int ReverseNumber(int number) { // declare function variable int rev=0; while(number > 0) { rev = rev * 10 + (number % 10); number = number/10; } return rev; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compiled three separate times to display different output)
==== RUN #1 ====
Enter a number: 2012
2012 reversed is: 2102==== RUN #2 ====
Enter a number: 1987
1987 reversed is: 7891==== RUN #3 ====
Enter a number: 241
241 reversed is: 142