This program will find out the position of a digit in a number. For example digit 4 is present in 41234253 at 4th and 8th positions from left.

Logic is simple, we start with the number say 41234253 and do modulo operation with 10. We’ll get the last digit 3. If it matches the digit (4 here) we are comparing with then we can say the position is 1. If not we can do same thing with remaining digits from the number (4123425). To get the remaining digits we do integer div operation with 10. In every iteration we’ll increase the position count by 1. Here is the program.

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 33 34 |
#include <stdio.h> #include <stdlib.h> int main() { int n, d; int number, r, i; int found = 0; printf("Enter a number: "); scanf("%d", &n); printf("Enter a digit to find (0 to 9): "); scanf("%d", &d); while(d < 0 || d > 9) { printf("Wrong entry\n"); printf("Enter a digit to find (0 to 9): "); scanf("%d", &d); } number = n; i = 1; while(number) { r = number % 10; if(r == d) { found = 1; printf("Digit %d found at position %d.\n", d, i); } i++; number = number / 10; } if(!found) printf("Digit %d is not present in %d\n", d, n); return 1; } |

He is the Output:

1 2 3 4 5 6 7 8 9 10 |
The output: [qnaplus@localhost home]$ ./test.out Enter a number: 41234253 Enter a digit to find (0 to 9): 4 Digit 4 found at position 4. Digit 4 found at position 8. [qnaplus@localhost home]$ ./test.out Enter a number: 23945 Enter a digit to find (0 to 9): 7 Digit 7 is not present in 23945 |