C program to calculate product of digits of a number

Write a C program to enter any number from user and calculate product of its digits. How to find product of digits of any 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, Loop

Logic to find product of digits

Finding sum of digits or product of digits. Logic of both the program are similar. If you are done with sum of digits, you can easily think logic for this program. If not read below the 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.

Below is the 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 that will hold 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 with 1 returns the same, so as summation with 0 returns the same. Hence, I have initialized product with 1.
  3. Find the last digit of number by performing modular 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

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

#include <stdio.h>

int main()
{
    int n;
    long product=1L;

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

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

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

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

    return 0;
}

Output

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

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>