Program to convert Celsius to Fahrenheit in C++

Written by

Garvit Gulati

Program to convert Celsius to Fahrenheit in C++

Given temperature in °C, we have to write a program to convert it in °F and print it on the screen.

To convert a temperature in Celsius to Fahrenheit, you can use this formula:

  • Multiply the temperature in Celsius by 9/5.
  • Add 32 to the result.

Formula

°F = (9/5) × °C + 32

# Algorithm

  • Input the temperature in Celsius and store it in a variable c.
  • Calculate the temperature in Fahrenheit using the formula f = c * 1.8 + 32 and store it in a variable f.
  • Print the result f to the screen.

Code

#include <iostream>
using namespace std;

int main(){
  float c;
  cout << "Enter temperature in Celsius\n"; // inputting the temperature
  cin >> c;
  float f = (9 * c) / 5; // calculating the first part of the formula
  f += 32; // calculating the remaining part
  cout << "Temperature in Fahrenheit: " << f; // printing the calculated temperature
  return 0;
}

Output

Enter temperature in Celsius
36
  
Temperature in Fahrenheit:96.8

Using Functions

code

#include <iostream>
using namespace std;

// Converts Celsius to Fahrenheit
float celsiusToFahrenheit(float c) {
  return (9 * c) / 5 + 32;
}

int main() {
  float c;
  cout << "Enter temperature in Celsius\n"; // inputting the temperature
  cin >> c;
  float f = celsiusToFahrenheit(c); // converting Celsius to Fahrenheit
  cout << "Temperature in Fahrenheit: " << f; // printing the calculated temperature
  return 0;
}

Output

Enter temperature in Celsius
36
  
Temperature in Fahrenheit:96.8

Define a function named as celsiusToFahrenheit that takes a temperature in Celsius as an argument and returns the corresponding temperature in Fahrenheit.

Then, in the main function, call this function to convert the input temperature to Fahrenheit and print the result.

Program to convert Celsius to Fahrenheit in C++