Reverse decimal digits

Logic is simple we start extracting digits from LSB. Say the number is decimal so base will be 10. Now if we divide the number by 10 then the modulo reminder is the LSB digit and same time division result will be shifted to right. Same way again we can get next digit and shift the number right. Now as we are getting digits we can construct a new number and multiply by 10 each time in the iteration. This way the digits will be shifted left in the MSB in the new number. In this way iteration will extract LSB digit from the original number and this same digit will be pushed to the MSB of the new number. Finally we will get the digits in the reversed order in the resultant number. We can modify the base 10 with base 8 for octal number or base 16 for hexadecimal number or base 2 for binary number and same program logic can be reused.

Source code

#include <stdio.h>
int main(int argc, char *argv[])
  int num = 0;
  int rnum = 0, onum;
  printf ("Enter a number : " );
  scanf ("%d", &num);
  onum = num;
10    {
11      rnum *= 10;
12      rnum += onum % 10;
13      rnum = onum /10;
14    }
15    while(onum > 0);
16    printf ("Original %d == Reverse %d", num, rnum);
18  }


Enter a number : 12345
Original 12345 == Reverse 54321
Enter a number : 12321
Original 12321 == Reverse 12321

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

palindrome, convert case, string to int, int to string, reverse decimal digits, signed and unsigned compare, palindrome digits, upper and lower 16bit of 32bit unsigned, Exchange variables,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan