C++ program to find the LCM (Least Common Multiple) of two numbers using class

Given two numbers, we have to find the LCM (Least Common Multiple) of them using the class and object approach.
Submitted by Shubh Pachori, on September 12, 2022

Example:

Input:
Enter 1st Number : 3
Enter 2nd Number : 5

Output:
LCM of 3 and 5 is 15

C++ code to find the LCM (Least Common Multiple) of two numbers using the class and object approach

#include <iostream>
using namespace std;

// create a class
class LCM {
  // private data members
 private:
  int number_1, number_2;

  // public member functions
 public:
  // getNumbers() function to insert numbers
  void getNumbers() {
    cout << "Enter 1st Number : ";
    cin >> number_1;

    cout << "Enter 2nd Number : ";
    cin >> number_2;
  }

  // lcm() function to find lcm of two numbers
  void lcm() {
    // a int type variable to store LCM
    int lcm;

    // maximum value between number_1 and number_2 is stored in lcm
    lcm = (number_1 > number_2) ? number_1 : number_2;

    // a do while loop to find LCM of two numbers
    do {
      // if condition to check if lcm is divisible by the both numbers
      if ((lcm % number_1 == 0) && (lcm % number_2 == 0)) {
        // upper if condition is satisfied then 
        // this will print the LCM of both numbers
        cout << "LCM of " << number_1 << " and " << number_2 << " is " << lcm;

        // break keyword to break the loop
        break;
      }

      // else condition if upper condition is not satisfied
      else {
        // lcm will be incremented by 1
        lcm++;
      }

      // while with the condition true
    } while (true);
  }
};

int main() {
  // create an object
  LCM L;

  // calling getNumbers() function to
  // insert two numbers
  L.getNumbers();

  // calling lcm() function to find lcm
  // of two inserted numbers
  L.lcm();

  return 0;
}

Output:

RUN 1:
Enter 1st Number : 5
Enter 2nd Number : 25
LCM of 5 and 25 is 25

RUN 2:
Enter 1st Number : 120
Enter 2nd Number : 45
LCM of 120 and 45 is 360

Explanation:

In the above code, we have created a class LCM, two int type data members number_1 and number_2 to store the numbers, and public member functions getNumbers() and lcm() to store the numbers and to find lcm of two numbers inserted.

In the main() function, we are creating an object L of class LCM, inputting the numbers by the user using the getNumbers() function, and finally calling the lcm() member function to check find lcm of two numbers inserted. The lcm() function contains the logic to find lcm of two numbers inserted.

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





Comments and Discussions!

Load comments ↻






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