Header Ads

Define a class to declare an array of size 20 of double datatype, accept the elements into the array and perform the following: • Calculate and print the sum of all the elements. • Calculate and print the highest value of the array

Java Array Data Types

Integer Array
Double Array
Byte Array
Boolean Array
Character Array
Array Of Strings
Empty Array


Approach 

In this program, we need to calculate the sum of all the elements of an array. This can be done by looping through the array and add the value of the element in each iteration to variable sum.

we also need to find out the largest element present in the array and display it. This can be accomplished by looping through the array from start to end by comparing temp with all the elements of an array. If any of element is greater than temp, then store a value of the element in temp. Initially, temp will hold the value of the first element. At the end of the loop, temp represents the largest element in the array which is now the last element of array.


Code :

import java.util.Scanner;

public class arrsum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

double arr[] = new double[20];
double temp, sum = 0;
System.out.println("Enter numbers:");
for (int i = 0; i < 20; i++) {
arr[i] = sc.nextDouble();
sum = sum + arr[i];
}
System.out.println("Sum : "+sum);
for (int i = 0; i < 20; i++) {
for (int j = i + 1; j < 20; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("highest value is : "+arr[19]);
}
}

Output :

Enter numbers:
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7
2.8
2.9
2.0
Sum : 39.0
highest value is : 2.9

Explanation :

Create a scanner object and declare  double array of size 20. Declare variable temp and sum of datatype double with 0 as initial value. Give a prompt to Enter numbers and use for loop to insert values to the array and calculate the sum simultaneously. Print the sum and use sorting technique to find the highest value of array. 
create nested for loop for sorting the array, sorting algorithm is explained above.
After sorting print the last element of the array, it will be the highest value of the array.

Application :

  • WAP to store the weight of 10 students into an array and display the highest weight
    This can be done in the similar way as explained above, you just have to make few modifications and     you are all set to go. If you are doing this application post the code in the comment section below

Post a Comment

0 Comments