C Program to find the product of digits of a number

In this blog post, we learn how to write a C Program to find the product of digits of a number?. We will write the C Program to find the product of digits of a number. Write a C program to input a number from the user and calculate the product of its digits. How to display product of digits of a number. How to find a product of digits of a number using loop in C programming. Logic to find a product of digits of a given number in the C program.

Example,

input:  125
output: 10

input: 432
output: 24

 

Logic to find product of digits of a number:

  1. Ask the user to enter any number.
  2. Declare and initialize another variable ‘prod’ with 1, where prod is an integer variable.
  3. Get the last digit of the given number by performing the modulo division (%) and store the value in last_digit variable, likey last_digit= number % 10.
  4. Multiply the last digit (last_digit) found above with prod i.e. prod= prod* last_digit.
  5. Remove last digit by dividing the number by 10 i.e. num = num / 10.
  6. Repeat steps 3-5 until the number becomes 0. In the last, you will get the product of the digits of the input number.

 

C Program to find the product of digits of a number using a loop:

The below program ask the user to enter the value. After getting the value from the user it will calculate the product of digits of entered number by using the above-mentioned logic.

#include<stdio.h>

int main()
{
    int num, rem, prod = 1;

    printf("Enter a number: ");
    scanf("%d", &num);

    while(num != 0)
    {
        rem = num % 10; // get the last-digit
        prod *= rem; // calculate product of digits
        num /=  10;  // remove the last digit
    }

    printf("%d", prod);

    return 0;
}

Output:

Enter a number: 2345
120

 

C Program to find the product of digits of a number using a function:

The below program ask the user to enter the value. After getting the value from the user it will call a function getProduct() to calculate the product of digits of the entered number.  The function getProduct() is using arithmetic operators to calculate the product of digits of an input number.

#include<stdio.h>


int getProduct(int num)
{
    int prod = 1,rem;

    while(num != 0)
    {
        rem = num % 10; // get the last-digit
        prod *= rem; // calculate product of digits
        num /=  10;  // remove the last digit
    }

    return prod;
}

int main()
{
    int num, prod;

    printf("Enter a number: ");
    scanf("%d", &num);

    prod = getProduct(num);

    printf("%d", prod);

    return 0;
}

Output:

C Program to find the product of digits of a number

 

Recommended Articles for you:

Leave a Reply

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