×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to print the perfect numbers in the given range using class

Submitted by Shubh Pachori, on August 22, 2022

Problem statement

Given a range, we have to print the perfect numbers in the given range using the class and object approach.

Example:

Input:
Enter Range:10 100

Output:
Perfect Numbers in the range 10 to 100 are 
28

C++ code to print the perfect number in the given range using the class and object approach

#include <iostream>
using namespace std;

// create a class
class Perfect {
  // private data member
  private:
    int start, end;

  // public functions
  public:
    // getRange() function to get the range
    void getRange() {
      cout << "Enter Range:";
      cin >> start >> end;
    }

  // isPerfect() function to print perfect number in range
  void isPerfect() {
    // initialising int type variables for 
    int index_1, index_2 = 1, sum;

    cout << "Perfect Numbers in the range " << start << " to " << end << " are " << endl;

    // nested for loop to check all numbers in the range if 
    // there is any number is perfect or not
    for (index_1 = start; index_1 <= end; index_1++) {
      // reinitialising sum after every iteration of first for loop
      sum = 0;

      for (index_2 = 1; index_2 < index_1; index_2++) {
        // if index_1 is completely divided by the index_2
        // then index_2 is added to the sum
        if (index_1 % index_2 == 0) {
          sum = sum + index_2;
        }
      }

      // index_1 is equal to sum then number is printed
      if (index_1 == sum) {
        cout << index_1 << " ";
      }
    }
  }
};

int main() {
  // create an object
  Perfect P;

  // function is called by the object to get range
  P.getRange();

  // isPerfect() function to print perfect number in range
  P.isPerfect();

  return 0;
}

Output

Enter Range:5 500
Perfect Numbers in the range 5 to 500 are 
6 28 496

Explanation

In the above code, we have created a class Perfect, two int type data members start and end to store the range, and public member functions getRange() and isPerfect() to store the range and to print the perfect number in the given range.

In the main() function, we are creating an object P of class Perfect, inputting the range by the user using the getRange() function, and finally calling the isPerfect() member function to print the perfect number in the given range. The isPerfect() function contains the logic to print the perfect number in the given range.

C++ Class and Object Programs (Set 2) »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.