36.9k views
5 votes
9.6 Code Practice: Question 2

- Instructions

Add a method named "sumArray" to your last program that takes an array as a parameter and returns the sum of its values.

-Sample Run

How many values to add to the array:
8
[17, 99, 54, 88, 55, 47, 11, 97]
Total: 468

User Mitim
by
4.5k points

1 Answer

4 votes

A method named "sumArray" to your last program that takes an array as a parameter and returns the sum of its values.

Step-by-step explanation:

The program is used to add a list of arrays.

import java.util.Scanner;

public class MethodsArrays {

public static int[] fillArray() {

Scanner scan = new Scanner(System.in);

int size = scan.nextInt();

int array[] = new int[size];

int pos=0;

for(int i=0; i<array.length; i++) {

pos=i+1;

System.out.println("Enter element " + pos);

array[i]=scan.nextInt();

}

return array;

}

public static int sumArray(int [] array) {

int sum=0;

for(int i=0; i<array.length-1; i++) {

sum=array[i]+array[i+1];

}

return sum;

}

}

public static void printArray(int [] array) {

for(int i=0; i<array.length; i++) {

System.out.print(array[i] + " ");

}

}

public static void main(String[] args) {

fillArray();

System.out.println("Sum=" + sumArray(array));

printArray(array);

}

}

User Orlando Osorio
by
4.3k points