C++ program to check if the number is disarium or not using class

Given a number, we have to check it is a disarium number using the class and object approach.
Submitted by Shubh Pachori, on October 08, 2022

Example:

Input:
Enter Number : 89

Output:
It is a Disarium Number!

C++ code to check if the number is disarium or not using the class and object approach

#include <iostream>
#include <math.h>

using namespace std;

// create a class
class Disarium {
  // private data member
 private:
  int number;

  // public member functions
 public:
  // getNumber() function to insert number
  void getNumber() {
    cout << "Enter Number : ";
    cin >> number;
  }

  // isDisarium() function to check if the number
  // is disarium is or not
  void isDisarium() {
    // initialising  int type variables to perform operations
    int remain, sum = 0, length = 0, temp = number;

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

    temp = number;

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

    if (sum == number) {
      cout << "It is a Disarium Number!" << endl;
    } else {
      cout << "It is not a Disarium Number!" << endl;
    }
  }
};

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

  // calling getNumber() function to
  // insert the number
  D.getNumber();

  // calling isDisarium() function to check the
  // number if it is a disarium number
  D.isDisarium();

  return 0;
}

Output:

Enter Number : 89
It is a Disarium Number!

Explanation:

In the above code, we have created a class Disarium, one int type data member number to store the number, and public member functions getNumber() and isDisarium() to store and to check the given integer number is a disarium number or not.

In the main() function, we are creating an object D of class Disarium, reading an integer number by the user using the getNumber() function, and finally calling the isDisarium() member function to check the given integer number. The isDisarium() function contains the logic to given check the number and printing the result.

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





Comments and Discussions!

Load comments ↻






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