











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


Algorithm
- Start
- Get the input value from the user.
- Get the digit from the i/o console.
- Declare variables n,d,count
- n – Given number
- d – Digit
- count – no. of occurrences
- Take a while loop.
- Declare a variable k to store every digit of the number to be compared.
- Compare k with the digit
- if k equals digit increment count.
- n=n/10
- Print the value of count.
- 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
while(n)
{
int k = n%10; // to store the digits of the given input
n=n/10;
if(k==d) // compare the given digit with digit of input
{
count++; // increment counter variable
}
}
cout << count; // display count of digits
return 0;
}
public class JavaApplication1
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
int x,c=0;
x = obj.nextInt();
char b = obj.next().charAt(0);
String s = Integer.toString(x);
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==b)
c=c+1;
}
System.out.println(c);
}
}