How to find position of a digit in a number in C programming?

This program will find out the position of a digit in a number. If the digits exists in multiple positions, this program will find all positions.

For example digit 4 is present in 41234253 at 4th and 8th positions from left.

#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:

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

Logic is simple: in every iteration we do modulo operation with the number ( 41234253) by 10. We’ll get the first digit (starting from right) 3. We compare that with the digit (4). If it is equal then we print the position. Then we take the remaining digits of the number ( 4123425) by doing div operation by 10. We continues this process for all digits in the number.

Here is the program to find the digit of a particular position of a number.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

One thought on “How to find position of a digit in a number in C programming?”

Leave a Reply

Your email address will not be published. Required fields are marked *

2
4
2
5
15
1