Write a C++ Program to find Product of Digits in a Number with an example. In this C++ product of digits in a number example, while loop checks whether the number is greater than 0.
- reminder = number % 10 – It gives the last digit of a number.
- digitProduct = digitProduct * reminder – It multiplies the last digit with digitProduct.
- number = number / 10 – it removes the last digit from the number.
#include<iostream>
using namespace std;
int main()
{
int number, reminder, digitProduct = 1;
cout << "\nPlease Enter the Number to find the Digits Product = ";
cin >> number;
while (number > 0)
{
reminder = number % 10;
digitProduct = digitProduct * reminder;
number = number / 10;
cout << "\nDigit = " << reminder << " and the Digit Product = " << digitProduct;
}
cout << "\n\nThe Product of all Digits in a given Number = " << digitProduct;
return 0;
}
C++ Program to find Product of Digits in a Number using For Loop
#include<iostream>
using namespace std;
int main()
{
int number, reminder, digitProduct;
cout << "\nPlease Enter the Number to find the Digits Product = ";
cin >> number;
for (digitProduct = 1; number > 0; number = number / 10)
{
reminder = number % 10;
digitProduct = digitProduct * reminder;
}
cout << "\nThe Product of all Digits in a given Number = " << digitProduct;
return 0;
}
C++ Program to calculate the Product of Digits in a Number using Functions
#include<iostream>
using namespace std;
int productOfDigits(int number)
{
int reminder, digitProduct;
for (digitProduct = 1; number > 0; number = number / 10)
{
reminder = number % 10;
digitProduct = digitProduct * reminder;
cout << "\nDigit = " << reminder << " and the Digit Product = " << digitProduct;
}
return digitProduct;
}
int main()
{
int number, digitProduct;
cout << "\nPlease Enter the Number to find the Digits Product = ";
cin >> number;
digitProduct = productOfDigits(number);
cout << "\n\nThe Product of all Digits in a given Number = " << digitProduct;
return 0;
}
C++ Program to calculate the Product of Digits in a Number using Recursion
#include<iostream>
using namespace std;
int productOfDigits(int number)
{
static int reminder, digitProduct = 1;
if(number > 0)
{
reminder = number % 10;
digitProduct = digitProduct * reminder;
productOfDigits( number / 10);
return digitProduct;
}
else
return 0;
}
int main()
{
int number, digitProduct;
cout << "\nPlease Enter the Number to find the Digits Product = ";
cin >> number;
digitProduct = productOfDigits(number);
cout << "\nThe Product of all Digits in a given Number = " << digitProduct;
return 0;
}