×

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 check if the number is narcissistic or not using class

Submitted by Shubh Pachori, on October 05, 2022

Problem statement

Given a number, we have to check whether it is narcissistic number using the class and object approach.

Example:

Input:
Enter Number : 22

Output: 
It is not a Narcissistic Number!

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

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

using namespace std;

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

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

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

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

    temp = number;

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

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

int main() {
  // create an object
  Narcissistic N;

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

  // calling isNarcissistic() function to check the
  // number if it is a narcissistic number
  N.isNarcissistic();

  return 0;
}

Output

Enter Number : 153
It is a Narcissistic Number!

Explanation

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

In the main() function, we are creating an object N of class Narcissistic, reading an integer number by the user using the getNumber() function, and finally calling the isNarcissistic() member function to check the given integer number. The isNarcissistic() 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.