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:
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:
Figure: Screen shot for reverse digit using user define function C program |
There's a huge mistake in your reverse function named rev(). You should've written the code as follows for the rev() function.
ReplyDeleteEdited 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.
@Valmik, Thanks friend, code has been edited.
DeletePleasure to help you out. :)
DeleteValmik bhai
DeleteNotice:- 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
Valmik bhai
DeleteNotice:- 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