8.6 Code Practice: Question 2

Instructions

Copy and paste your code from the previous code practice. If you did not successfully complete it yet, please do that first before

completing this code practice.

ate

After your program has prompted the user for how many values should be in the array, generated those values, and printed the

whole list, create and call a new function named sumarray. In this method, accept the array as the parameter. Inside, you should

sum together all values and then return that value back to the original method call. Finally, print that sum of values.

Sample Run

How many values to add to the array:

8

[17, 99, 54, 88, 55, 47, 11, 97]

Total 468

Respuesta :

Answer:

In Java:

import java.util.*;

public class Main{

public static int sumArray(int []arr, int lent){

    int sum = 0;

    for(int i = 0; i<lent; i++){

     sum+=arr[i];

 }

 return sum; }

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 System.out.print("Number of elements: ");

 int lent = input.nextInt();

 Random rd = new Random();

 int [] intArray = new int[lent];

 for(int i = 0; i< lent; i++){

     intArray[i] = rd.nextInt(100)+1;

 }

 System.out.print("Total: "+sumArray(intArray,lent));

}

}

Explanation:

No previous code was provided; So, I had to write the program from scratch (in Java)

Also, the elements of the array were generated randomly

See attachment for program source file where I used comments for explanatory purpose.

Ver imagen MrRoyal