Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

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

$
0
0

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.

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

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

The post How to find position of a digit in a number in C programming? appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>