C Program to Reverse a Given Number

Posted by on 18 Mar 2010. Filed under C/C++ Examples, C/C++ Programming. You can follow any responses to this entry through the RSS 2.0. You can leave a response or trackback to this entry

Here is a program that mathematically reverse any given numer. The program uses simple functions, an easy and fast flow.


Code

#include "stdio.h"
#include "conio.h"
void main()
{
int num, rev = 0, dig;
printf("Enter a number: \t");
scanf("%d", &num);
while(num>0)
 {
 dig = num % 10;
 rev = rev * 10 + dig;
 num = num / 10;
 }
printf("\nThe reversed numer is: \t%d\n", rev);
getch();
}

Output


Analysis

Line 1&2 include “stdio.h” for printf(); & scanf(); and “conio.h” for getch();.

Line 5 initialize the three variable.

Line 6 asking for the number.

Line 7 Pick the number and assign it in the variable num.

From line 8 to line 13 is the core of the program as we taking the first digit of the given number, putting it temporally in the variable dig (line 10) than putting it as a last digit at the variable rev (line 11) then deducing that digit from the original number (line 12) and continue doing the process for all digits (that`s why the condition of the while loop is num>0).

Line 14 print the answer, and line 15 pause the program.


Advanced Analysis

Shortest Code:

1- We can remove line 10 and edit line 11 to be  rev = rev * 10 + num % 10; then we don`t need to initialize the variable dig at line 5 and that reduced the memory need for this program with int size (4 Bytes in most cases. Huge difference, Isn’t it :D ?).

2- Line 12 can be replaced with num /= 10; but it is just affect the style not the size or the speed of the program


Share

16 Comments for “C Program to Reverse a Given Number”

  1. rt8s

    what will be the value of dig when num % 10

  2. andy

    I’m not getting the correct output for 5 or more digits.I’m using Borland c++ 4.5.
    Just want to reverse a number of any length.plz rply

    • I just tried it now (in visual studio 2012) and it works for any number with any digits count (even lower than 4 digits).

      Can you debug the code in your IDE “Borland c++ 4.5″ and detect the problem? or just let me know if I can help.

      • andy

        It is working well & fine for 4 digits(even lower than 4 digits).I’m facing a problem with 5 or more digits.Suppose when i gave 12345 & 123456 i’m getting -11215 & 0 respectively as the output.Is it compiler specific..

        • oops, I did a mistake in the comment but the algorithm is working fine in 4 digit and any number more than 4 digits.

          Nothing in the code is compiler dependent.

          However, if you are trying this in a very old machine which has an 8-bits int or your compiler converted the int somehow to __int8 it would make a problem, so change the first line in the main function from “int” to “long” and let me know…

          • andy

            First of all thanks for ur quick rply.Yes changing it to long has solved my prblm. I’m using Borland c++ 4.5 which is for 32bit machine.But i’ve installed 32bit os on a 64bit machine.Is that a prblm?.Sry fr troubling u again for such a silly question.

            But these small prblms i often face while programming,where i arrive at a diff. output & get stuck & finally loose my interest in programming..I’m learning C for 1-1/12 years.Still i face prblms in some of the basic questions of array,pointers etc,.
            Thanks a lot fr ur rply….

          • andy

            thanks fr ur rply….

  3. andy

    Also i don’t want the user to enter the limit explicitly and store it into some variable..& continue my loop upto the entered limit.On the output screen he(user) should just be prompted to enter the number & on pressing the Enter Button will fetch him the result.Is it possible..plz rply

    Thanks in advance

  4. andy

    Waiting fr ur rply..

    • “But these small prblms i often face while programming,where i arrive at a diff. output & get stuck & finally loose my interest in programming..I’m learning C for 1-1/12 years.Still i face prblms in some of the basic questions of array,pointers”

      Actually C/C++ has a lot of tricky stuff when it comes to pointers, I was lucky because the first one teaches me that was a very good professor at the university, and you need to find someone or some good tutorial online for that (if I find such a good one I will email you) other wise debugging is you friend.
      whenever a problem happen go and debug the code, track the pointers values and see what they point to and when the program crash you will have a good idea what made the problem.
      I recommend you to use Visual studio, as it has a lot of good testing/debugging tools that will make you life much more easier.

  5. new in c

    hii can anyone explain me the logic with a example?/ plz

  6. andy

    Hi! holmez

    hope u good there.
    I’m back with a question
    Why the array index in c,c++, java & also in other languages(except VB)alwyz starts with zero..This is a question which I was asked when i went to an internship program in a company & again the same question was asked to me by my teacher in the class.The same question followed me when i appeared for a campus interview..The first time when it was asked, i took no time searching the internet but hardly got an answer to it..and some of the answers were not clear to me(I coudn’t understand the answers).PLz help me with it..

    Thanks in advance..

    • well, I don’t know an answer for sure but if I’ve been asked this question I will have two answers:

      1- Generally numbers should start with 0 not 1, I can argue about that a lot but you can chack this reference “http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF” or just google “why should numbers start at zero”

      2- In c/c++ the name of the array is pointer to the first element, and we can consider the index as the offset in memory for the required element.

      Hopefully this will help you, I googled the questions and find that most popular answer are pretty much around these two points.

      Also, if you have been asked this type of questions in an interview, I think it is okay to ask the interviewer for the right answer or what he was expecting to hear at the end of the interview.

Leave a Reply

Log in | Designed by Gabfire themes

[2checkout]