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 https://www.youtube.com/watch?v=zsHoXuew33A]

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

#include<stdio.h>

int occurrence(int, int);

int main()
{
    int n, k;

    printf("Enter a positive integer number\n");
    scanf("%d", &n);

    printf("Which digits occurrence you want to check for?\n");
    scanf("%d", &k);

    printf("\n%d has appeared %d times in %d.\n", k, occurrence(n, k), n);

    return 0;
}

int occurrence(int num, int k)
{
    int count = 0;

    while(num)
    {
        if(num%10 == k)
            count++;

        num = num / 10;
    }
    return count;
}

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 *