C program to count occurrence of a particular digit in a number

In this program, we will read an integer number and a digit then print the total number of occurrence of input digit in that number.

For example there is a number 12311 and in which we want to find occurrence of 1 - The occurrence of 1 will be 3 in number 12311.

Count Occurrence of a Digit in a Number using C program

/*C program to print occurrence of a particular digit in a number.*/
 
#include <stdio.h>
 
int main()
{
    int num,tNum,digit,cnt;
    int rem;
 
    printf("Enter a number: ");
    scanf("%d",&num);
    printf("Enter digit to search: ");
    scanf("%d",&digit);
 
    cnt=0;
    tNum=num;
 
    while(tNum>0)
    {
        rem=tNum%10;
        if(rem==digit)
            cnt++;
        tNum/=10;
    }
 
    printf("Total occurrence of digit is: %d in number: %d.",cnt,num);
     
    return 0;
}

Using User Define Function

/*C program to print occurrence of a particular digit in a number.*/
 
#include <stdio.h>
 
/*function to get occurrence of a digit in a number*/
int findOccurrence(int num,int dig)
{
    int rem, cnt;
  
    cnt=0;
    while(num>0)
    {
        rem=num%10;
        if(rem==dig)
            cnt++;
        num/=10;
    }    
    return cnt;
}
  
int main()
{
    int num, digit, cnt;
  
    printf("Enter a number: ");
    scanf("%d",&num);
    printf("Enter digit to search: ");
    scanf("%d",&digit);
  
    cnt=findOccurrence(num,digit);
     
    printf("Total occurrence of digit is: %d in number: %d.",cnt,num);
      
    return 0;
}

Output:

Enter a number: 23111
Enter digit to search: 1
Total occurrence of digit is: 3 in number: 23111.

C Number Manipulation Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.