Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to produce a table of Celsius and the equivalent Fahrenheit temperatures from 0 to 10.

Java Code Example — OOP Programs

ADVERTISEMENT

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

  1. Create a class Temp.
  2. Define a method convert(int c) that accepts a Celsius integer and returns a float Fahrenheit value.
  3. In the method, use the formula: F = (9.0/5) * C + 32.
  4. In the main method, instantiate the Temp object.
  5. Use a for loop to iterate from 1 to 10.
  6. 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 convert method acts as a utility function. It takes an input c, processes it, and returns the result.
  • The expression (float)9.0/5 ensures floating-point division is performed instead of integer division (which would mistakenly evaluate to 1).
  • The \t character 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)
ADVERTISEMENT