C++ program for Celsius to Fahrenheit and Fahrenheit to Celsius conversion using class

Code for Celsius to Fahrenheit and Fahrenheit to Celsius conversion using class in C++:

#include <iostream>
using namespace std;

class TemperatureConverter {
private:
    float temperature;

public:
    void setCelsius(float temp) {
        temperature = temp;
    }

    void setFahrenheit(float temp) {
        temperature = (temp - 32) * 5 / 9;
    }

    float getCelsius() {
        return temperature;
    }

    float getFahrenheit() {
        return (temperature * 9 / 5) + 32;
    }
};

int main() {
    TemperatureConverter converter;
    float celsiusTemp, fahrenheitTemp;

    cout << "Enter temperature in Celsius: ";
    cin >> celsiusTemp;

    converter.setCelsius(celsiusTemp);
    cout << "Temperature in Fahrenheit: " << converter.getFahrenheit() << endl;

    cout << "Enter temperature in Fahrenheit: ";
    cin >> fahrenheitTemp;

    converter.setFahrenheit(fahrenheitTemp);
    cout << "Temperature in Celsius: " << converter.getCelsius() << endl;

    return 0;
}

Explanation:

  • The program starts by including the necessary header files and using the standard namespace.
  • A class named TemperatureConverter is defined to handle the temperature conversion operations.
  • Inside the class, a private member variable temperature is declared to store the temperature value.
  • The class contains member functions setCelsius, setFahrenheit, getCelsius, and getFahrenheit to set and get temperature values and perform the conversion calculations.
  • In the main function, an instance of the TemperatureConverter class is created.
  • The user is prompted to enter a temperature in Celsius, which is then used to set the temperature in the TemperatureConverter object, and the equivalent temperature in Fahrenheit is displayed using the getFahrenheit function.
  • Next, the user is prompted to enter a temperature in Fahrenheit, which is used to set the temperature in the TemperatureConverter object, and the equivalent temperature in Celsius is displayed using the getCelsius function.
  • The program then ends with a return value of 0.