Home »
C++ Programs
C++ program to find the product of digits of numbers between a given range using class
Submitted by Shubh Pachori, on September 01, 2022
Problem statement
Given a range, we have to find the product of digits of numbers between a given range using the class and object approach.
Example:
Input:
Enter Numbers: 22 24
Output:
Product of Digits: 192
(2*2*2*3*2*4 = 192)
C++ code to find the product of digits of numbers between a given range using the class and object approach
#include <iostream>
using namespace std;
// create a class
class ProductDigit {
// declare private data members
private:
int start, end;
// public functions
public:
// getNumbers() function to insert numbers
void getNumbers() {
cout << "Enter Numbers: ";
cin >> start >> end;
}
// productDigit() function to multiply digits of
// numbers in between the numbers
int productDigit() {
// initializing int type variables to
// performing operations
int index, temp, product = 1;
// for loop to multiply every digit one by one
// between the numbers
for (index = start; index <= end; index++) {
// copying number in the temporary variable
temp = index;
// while loop to gain digits one by one
while (temp > 0) {
// adding digits in product
product = product * (temp % 10);
// dividing temp by 10 at every iteration
temp = temp / 10;
}
}
// returning product
return product;
}
};
int main() {
// create an object
ProductDigit P;
// int type variable to store the product
int product;
// calling getNumbers() function to insert numbers
P.getNumbers();
// productDigit() function to multiply digits of
// numbers between in numbers
product = P.productDigit();
cout << "Product of Digits : " << product;
return 0;
}
Output
Enter Numbers: 21 25
Product of Digits: 3840
Explanation
In the above code, we have created a class ProductDigit, two int type data members start and end to store the start and end of the numbers, and public member functions getNumbers() and productDigit() to store and to multiply digits of numbers in between that given numbers.
In the main() function, we are creating an object P of class ProductDigit, reading a number by the user using getNumbers() function, and finally calling the productDigit() member function to multiply digits of numbers in the given numbers. The productDigit() function contains the logic to multiply digits of numbers in the given numbers and printing the result.
C++ Class and Object Programs (Set 2) »