C Program To Count Digit k in Number n


Lets write a C program to count the number of occurrences of digit k in user input positive integer number n, using iterative logic. We will be using while loop to iterate in this program.

For Example:

If user inputs n = 1550, and k = 5, then our C program should find how many times digit 5 is present in number 1550.

Note: (num % 10) fetches last digit in num. If num = 1234; (num%10) fetches the last digit from right, which is 4.

(num/10) removes the last number from right. If num = 1234; (num/10) removes last digit i.e., 4 and the result of (num/10) will be 123.

Related Read:
C Program To Count Digit k in Number n using Recursion

Video Tutorial: C Program To Count Digit k in Number n



YouTube Link: https://www.youtube.com/watch?v=zsHoXuew33A [Watch the Video In Full Screen.]

Source Code: C Program To Count Digit k in Number n

  1. #include<stdio.h>  
  2.   
  3. int occurrence(intint);  
  4.   
  5. int main()  
  6. {  
  7.     int n, k;  
  8.   
  9.     printf("Enter a positive integer number\n");  
  10.     scanf("%d", &n);  
  11.   
  12.     printf("Which digits occurrence you want to check for?\n");  
  13.     scanf("%d", &k);  
  14.   
  15.     printf("\n%d has appeared %d times in %d.\n", k, occurrence(n, k), n);  
  16.   
  17.     return 0;  
  18. }  
  19.   
  20. int occurrence(int num, int k)  
  21. {  
  22.     int count = 0;  
  23.   
  24.     while(num)  
  25.     {  
  26.         if(num%10 == k)  
  27.             count++;  
  28.   
  29.         num = num / 10;  
  30.     }  
  31.     return count;  
  32. }  

Output:
Enter a positive integer number
1550
Which digits occurrence you want to check for?
5

5 has appeared 2 times in 1550.

Logic To Count Digit k in Number n

We ask the user to input values for variable n and k. We need to find the number of occurrences of digit k in number n. We pass both these variables to a function called occurrence().

Inside occurrence() function
Inside occurrence() function, we keep iterating the while loop until num value is 0. Btw, n value is copied into variable num. Now we check if (num%10) is equal to value of k. (num%10) fetches the last digit in the num. If (num%10) is equal to k, then we increment the value of count by 1. For each iteration of while loop we decrement the value of num by 1 digit, from right, by dividing num by 10 i.e., (num/10).

Once num is 0, control exits while loop and value of count will be returned to main method.

If num%10 is not equal to k, then we simply divide the num by 10, and reduce the value of num by one digit from right.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *