137k views
3 votes
We have written a method called sum with an int[] parameter nums. We want our sum method to compute the sum of nums, but our code has a bug (or perhaps bugs?) in it.

Fix the bugs.

We have written a method called sum with an int[] parameter nums. We want our sum-example-1

1 Answer

4 votes

Answer:

Following are the code to this question:

public class Main//defining a class-main

{

public static int sum(int[] nums)//defining a method sum that accepts array

{

int total = 0;//defining integer variable total

for(int num : nums) // use for-each loop

{

total += num;//add array value in total variable

}

return total;//use return keyword to return the total value

}

public static void main(String []ar )//defining a main method

{

int[] nums={1,2,3,4,5};//defining 1-D array nums

System.out.println(sum(nums));//use print function to call sum method

}

}

Output:

15

Step-by-step explanation:

In the class "Main", a static method, "sum" is defined, that accepts array in its parameter and inside the method, an integer variable "total" is define, that uses the for each loop to add array value in a total variable and use a return keyword to return its value.

Inside the main method, an integer array nums are defined, that holds store some values and use the print function to call the sum method.

User Darren Haynes
by
4.4k points