18.0k views
24 votes
1. Write a static method named computeOddSum that is passed an array of int's named numbers. The method must compute and return the sum of all the values in numbers that are odd. For example, if numbers is {3, 10, 11, 2, 6, 9, 5} then the value 28 should be returned since 3 11 9 5

User Moebius
by
3.7k points

1 Answer

13 votes

Answer:

The method in Java is as follows:

public static int computeOddSum(int [] myarray){

int oddsum = 0;

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

if(myarray[i]%2==1) {

oddsum+=myarray[i];

}

}

return oddsum;

}

Step-by-step explanation:

This defines the static method

public static int computeOddSum(int [] myarray){

This initializes oddsum to 0

int oddsum = 0;

This iterates through the array

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

This checks for odd number

if(myarray[i]%2==1) {

The odd numbers are added, here

oddsum+=myarray[i];

}

}

This returns the calculated sum of odd numbers

return oddsum;

}

To call the method from main, use:

int [] myarray = {3, 10, 11, 2, 6, 9, 5};

System.out.println("Odd sum = " + computeOddSum(myarray));

User Bhupesh
by
3.8k points