ICSE Class 10 Computer Applications Question 14 of 59

Arrays — Question 16

Back to all questions
16
Question

Question 16

Write Java statements for the following:

i. Create an array to hold 15 double values.

ii. Assign the value 10.5 to the last element in the array.

iii. Display the sum of the first and the last element.

iv. Write a loop that computes the sum of all elements in the array.

Answer

i. Create an array to hold 15 double values.

double arr[] = new double[15];

ii. Assign the value 10.5 to the last element in the array.

arr[14] = 10.5;

iii. Display the sum of the first and the last element.

double r = arr[0] + arr[14];
System.out.println("Result = " + r);

iv. Write a loop that computes the sum of all elements in the array.

double sum = 0;
for (int i = 0; i < 15; i++) {
    sum += arr[i];
}
System.out.println("Sum = " + sum);