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

Given a number, we have to check whether it is ugly number or not using class and object approach.
Submitted by Shubh Pachori, on October 04, 2022

Example:

Input: Enter Number : 30
Output: It is an ugly number.

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

#include <iostream>
using namespace std;

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

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

  // isUgly() function to check if the number
  // is ugly is or not
  void isUgly() {
    // initializing an int type variable
    int check = 0;

    // while loop to check the number
    while (number != 1) {
      // if condition to check if the
      // number is a multiple of 5
      if (number % 5 == 0) {
        number = number / 5;
      }

      // else if condition to check if the
      // number is a multiple of 3
      else if (number % 3 == 0) {
        number = number / 3;
      }

      // else if condition to check if the
      // number is a multiple of 2
      else if (number % 2 == 0) {
        number = number / 2;
      }

      // if condition to check if the number
      // is not a multiple of 2, 3 and 5
      else {
        cout << "It is not an ugly number." << endl;
        check = 1;
        break;
      }
    }

    if (check == 0) {
      cout << "It is an ugly number." << endl;
    }
  }
};

int main() {
  // create an object
  Ugly U;

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

  // calling isUgly() function to check the
  // number if it is a ugly number
  U.isUgly();

  return 0;
}

Output:

RUN 1:
Enter Number : 30
It is an ugly number.

RUN 2:
Enter Number : 543
It is not an ugly number.

Explanation:

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

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