Write a recursive method called countOddsInRange The method

Write a recursive method called countOddsInRange. The method returns how many odd numbers are between two positions (inclusive) of an array. The method header is: public int countOddsInRange(int[] numbers, int start, int end) For example: int[] a = {5, 2, 3, 6, 5, 1, 8}; int n = countOddsInRange(a, 1, 4); // n stores 2 int m = countOddsInRange(a, 0, 6); // m stores 4 You can include private, recursive helper methods if needed.

Solution

public static int countOddsInRange(int [] a, int first, int last) { int count = 0; if(first <= last) //check whether the end of array reached { count+=countOddsInRange(a, first + 1, last); if(a[first] % 2 != 0) // check whether its is odd number. { count++; // increment count if it is odd no. } } return count; }
Write a recursive method called countOddsInRange. The method returns how many odd numbers are between two positions (inclusive) of an array. The method header i

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site