81.6k views
3 votes
Create an array of doubles with 5 elements. In the array prompt the user to enter 5 temperature values (in degree Fahrenheit). Do this within main. Create a user defined function called convert2Cels. This function will not return any values to main with a return statement. It should have parameters that include the temperature array and the number of elements. The function should convert the values for Fahrenheit to Celsius and save them back into the same array. Celsius=(F-32)*5/9 From main, print the modified temperature array in a single column format similar to one shown below: Temperatures(Celsius) 37.78 65.56 100.00 0.00 21.11 Test your program with the following values: 100 150 212 32 70

1 Answer

4 votes

Answer:

The solution code is written in Java.

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. double myArray [] = new double[5];
  5. Scanner reader = new Scanner(System.in);
  6. for(int i=0; i < myArray.length; i++){
  7. System.out.print("Enter temperature (Fahrenheit): ");
  8. myArray[i] = reader.nextDouble();
  9. }
  10. convert2Cels(myArray, 5);
  11. for(int j = 0; j < myArray.length; j++){
  12. System.out.format("%.2f \\", myArray[j]);
  13. }
  14. }
  15. public static void convert2Cels(double [] tempArray, int n){
  16. for(int i = 0; i < n; i++){
  17. tempArray[i] = (tempArray[i] - 32) * 5 / 9;
  18. }
  19. }
  20. }

Step-by-step explanation:

Firstly, let's create a double-type array with 5 elements, myArray (Line 6).

Next, we create a Java Scanner object to read user input for the temperature (8).

Using a for-loop that repeats iteration for 5 times, prompt user to input temperature in Fahrenheit unit and assign it as the value of current element of the array. (Line 11 - 12). Please note the nextDouble() method is used to read user input as the data type of input temperature is expect in decimal format.

At this stage, we are ready to create the required function convert2Cels() that takes two input arguments, the temperature array, tempArray and number of array elements, n (Line 23). Using a for-loop to traverse each element of the tempArray and apply the formula to convert the fahrenheit to celcius.

Next, we call the function convert2Cels() in the main program (Line 15) and print out the temperature (in celsius) in one single column (Line 17-19). The %.2f in the print statement is to display the temperature value with 2 decimal places.

User MarZab
by
5.9k points