You don't have to reverse the original number
n
to get its i
th digit.
Just divide it by 10^
(L-i) and then take apply the modulus (% 10)
Where
L
is the 'length' of the number (the integer part of its decimal logarithm).
Now, back at your code. You don't need the
length
function to reverse the number and, moreover, your
reverse
function is incorrect (you didn't initialize the variable
i
).
In
position
function, you dynamically allocate memory that then you never release (that's a sloppy approach at programming). By the way you really don't need at all that piece of dynamic memory.
Try
#include <stdio.h>
#include <stdlib.h>
long reverse(long int num)
{
long rev = 0;
while ( num )
{
rev *= 10;
rev += num % 10;
num /= 10;
}
printf("%ld\n", rev);
return rev;
}
int position(long int num, int n)
{
long rev = reverse(num);
for(int i=1; i<n; i++) {
rev /= 10;
}
return (rev % 10);
}
int main()
{
long int num;
int n;
printf("Enter a number: \n");
scanf("%ld", &num);
printf("Enter the nth position: \n");
scanf("%d", &n);
printf("The no. in %d position is: %d", n, position(num, n));
}
Please note, such algorithm doesn't work with numbers containing trailing zero(es).