C program to find product of digits of a number

Write a C program to input a number from user and calculate product of its digits. How to find product of digits of a number using loop in C programming. Logic to find product of digits of a given number in C program.

Example

Input

Input number: 1234

Output

Product of digits: 24

Required knowledge

Basic C programming, While loop

Logic to find product of digits of a number

Logic to find product of digits is exactly similar to sum of digits. If you are done with previous program sum of digits, you can easily think logic for this program. If not read below logic to find product of digits.

I have divided the logic to calculate product of digits in three steps.

  1. Extract last digit of the given number.
  2. Multiply the extracted last digit with product.
  3. Remove the last digit by dividing number by 10.

Step by step descriptive logic to find product of digits of a given number.

  1. Input a number from user. Store it in some variable say num.
  2. Initialize another variable to store product i.e. product = 1. Now, you may think why I have initialized product with 1 why not 0? This is because we are performing multiplication operation not summation. Multiplying a number with 1 returns same, so as summation with 0 returns same. Hence, I have initialized product with 1. Also be sure to initialize the product with 0 if num is 0.
  3. Find last digit of number by performing modulo division by 10 i.e. lastDigit = num % 10.
  4. Multiply last digit found above with product i.e. product = product * lastDigit.
  5. Remove last digit by dividing the number by 10 i.e. num = num / 10.
  6. Repeat step 3-5 till number becomes 0. Finally you will be left with product of digits in product variable.

Program to find product of digits of a number

/**
 * C program to calculate product of digits of a number
 */

#include <stdio.h>

int main()
{
    int num;
    long long product=1ll;

    /* Input number from user */
    printf("Enter any number to calculate product of digit: ");
    scanf("%d", &num);

    product = (num == 0 ? 0 : 1ll);

    /* Repeat the steps till num becomes 0 */
    while(num != 0)
    {
        /* Get the last digit from num and multiplies to product */
        product = product * (num % 10);

        /* Remove the last digit from n */
        num = num / 10;
    }

    printf("Product of digits = %lld", product);

    return 0;
}

In the above program I have declared product as long long type and used %lld format specifier to print a long long type.

Also you have noticed I have used a suffix ll to initialize long long type i.e. long long product = 1ll;. This is because 1 is implicitly treated as integer in C, hence to make compiler aware that 1 is a long long value I have used suffix ll.

Read more about – Literals in C programming.

 

Output

 
 
 
Enter any number to calculate product of digit: 1234
Product of digits = 24

Happy coding 😉