Search code examples
cloopscodeblocksdigits

C - Position of digit in a number


void main()
{
    int i, j = 0, p, q, N;    // N is the integer and p is the position needed
    printf("Enter two positive integers: ");
    scanf("%d%d", &N, &p);  // Taking the values of N and p

    for(i = 1; i <= p; i++) {

        j = N / 10;
        q = j % 10;
        i++;
        j = q;
    }

    printf("The digit of %d in the position %d is %d", N, p, j);
}

Example Input:

Enter two positive integers:
123456789
3

Output:

The digit of 123456789 in the position 3 is 8 

I actually have 2 problems with the above lines of code:

  1. if I use the method above the computer will start taking digits from right to left while usually, the count of digits starts from left to right
  2. the program is only repeating itself in the loop which means that it is not taking the new value of j to work with the second time it runs

Solution

  • First you count the number of digits in the integer,let say n.Then you can get the first digit by dividing the number by 10n-1.Then put this in a loop and decrease n by 1 & number N by N%=10n-1

    int main()
    {
        int i,j=0,p,N;
        printf("Enter two positive integers: ");
        scanf("%d%d",&N,&p);
    
        int pow=1,tmp=N;
        //counting power of 10 to divide
        while(tmp>10)
        {
            pow*=10;
            tmp/=10;
        }
        tmp=N;
        for(i=1; i<=p;i++){
           j = tmp/pow;
           tmp%=pow;
           pow/=10;
        }
        printf("The digit of %d in the position %d is %d\n",N,p,j);
    }