Java Program to produce a table of Celsius and the equivalent Fahrenheit temperatures from 0 to 10.
Objective
Write a Java program to generate a Celsius to Fahrenheit conversion table using a class method.
Algorithm / Approach
- Create a class
Temp. - Define a method
convert(int c)that accepts a Celsius integer and returns afloatFahrenheit value. - In the method, use the formula:
F = (9.0/5) * C + 32. - In the
mainmethod, instantiate theTempobject. - Use a
forloop to iterate from 1 to 10. - For each number, call the
convert()method and print the result in a tabular format.
Temp.java
class Temp {
float convert(int c) {
float f = (float)9.0/5*c;
return f+32;
}
public static void main(String[] a)
{
Temp t = new Temp();
System.out.println("Celc.\tFahren.");
for(int i=1; i<=10; i++) {
float x = t.convert(i);
System.out.println(i+"\t"+x);
}
}
}
Expected Output
Celc. Fahren. 1 33.8 2 35.6 3 37.4 4 39.2 5 41.0 6 42.8 7 44.6 8 46.4 9 48.199997 10 50.0
Explanation of the Program
- This program highlights how methods can accept arguments and return computed values.
- The
convertmethod acts as a utility function. It takes an inputc, processes it, and returns the result. - The expression
(float)9.0/5ensures floating-point division is performed instead of integer division (which would mistakenly evaluate to 1). - The
\tcharacter is an escape sequence used to insert a tab space for tabular alignment.
Complexity
Time Complexity
O(n) - Where n is the loop limit (10).
Space Complexity
O(1)