Home »
C++ Programs
C++ program to print deficient numbers in a range using class
Given a range, we have to print deficient numbers in that range using the class and object approach.
Submitted by Shubh Pachori, on October 05, 2022
Example:
Input:
Enter Start : 10
Enter End : 20
Output:
Deficient Numbers in range 10 to 20 :
10 11 13 14 15 16 17 19
C++ code to print deficient numbers in a range using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Deficient {
// 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;
}
// isDeficient() function to print
// the deficient number
// lies in the range
void isDeficient() {
// initialising int type variables
// to perform operations
int index_1, index_2, sum = 0;
cout << "\nDeficient 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 number
for (index_2 = 1; index_2 <= index_1; index_2++) {
// if condition to check if the number is
// multiple of the index_2
if (index_1 % index_2 == 0) {
sum = sum + index_2;
}
}
if (sum < (2 * index_1)) {
cout << index_1 << " ";
}
}
}
};
int main() {
// create an object
Deficient D;
// calling getRange() function to
// insert the range
D.getRange();
// calling isDeficient() function to print
// deficient numbers lies in the range
D.isDeficient();
return 0;
}
Output
Enter Start : 1
Enter End : 20
Deficient Numbers in range 1 to 20 :
1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19
Explanation
In the above code, we have created a class Deficient, two int type data members start and end to store the start and end of the range, and public member functions getRange() and isDeficient() to store and print deficient numbers in between that given range.
In the main() function, we are creating an object D of class Deficient, reading a range by the user using getRange() function, and finally calling the isDeficient() member function to print the deficient numbers in the given range. The isDeficient() function contains the logic to print deficient numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »