In Java 1.Given an unsorted array of doubles, write a program that Computes the
ID: 3886967 • Letter: I
Question
In Java
1.Given an unsorted array of doubles, write a program that Computes the sum of the array Finds the maximum in the array. (30 pts)
2.Given an array of ints sorted in ascending order, write a program to find the median in the array. (30 pts) (You may create your own array to test the program.)
3. Given a 6-by-8 two-dimensional array of ints and a target value, search the target value in the array. If found in the array, return its index, otherwise, return -1. (40 pts) (You may create your own array to test the program.)
Explanation / Answer
1.Given an unsorted array of doubles, write a program that Computes the sum of the array Finds the maximum in the array
//Please see the code below
public class ComputeSum
{
static double sum;
static double maxElement;
public static void computeSumAndMaxElement(double[] array)
{
maxElement=0;
for (int i=0; i < array.length; i++)
{
if(array[i]>maxElement)
maxElement=array[i];
sum += array[i];
}
}
public static void main(String[] args)
{
double arr[]={1.1, 2.2, 5.5, 4.4, 2.4};
computeSumAndMaxElement(arr);
System.out.println("Sum is "+sum+" and Max element is "+maxElement);
}
}
2.Given an array of ints sorted in ascending order, write a program to find the median in the array.
public class ComputeMedian
{
public static void main(String[] args)
{
int arr[]={1, 2, 3 ,4, 5};
int middle = arr.length/2;
int medianValue = 0;
if (arr.length%2 == 1)
medianValue = arr[middle];
else
medianValue = (arr[middle-1] + arr[middle]) / 2;
System.out.println("Median of an array of Int is "+medianValue);
}
}
Given a 6-by-8 two-dimensional array of ints and a target value, search the target value in the array. If found in the array, return its index, otherwise, return -1
public class twoDimArray
{
static int searchTargetValue (int [][] arr, int val)
{
for(int i=0;i<6;i++)
{
for(int j=0;j<8;j++)
{
if(arr[i][j]==val)
{
System.out.println("The given element "+val+ " is present at index " +i+j);
return 0;
}
}
}
System.out.print("The given element "+val+ " is not present in array");
return -1;
}
public static void main(String[] args)
{
int twoDimArr[][]= new int[6][8];
int i,j;
//Setting the value in 2-dimension array
for(i=0;i<6;i++)
{
for(j=0;j<8;j++)
{
twoDimArr[i][j]=i+j;
}
}
//Printing the value of 2-dimension array
for(i=0;i<6;i++)
{
for( j=0;j<8;j++)
{
System.out.print(twoDimArr[i][j]+ " ");
}
System.out.println();
}
searchTargetValue(twoDimArr,10);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.