Electrofriends

To reverse a given number

by Ranjith | December 4th, 2008.

Here is the program to mathematically reverse the entered integer. The program uses simple library functions, and an easy flow.

Logic :  The main idea here is to trace the entered number till its length, and slicing up in each of the iterations. The program asks the user to enter the number to reverse. Sets two variable flags to hold each digits and the final reversed number.
The while loop slices down the given number to digits, and appends to the reversed flag ‘rev’. Finally it prints out the reversed number after exiting from the while loop.

The similar logic for slicing up the given number is used in other programs like, finding the sum of digits and, palindrome checking programs

#include<stdio.h>
#include<math.h>
void main()
{
long int num, rev = 0, dig;
clrscr();
printf(“\n\n\t ENTER A NUMBER…: “);
scanf(“%ld”, &num);
while(num>0)
{
dig = num % 10;
rev = rev * 10 + dig;
num = num / 10;
}
printf(“\n\t REVERSED NUMBER IS…: %ld”, rev);
getch();
}
Download exe and source code here.


Share and Enjoy:
  • Digg
  • Technorati
  • StumbleUpon
  • Twitter
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Mixx
  • Yahoo! Buzz
  • LinkedIn
  • NewsVine
  • RSS
  • email
Similar Posts:

Leave a Reply

Share and enjoy

    • Digg
    • Facebook
    • Technorati
    • StumbleUpon
    • Twitter
    • Reddit
    • del.icio.us
    • Yahoo! Buzz
Copyright©2009 www.electrofriends.com All Rights Reserved. Powered by Dhyeya