C++ | Counting occurrence of digit in a number

Introduction

This is program to count the occurrence of digit in a number. The program counts the given digit occurred in the given number.This program is not extendable. Go enjoy the program. Lets begin…………….

Program to count occurrence of digit in number.


#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int and float
int no,oc=0,digit,i=0;
float m;
//Input the number save it in 'no'
cout<<"Enter the no."<<endl;
cin>>no;
cout<<"Enter the digit"<<endl;
cin>>digit;
//while loop
while(no>0)
{
m=no%10;
if(m==digit)
oc++;
no=no/10;
}
//show the oc
cout<<"Digit occurred "<<oc<<" times";
//get character
getch();
}

Output

Enter the no.
2242
Enter the digit
2
Digit occurred 3 times

How does it work

  1. You enter the number.
  2. You enter the digit
  3. In while loop last digit is separated and matched with given digit.
  4. If matched true, then increases the oc by one value.
  5. Prints the occurrence.

Extending it

The program cannot be extended.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variables as int (name them as you want.)
  5. Add the cout and cin of number.
  6. Add the loop.
  7. Count the occurrence.
  8. Print it.

At the end

You learnt creating the c++ program of Counting the occurrence of given digit in number.. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: