## Friday, April 5, 2013

### Celsius to Fahrenheit conversion program

In the CelsiusFahrenheitConverter program, you learn to convert from Celsius to Fahrenheit and vise versa.
To convert from Celsius to Fahrenheit, the formula written below is used. The program displays a table of Celsius to Fahrenheit and Fahrenheit to Celsius conversions.
F=32+(C*180.0/100.0)

CelsiusFahrenheitConverter source code:

1  class CelsiusFahrenheitConverter{
2     public static void main(String[] args){
3           int celsius=0, fahrenheit=32;
4             System.out.format("%-15s%-15s%-15s%-15s\n","Celsius", "Fahrenheit", "Fahrenheit","Celsius");
System.out.println("-----------------------------------------------------");
5 while(celsius<=100 || fahrenheit<=212 ){
if(celsius<=100)
System.out.format("%-15d%-15.2f%-15d%-15.2f\n",celsius, celToFah (celsius), fahrenheit, fahToCel(fahrenheit));
else
System.out.format("%33d%17.2f\n",fahrenheit, fahToCel(fahrenheit));

celsius++;
fahrenheit++;
6 }
7    }

8    public static double celToFah(int celsius){
double F;
F=32+(celsius*180.0/100.0);
return F;
9   }
10     public static double fahToCel(int fahrenheit){
double C;
C=(fahrenheit-32)*100.0/180.0;
return C;
11 }
12 }

Program Output

Code Explanation:
1 Open CelsiusFahrenheitConverter class block.
2. Open the main method block.
3 Declare local variables celsius, and fahrenheit for using in while loop iteration.
4 Print heading column text. Each heading column text is left aligned and 15 characters wide.
5 Use a while loop to print the conversion table. The celToFah and fahToCelsius methods are called to make the conversions and return results to be shown on the screen while the loop is working.
6 Close the while loop block.
7 Close the main method block.
8 It is the celToFah method. This method is to convert from Celsius to Fahrenheit equivalent.
9 Close the celToFah method block.
10 It is the fahToCelsius method. This method is to convert from Fahrenheit to Celsius equivalent.
11 Close the fahToCelsius method block.
12 Close the CelsiusFahrenheitConverter class block.