How do you code in Java a method (lets say its called PosOddAverage) that:
- Takes an array of doubles as input
- Prints the avearge of positive odd numbers in the array
- Prints 'ERROR' for empty input array
An Example:
Input: [1.2,1.5,0.0,-2.3,3.5,7.1,-1.3]
Output: 4.03333333
Thanks :)
public class OddNumber {
public static void PosOddAverage(double[] arr)
{
int count=0;
// count of odd numbers in
the array
double sum=0;
// sum of odd numbers int the array
if(arr.length!=0) {
// if array is not empty then only we will
calculate average
for( int
i=0;i<arr.length;i++) { //traversing till array
length to calculate sum of the odd numbers
if((arr[i]*10)%2==1) {
// if
number is odd and positive(-1!=1 satisfying positive condition) we
will enter into loop(multiplying it by 10 eliminates decimal point
then making %2 equals one then its an odd number
sum=sum+arr[i];
// adding every odd number to sum value
count++;
// and incrementing the count
of the odd numbers
}
}
double
Average=sum/count; //average of the
odd numbers in the array where average=sum of digits/count of
digits
System.out.printf("Average of Positive Odd: %f",
Average); //finally printing the
average of the odd numbers in the array
}
else {
System.out.println("ERROR:Empty input Array"); // if
array is empty prints relevant message
}
}
public static void main(String[] args) {
double arr[]=
{1.2,1.5,0.0,-2.3,3.5,7.1,-1.3};
PosOddAverage(arr);
}
}
Output:
Output: If empty array is present.
Get Answers For Free
Most questions answered within 1 hours.