Please login


Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Occurrence of a digit in a given number using C++

Number of times the digit x occurs in the given number

In this C++ program 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


  1.  Start
  2. Get the input value from the user.
  3. Get the digit from the i/o console.
  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 <bits/stdc++.h>

using namespace std;

int main()
    //Declare variables

    int n; //given integer
    int d; //given digit
    int count=0; //declare counter variable

    cin >> n >> d; // take input from user 


        int k = n%10; // to store the digits of the given input


        if(k==d) // compare the given digit with digit of input
            count++; // increment counter variable


    cout << count; // display count of digits

    return 0;

One comment on “Occurrence of a digit in a given number using C++”

  • Shubham

    public class JavaApplication1
    public static void main(String[] args)
    Scanner obj = new Scanner(;
    int x,c=0;
    x = obj.nextInt();
    char b =;
    String s = Integer.toString(x);
    for(int i=0;i<s.length();i++)