11.10.2012

User Define Function- Reverse Number

Q. Write a C program to create a function that would reverse the any number.
For example:
Assume enter number = 57429
Result = 92475

Ans.

/*c program for reverse number using user define function- rev */
#include<stdio.h>
int rev(int );
int main()
{
 int num,res;  // res = result
 printf("Enter any number : ");
 scanf("%d", &num);
 res = rev(num);
 printf("Reverse order number = %d",res);
 return 0;
}

int rev(int n)
{
 int r=0;
 for(; n>=1; n=n/10)
   r = r*10 + n%10;
 return r;
}

The output of above program would be:


Output of reverse number using user define function C program
Figure: Screen shot for reverse digit using
user define function C program


5 comments:

  1. There's a huge mistake in your reverse function named rev(). You should've written the code as follows for the rev() function.

    Edited Code :

    int rev(int n)
    {
    int r=0;
    for(; n>=1; n=n/10)
    {
    r = r*10 + n%10;
    }
    return r;
    }


    Mistake : "return r ;" line should be placed outside the for loop , not in the for loop.

    Your program generates only last digit of entered number as output.
    For example : If input is 5426 then it generates 6 as output instead of generating 6245.

    So I think you need to edit the code of rev() function.

    ReplyDelete
    Replies
    1. @Valmik, Thanks friend, code has been edited.

      Delete
    2. Pleasure to help you out. :)

      Delete
    3. Valmik bhai
      Notice:- He didn't used any curley braces after for loop. That means for loop ends with that only line "r=r/10+n%10" and return is outside the for loop

      Delete
    4. Valmik bhai
      Notice:- He didn't used any curley braces after for loop. That means for loop ends with that only line "r=r/10+n%10" and return is outside the for loop

      Delete