54.2k views
3 votes
In the main function, define an array that can contain four int values. Also define an int named sum. Write a function named getData which asks the user for the data and puts it in the array. Write a function named computeTotal which adds the data in the array and returns the sum. Write a function named printAll which takes the array and the sum as arguments. In the main function, call the getData function. Then in the main function, call the computeTotal function. Then in the main function, call the printAll function.

User Jamiew
by
4.4k points

1 Answer

5 votes

Answer:

import java.util.Scanner;

public class Array

{

public static void main(String[] args) {

int[] arr = new int[4];

int sum = 0;

getData(arr);

System.out.println("Total is: " + computeTotal(arr));

printAll(arr);

}

public static void getData(int[] arr) {

Scanner input = new Scanner(System.in);

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

System.out.print("Enter an element: ");

arr[i] = input.nextInt();

}

}

public static int computeTotal(int[] arr) {

int total = 0;

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

total += arr[i];

}

return total;

}

public static void printAll(int[] arr) {

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

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

}

}

}

Step-by-step explanation:

- Create a function called getData that takes one parameter, an array, and fills it with given numbers

- Create a function called computeTotal that takes one parameter, an array, and calculates the total of the numbers in the array

- Create a function called printAll that takes one parameter, an array, and prints the numbers in the array

Inside the main:

- Initialize the array and sum

- Call the functions to add elements, calculate the total, and print the values

User Staugaard
by
4.1k points