C Program for finding the occurrence of a digit in a given number

Occurrence of a Digit in a given Number in C

Occurrence of a Digit in a given Number

we will count the number of occurrences of a given digit in the given input number.
The input may lie within the range of integer.
 
If the digit does not occur in the input it should print 0 else the count of digits.
 
Sample Input :
  • Enter a number : 897982
  • Enter the digit : 9
  • Output : 2
 
Explanation : The digit 9 occurs twice

Algorithm

  1. Start
  2. Take user input.
  3. Take digit as a user input.
  4. Declare variables n,d,count
    • n – Given number
    • d – Digit
    • count – no. of occurrences
  5. Take a while loop.
  6. Declare a variable k to store every digit of the number to be compared.
  7. Compare k with the digit
    • if k equals digit increment count.
  8. n=n/10
  9. Print the value of count.
  10. End

C Code:

#include <stdio.h>

int main() {
    int n; 
    int d; 
    int count=0
    scanf(%d%d,&n,&d);
    while(n) 
    {
        int k = n%10
        n=n/10
        if(k==d) 
        {
            count++;
        }
    }
    printf(%d,count);
    return 0;
}

Input:

897982
9

Output:

2