C++ Program to find Number of times a digit occurs in each and every number from 0 to n

Number of times a digit occurs in each and every number from 0 to n

Here we will discuss how to find the occurrence of a digit in numbers between 0 to (a limit specified by the user) using C++ programming language. 

To find the occurrences of the digit in the specified range every number in the range is checked whether they contain the digit or not, if they do count otherwise move onto the next number.

Let’s take an example for reference:

Digit = 2

Range = 0 – 20

Occurrences = 2, 12, 20.

So the number of occurrences = 3

Occurrence of number

Working

Let’s see how the code works:

  • User gives two input(digit and limit).
  • The inputs are stored in two int type variable say digit & range.
  • A for loop is started for(i → 0 to range)
    • A function count() is called with i and digit as parameter
      • Every number is checked whether they contain the digit or not
      • If they contain the digit then it is counted and the counted value is returned
    • Every time a value is returned it will be added to a counter which counts the total occurrence of the digits in the range.
  • The result is printed.

C++ Code

//C++ Program
//Occurrence of digit of 0 to n
#include<iostream>
using namespace std;
//function to count the Occurrence
int count(int num,int digit)
{
int c=0;
while(num!=0)
{
if(num%10==digit)
c++;
num=num/10;
}
return c;
}
//main program
int main()
{

int digit,range;
cout<<"Enter digit and range:\n ";
//user input
cin>>digit>>range;
int c=0;
for(int i=0;i<=range;i++)
{
//calling function and counting Occurrences
c+=count(i,digit);
}
//Printing output
cout<<"number of times "<<digit<<" occurs between 0 to "<<range<<" is: "<<c;
return 0;
}

Output

Enter digit and range:
3
100
number of times 3 occurs between 0 to 100 is: 20