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

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

Here, in this page we will discuss the program that count the occurrence of a digit in a given number using C++.
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
occurrence of a digit in a given number using C++

Algorithm

  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

Code to find the occurrence of a digit in a given number using C++

#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;
}

Another Algorithm :

  • Take the integer number and the digit from the user and store them in variable say n and d respectively.
  • Now, convert the integers into string using to_string() function.
  • Then iterate the string of the number and count the occurence of the digit in the number and store it in variable say count.
  • After completely iterating the string print the value of count.
#include<bits/stdc++.h>
using namespace std;

int main(){

int n, d;

cout<<"Enter the number and didgit :";
cin>>n>>d;

string x = to_string(n);
string y = to_string(d);

int count =0;

for(int i=0; i<x.size(); i++){
if(x[i]==y[0]) count++;
}

cout<<d <<" occurs "<<count<<" times in "<<n;

}
Output :

Enter the number and digit : 345234 3

3 occurs 2 times in 345234

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(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);
    }
    }