Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Language:Java 1. Write a function that takes as input parameter an array of type

ID: 3720131 • Letter: L

Question

Language:Java
1. Write a function that takes as input parameter an array of type Double, and returns the array containing the middle values of all three-consecutive values in the original array.
Language:Java
1. Write a function that takes as input parameter an array of type Double, and returns the array containing the middle values of all three-consecutive values in the original array.

1. Write a function that takes as input parameter an array of type Double, and returns the array containing the middle values of all three-consecutive values in the original array.

Explanation / Answer

import java.util.*;
public class convert{
   static double[] convert(double[] a){ //function for converting the given array
       int n = a.length; //finding length of array
       //for first value of new array
       double[] new_array = new double[n]; //creating new array
       if(n>2) //if the array contains more than 2 values
           new_array[0] = (a[0] + a[1]) / 2; //taking average of first two values as there is no value to left of present value
       else if(n>0 && n>1) //if there is atleast one value
           new_array[0] = a[0];
       for(int i=1;i<(n-1);i++){ //looping through the array
           new_array[i] = (a[i-1] + a[i] + a[i+1]) / 3; //taking average of 3 cosecutive values
       }
       //for lat value of new array
       if(n>2) //finding average of last two values
           new_array[n-1] = (a[n-1] + a[n-2]) / 2;
       return new_array //returning new array
   }
   public static void main(String args[]){
       Scanner in = new Scanner(System.in);
       //reading input
       System.out.println("Enter no of values");
       int n = in.nextInt();
       System.out.println("Enter values");
       double[] a = new double[n];
       for(int i=0;i<n;i++)
           a[i] = in.nextDouble();
       double[] new_array = new double[n];
       new_array = convert(a);
       //printing array values
       System.out.print("Required array is");
       for(int i=0;i<n;i++)
           System.out.print(" " + new_array[i]);
   }
}

output:

Enter no of values
5
Enter values
2.3
5.6
9.87
4.1
7.6
Required array is 3.9499999999999997 5.923333333333333 6.523333333333333 7.19 5.85