Posted January 25, 2011 by Spyros

# Write a Celcius to Fahrenheit Converter in C++ (and vice versa) I personally believe that the most important thing in programming is practice. What will make you a better programmer is writing more and more programs. Therefore, i believe that writing some simple programs is pretty important for novice programmers. This post will be about writing a converter from Celsius to Fahrenheit and Fahrenheit to Celsius as well.

This program is actually pretty simple and will take about 10 minutes for a seasoned programmer to write. However, it serves an important role. It is a good introductory program for those of you who have taken up C++ recently. Let’s take a look at the source code and elaborate a bit :

```
#include <iostream>
using namespace std;

int main()
{
char option;
float degrees;

cout << "Press 1 or 2 to convert From :" << endl;
cout << " Celsius to Fahrenheit" << endl;
cout << " Fahrenheit to Celsius" << endl;

cin >> option;

if (option == '1')
{
cout << "Please enter the number of Celsius Degrees:" << endl;
cin >> degrees;
float fahren = (degrees * 1.8) + 32;
cout << degrees << " degrees Celsius is " << fahren << " degrees Fahrenheit" << endl;
}
else
{
cout << "Fahrenheit to Celsius" << endl;
cin >> degrees;
float celsius = (degrees - 32) / 1.8;
cout << degrees << "degrees Fahrenheit is " << celsius << "degrees Celsius" << endl;
}

return 1;
}

```

The conversion formula is Celsius = (Fahrenheit * 1.8) + 32. The first thing we do in that program is ask the user to what he/she would like to convert to. I am aware that this code does not sanitize the user input, neither it handles possible exceptions and such. This is not the case here. I wanted to make it as simple as possible, so if you really need to make it better, please go ahead and i will post your code in that very post Notice that we used “cout” in order to print to screen and we use “cin” to receive user input. Once we receive this input, we perform the necessary calculations and print back the temperature in the needed format.

Hope this code helps you understand some of the basic C++ principles. Remember to use g++ (if you are a unix user) and not gcc for this one (g++ -o programName programName.c). Thanx for reading, hope you enjoyed that !

## Spyros 