OverIQ.com

C Program to find the product of digits of a number

Last updated on July 27, 2020


The following is a C program to find the product of digits of a number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**************************************************
 Program to find the product of digits of a number
 * 
 * Enter a number: 456
 * 120
 **************************************************/

#include<stdio.h> // include stdio.h library

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

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

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

    printf("%d", prod);

    return 0; // return 0 to operating system
}

Expected Output:

1st run:

1
2
Enter a number: 234
24

2nd run:

1
2
Enter a number: 444
64

How it works #

The following table demonstrates what happens at each iteration of the while loop, assuming num = 234.

Iteration rem prod num
After 1st iteration rem=234%10=4 prod=1*4=4 num=234/10=23
After 2nd iteration rem=23%10=3 prod=4*3=12 num=23/10=2
After 3rd iteration rem=2%10=2 prod=12*2=24 num=2/10=0

Recommended Reading: