C Program To Reverse a Number

C Program To Reverse a Number

Write a program to reverse a number or digits in C, a very basic and commonly asked question in interviews and exams. Today you will learn the standard method to reverse the number or digits and later we will tell you the error or bug which ever reverse number program have and how to remove that error completely!



Source Code:
#include <stdio.h>
#include <conio.h>

void main(){
    int num , rev=0;
    printf("--- Reverse Number Program In C ---\n\n");
    printf("Enter a Number: ");
    scanf("%d",&num);
    while(num>0){
        rev = rev*10 + num%10;
        num = num / 10;
    }
    printf("Reverse is %d",rev);
    getch();
}


Output:
Reverse-Number-Output

ERROR / BUG:
The above program work perfectly but when you enter a number having 0 (zero)s at the end than you will find out what's wrong with this program! ( See above output image carefully )
e.g If you enter 540 than the reversed number will be 45 instead of 045.

Correction:
So the only thing we have to do is count the leading number of zeros and print them before the reversed number. Lets see how to do that!

Correct Source Code:
#include <stdio.h>
#include <conio.h>

void main(){
    int num , temp, rev=0, c=0, i=0;
    printf("--- Reverse Number Program In C ---\n\n");
    printf("Enter a Number: ");
    scanf("%d",&num);
    temp = num;
    while(num>0){
        rev = rev*10 + num%10;
        //Check for zeros
        if(num%10==0 && i==0) c++;
        else i=1;
        num = num / 10;
    }
    printf("Reverse is ");
    for(i=0;i<c;i++){
      printf("0");
    }
    printf("%d",rev);
    getch();
}
Output:
correct-reverse-in-c-output

4 Comments Leave new

sir please help me with this also pleaseeeeeeeeeeeeeeeee
Q: write a program to print the following
user input:mirror
required output is:miror

Reply

I guess you missed our reply to this question....
visit-> Here

Reply

if i give number as 1234 then i want the reverse of a number as3124 . help me

Reply

@Prashanth you just want to change the location of last digit?

Reply

Make sure you tick the "Notify Me" box below the comment form to be notified of follow up comments and replies.