C++ program to print disarium numbers in a range using class

Given a range, we have to print disarium numbers in that range using the class and object approach.
Submitted by Shubh Pachori, on October 08, 2022

Example:

Input: 
Enter Start : 100
Enter End : 200

Output: 
Disarium Numbers in range 100 to 200 : 
135 175

C++ code to print disarium numbers in a range using the class and object approach

#include <iostream>
#include <math.h>
using namespace std;

// create a class
class Disarium {
  // 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;
  }

  // isDisarium() function to print the disarium number
  // lies in the range
  void isDisarium() {
    // initialising  int type variables to perform operations
    int index, remain, sum, length, temp;

    cout << "\nDisarium Numbers in range " << start << " to " << end << " : "
         << endl;

    // for loop to check numbers lies in the range
    for (index = start; index <= end; index++) {
      length = 0;
      sum = 0;

      temp = index;

      // while loop to count length of the number
      while (temp) {
        length++;
        temp = temp / 10;
      }

      temp = index;

      // while loop to manipulate the number
      while (temp) {
        remain = temp % 10;
        sum = sum + pow(remain, length);
        temp = temp / 10;
        length--;
      }

      if (sum == index) {
        cout << index << " ";
      }
    }
  }
};

int main() {
  // create an object
  Disarium D;

  // calling getRange() function to
  // insert the range
  D.getRange();

  // calling isDisarium() function to print
  // disarium numbers lies in the range
  D.isDisarium();

  return 0;
}

Output:

Enter Start : 500
Enter End : 1000

Disarium Numbers in range 500 to 1000 : 
518 598

Explanation:

In the above code, we have created a class Disarium, two int type data members start and end to store the start and end of the range, and public member functions getRange() and isDisarium() to store and print disarium numbers in between that given range.

In the main() function, we are creating an object D of class Disarium, reading a range by the user using getRange() function, and finally calling the isDisarium() member function to print the disarium numbers in the given range. The isDisarium() function contains the logic to print disarium numbers in the given range and printing the result.

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





Comments and Discussions!

Load comments ↻






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