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

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

Example:

Input: 
Enter Start : 100
Enter End : 10000

Output: 
Narcissistic Numbers in range 100 to 10000 : 
153 370 371 407 1634 8208 9474

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

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

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

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

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

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

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

      temp = index;

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

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

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

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

  // calling isNarcissistic() function to print
  // narcissistic numbers lies in the range
  N.isNarcissistic();

  return 0;
}

Output:

Enter Start : 100
Enter End : 1000
153 370 371 407

Explanation:

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

In the main() function, we are creating an object N of class Narcissistic, reading a range by the user using getRange() function, and finally calling the isNarcissistic() member function to print the narcissistic numbers in the given range. The isNarcissistic() function contains the logic to print narcissistic 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.