C++ Program to Find Product of Digits of a Number

In this post, we will learn how to find the product of digits of a number using C++ Programming language.

So, without further ado, let’s begin this tutorial.

C++ Program to Find Product of Digits of a Number

// C++ Program to Find Product of Digits of a Number
#include <iostream>
using namespace std;

int main(){
    int num, product = 1;
    
    // Asking for input
    cout << "Enter any number: ";
    cin >> num;
    
    while (num > 0){
        product = product * (num % 10);
        num = num / 10;
    }
    
    // Displaying output
    cout << "The product of digits is: " << product;
    return 0;
}

Output

Enter any number: 1234
The product of digits is: 24

How Does This Program Work ?

    int num, product = 1;

In this program, we have declared two int data type variables named num, product.

    // Asking for input
    cout << "Enter any number: ";
    cin >> num;

Then, the user is asked to enter any number.

    while (num > 0){
        product = product * (num % 10);
        num = num / 10;
    }

We calculate the product of digits using a simple while loop.

After 1st iteration, product = 1 * 4 = 4, num becomes 123.
After 2nd iteration, product = 4 * 3 = 12, num becomes 12.
After 3rd iteration, product = 12 * 2 = 24, num becomes 1.
After 4th iteration, product = 24 * 1 = 24, num becomes less than 0 and loop terminates.

    // Displaying output
    cout << "The product of digits is: " << product;

Finally, the result is displayed on the screen using the cout statement.

Conclusion

I hope after going through this post, you understand how to find the product of digits of a number using C++ Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to guide you.

Also Read:

Leave a Comment

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