This C program finds the digit of specified position of a number. The numbering starts from 0. The least significant digit of a number is 0-th digit. For example 0th digit of 2341238 is 8 and 3-rd digit is 1.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <stdio.h> #include <math.h> /*Function to return the digit of n-th position of num. Position starts from 0*/ int getdigit(int num, int n) { int r, t1, t2; t1 = pow(10, n+1); r = num % t1; if (n > 0) { t2 = pow(10, n); r = r / t2; } return r; } void main() { int num = 0, pos; printf("Enter an integer: "); scanf("%d", &num); printf("Enter a position: "); scanf("%d", &pos); printf("%dth digit of %d is %d.\n", pos, num, getdigit(num, pos)); } |

**Output**: (Position starts from 0).

Enter an integer: 345672

Enter a position: 3

3th digit of 345672 is 5.

The function *getdigit()* uses C integer operations, *modulo* and *dev*, to find the digit of a particular location of a number. ItĀ first does the modulo operation on the input number by 10, if position is 0, 100 if position is 1, 1000 if position is 2 and so on.

In our above example, we want to find 3rd digit of 345672, so the *getdigit()* function will do modulo operation with 345672 with 10000. The result of the modulo operation will be 5672, the intended digit will become the right most in the result. After this, the function does *div* operation with the result (5672 here) by 1000, same number of 0s as intended position after 1.

The result of the div operation will become the digit of the intended position.