×

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 print pronic numbers in a range using class

Submitted by Shubh Pachori, on October 08, 2022

Problem statement

Given a range, we have to print pronic numbers in that range using the class and object approach.

Example:

Input: 
Enter Start : 10
Enter End : 20

Output: 
Pronic Numbers in range 10 to 20 : 
12 20

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

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

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

  // isPronic() function to print the pronic number
  // lies in the range
  void isPronic() {
    // initialising  int type variables to perform operations
    int index_1, index_2, check;

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

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

      // for loop to check the number
      for (index_2 = 0; index_2 <= (int)(sqrt(index_1)); index_2++) {
        // if condition for number is equal to multiply of
        // index_2 and one number increased in index_2
        if (index_1 == index_2 * (index_2 + 1)) {
          check = 1;
          break;
        }
      }

      if (check) {
        cout << index_1 << " ";
      }
    }
  }
};

int main() {
  // create an object
  Pronic P;

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

  // calling isPronic() function to print
  // pronic numbers lies in the range
  P.isPronic();

  return 0;
}

Output

Enter Start : 20
Enter End : 50

Pronic Numbers in range 20 to 50 : 
20 30 42

Explanation

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

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