×

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 convert the number from integer to roman using class

Submitted by Shubh Pachori, on October 09, 2022

Problem statement

Given an integer number, we have to convert it into roman using the class and object approach.

Example:

Input:
Enter Number : 101

Output:
Roman : CI

C++ code to convert the number from integer to roman using the class and object approach

#include <iostream>
using namespace std;

// create a class
class IntegerToRoman {
  // private data members
 private:
  int number;

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

  // IToR() function to convert number 
  // from integer to roman
  void IToR() {
    // string for roman numbers
    string roman[] = {"M",  "CM", "D",  "CD", "C",  "XC", "L",
                      "XL", "X",  "IX", "V",  "IV", "I"};

    // array of integer numbers corresponding to the
    // string of the roman number
    int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

    // initialising a empty string
    string result = "";

    // for loop to traverse both string array
    // of corresponding numbers
    for (int index = 0; index < 13; index++) {
      // while loop to convert number from integer to roman
      while (number - values[index] >= 0) {
        result = result + roman[index];
        number = number - values[index];
      }
    }

    cout << "Roman : " << result;
  }
};

int main() {
  // create an object
  IntegerToRoman I;

  // calling getNumber() function to
  // insert number in integer
  I.getNumber();

  // calling IToR() function to convert
  // number from integer to roman
  I.IToR();

  return 0;
}

Output

Enter Number : 561
Roman : DLXI

Explanation

In the above code, we have created a class IntegerToRoman, one int type data member integer to store the numbers in integer, and public member functions getNumber() and IToR() to store and convert the given numbers.

In the main() function, we are creating an object I of class IntegerToRoman, reading the numbers by the user using the function getNumber(), and finally calling the IToR() member function to convert the given numbers from integer to roman. The IToR() function contains the logic to convert the given numbers from integers to roman and printing the result.

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

Comments and Discussions!

Load comments ↻





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