5.4.3 : Print the sum and average of an array\'s elements. Modify the program to
ID: 3664459 • Letter: 5
Question
5.4.3 : Print the sum and average of an array's elements.
Modify the program to print the average as well as the sum. Hint: You don't actually have to change the loop, but rather change what you print.
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 8; // Number of elements
int[] userVals = new int[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
// Prompt user to populate array
System.out.println("Enter " + NUM_ELEMENTS + " integer values...");
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.println("Value: ");
userVals[i] = scnr.nextInt();
}
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
System.out.println("Sum: " + sumVal);
return;
}
}
Explanation / Answer
/**
* @author Srinivas Palli
*
*/
import java.util.Scanner;
public class ArraySum {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 8; // Number of elements
int[] userVals = new int[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
// Prompt user to populate array
System.out.println("Enter " + NUM_ELEMENTS + " integer values...");
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.print("Value " + (i + 1) + ": ");
userVals[i] = scnr.nextInt();
}
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
System.out.println("Sum : " + sumVal);
System.out
.println("Average : " + (float) sumVal / (float) NUM_ELEMENTS);
return;
}
}
OUTPUT:
Enter 8 integer values...
Value 1: 1
Value 2: 2
Value 3: 3
Value 4: 4
Value 5: 5
Value 6: 6
Value 7: 7
Value 8: 8
Sum : 36
Average : 4.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.