Here we’ll see how to write C program to find a digit of a specified position in a number. We’ll start the numbering from right side. The right most position would be 0. For example, 0-th digit of 2341238 is 8 and 3-rd digit is 1.
Logic to Find N-th Digit of a Number
- Do div operation with the number with 10N (num = num / pow (10, N)). The right most digit of the result would be the intended digit.
- Do modulo operation on the result with 10 (num = num % 10).
Program
#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;
r = num / pow(10, n);
r = r % 10;
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));
}
To compile this program, run this command.
cc -lm test.c -o test
Here is the output of the program.
In this example, we want to find 3rd digit of 345672, so the getdigit() function did div operation on 345672 with 1000. The result was 345. So the intended digit came to the right most position in the result. Then function then did div operation with the result (345) by 10. The result became 5.
Alternate Logic
We can have very similar logic to do the same thing.
- Do modulo operation on the number with 10(N+1) (num = num % pow (10, N+1)). The right most digit of the result would be the intended digit.
- Do div operation on the result with 10N (num = num / pow(10, N)).
Here is the modified get_digit() function.
int getdigit(int num, int n)
{
int r, t1, t2;
t1 = pow(10, n+1);
r = num % t1;
t2 = pow(10, n);
r = r / t2;
return r;
}
Read also: Find position of a digit in a number.
Teste both functions and does not works:
printf(“%d\n”, getdigit(1234, 1));
printf(“%d\n”, getdigit(1234, 2));
printf(“%d\n”, getdigit(1234, 3));
printf(“%d\n”, getdigit(1234, 4));
Prints:
3
2
1
0
Espected
1
2
3
4
It is a matter of interpretation.
In the examples here, the numbering is assumed from right to left, starting from 0.
That means, for the number 1234:
0-th position digit is: 4.
1-st position digit is: 3.
2-nd position digit is: 2.
3-rd position digit is: 1.
But you can change the getdigit() function to get your output like this:
Your logic is going wrong..
Plz try it to find out the 2nd digit..
Thanks for your comment.
I re-tested the program – both the logics. It worked as expected for the 2nd position also. It will help if you can provide an example.
Thank you sir. Helped me.
try to make a video