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. C program to find product of digits.

Example:
Input number: 1234
Output product of digits: 1 * 2 * 3 * 4 = 24

Required knowledge

Basic C programming, Loop

Logic to find product of digits

Before moving on to the logic of finding product of digits one thing you must be done with is how to find the last digit of any number. Now, moving on to logic of this program can be divided in three basic steps:
  1. Find the last digit of number by performing modular division.
  2. Multiply the last digit just found above to product.
  3. Remove the last digit from number by dividing the number by 10.
Repeat the above three steps till the number becomes 0 and you will be left with the product of digits.

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=1;

    /* Reads a 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)
    {
        /* Gets the last digit from n and multiplies to product */
        product = product * (n % 10);

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

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

    return 0;
} 

Note: Initializing product=1 is must if you haven't initialized it before calculating product then you will get garbage value.

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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment