Write a program that initialize an array of size 10. Find the Sum and average of only even numbers and print the result on screen.
Answers
Answer:
// Java program to find out
// Sum of elements at even and
// odd index positions separately
import java.io.*;
class EvenOddSum {
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int even = 0, odd = 0;
// Loop to find even, odd sum
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 0)
even += arr[i];
}
System.out.println("Even index positions sum: " + even);
}
}
program to find average of even numberpublic class OddEvenAvgArray2{
public static void main(String args[]){
int arr[]={14,43,59,68,71,86}; //1
int oddSum=0,evenSum=0,evenCount=0,oddCount=0; //2
for(int i=0; i<6; i++){ //3
if(arr[i]%2==0){ //4
evenSum=evenSum+arr[i];
evenCount++;
}
else{ //5
oddSum=oddSum+arr[i];
oddCount++;
}
}
double avgOdd=oddSum/oddCount; //6
double avgEven=evenSum/evenCount;
System.out.println("\nAverage of even numbers are: "+avgEven); //7
System.out.println("\nAverage of odd numbers are: "+avgOdd);
}
}