Write a ‘C’ function that returns the k-th digit from the right in the positive integer n. For example, digit(829,1) returns 9, digit(829,3) returns 8. If k is greater than the number of digits in n then the function is to return –1. Include appropriate documentation in your program.

#include<stdio.h>
int digit(int,int);

main()
{
int num,pos,dg;
printf("\nEnter a number=");
scanf("%d",&num);
printf("\nEnter the position=");
scanf("%d",&pos);
dg=digit(num,pos);
if(dg==-1)
printf("\nInvalid position");
else
printf("\nDigit found in position %d is %d",pos,dg);
}

int digit(int n,int p)
{
int i=1;
while(i<p && n>=0)
{
n=n/10;
i++;
}
if(n==0)
return -1;
else
return n%10;
}

No comments:

Post a Comment