Home »
C++ Programs
C++ program to print abundant numbers in a range using class
Submitted by Shubh Pachori, on October 04, 2022
Problem statement
Given a range, we have to print abundant numbers in that range using the class and object approach.
Example:
Input:
Enter Start : 10
Enter End : 20
Output:
Abundant Numbers in range 10 to 20 :
12 18 20
C++ code to print abundant numbers in a range using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Abundant {
// private data member
private:
int start, end;
// public member functions
public:
// getRange() function to insert range
void getRange() {
cout << "Enter Start : ";
cin >> start;
cout << "Enter End : ";
cin >> end;
}
// isAbundant() function to print the abundant number
// lies in the range
void isAbundant() {
// initialising int type variables to perform operations
int index_1, index_2, sum = 0;
cout << "\nAbundant Numbers in range " << start << " to " << end << " : "
<< endl;
// for loop to check numbers lies in the range
for (index_1 = start; index_1 <= end; index_1++) {
sum = 0;
// for loop to check the index_1
for (index_2 = 1; index_2 < index_1; index_2++) {
// if condition to check if the index_1
// is a multiple of index_2
if (index_1 % index_2 == 0) {
sum = sum + index_2;
}
}
if (sum > index_1) {
cout << index_1 << " ";
}
}
}
};
int main() {
// create an object
Abundant A;
// calling getRange() function to
// insert the range
A.getRange();
// calling isAbundant() function to print
// abundant numbers lies in the range
A.isAbundant();
return 0;
}
Output:
RUN 1:
Enter Start : 15
Enter End : 25
Abundant Numbers in range 15 to 25 :
18 20 24
RUN 2:
Enter Start : 1
Enter End : 100
Abundant Numbers in range 1 to 100 :
12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80 84 88 90 96 100
Explanation:
In the above code, we have created a class Abundant, two int type data members start and end to store the start and end of the range, and public member functions getRange() and isAbundant() to store and print abundant numbers in between that given range.
In the main() function, we are creating an object A of class Abundant, reading a range by the user using getRange() function, and finally calling the isAbundant() member function to print the abundant numbers in the given range. The isAbundant() function contains the logic to print abundant numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »