Objective : You are given a number and you have to find the reverse of the given number in C. reverse of 1234 will be 4321.
Like 1234:
1234%10=4 (remainder). rev=4.
123%10= 3. rev=4x10+3=43.
12%10=2 rev=43x10+2=432.
1%10=1 rev=432x10+1=4321.
Code:
#include<stdio.h> int main() { int k; printf("\n enter a number="); scanf("%d",&k); printf("\n Reverse of the number is=%d",reverse(k)); return 0; } int reverse(int x) { int ans=0,r; while( x > 0 ) { r=x%10;//extract last digit ans=ans*10+r;// multiply by 10 and then add the remainder x=x/10;//reduce number } return(ans); }
No comments:
Post a Comment