1) Write a program that accepts a set of integers (the user decides how many) and then stores them in an array. The main function then passes these values one by one to a method called get_even which returns 1 if the integer is even and 0 if it is odd. The main function should then specify which numbers were even, which ones were odd and their respective totals. It should also specify how many numbers were odd and how many were even. For example, if the user enters 25 34 56 17 14 20, the output should be: -
25 is an odd number
34 is an even number
56 is an even number
17 is an odd number
14 is an even number
20 is an even number
There is a total of 2 odd numbers and their sum is 42.
There is a total of 4 even numbers and their sum is 124.
NB: All data input and output should be done in main. Don’t use % any where in the main function (% can be used in the method).
import java.util.Scanner;
public class CheckEven {
public static boolean get_even(int value){
boolean evenOrOdd=false;
if(value % 2 == 0)
evenOrOdd=true;
return evenOrOdd;
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int sumOfOdd=0;
int sumOfEven=0;
int countOfOdd=0;
int countOfEven=0;
System.out.print("Enter the number of numbers in the array: ");
int quantity = in.nextInt();
int array[]=new int[quantity];
for(int i =0;i<quantity;i++)
{
System.out.print("Enter the "+(i+1)+" array element: ");
array[i]=in.nextInt();
}
for(int i =0;i<quantity;i++)
{
if(get_even(array[i])){
sumOfEven+=array[i];
countOfEven+=1;
System.out.println(array[i]+" is an even number");
}
else{
sumOfOdd+=array[i];
countOfOdd+=1;
System.out.println(array[i]+" is an odd number");
}
}
System.out.println("There is a total of "+countOfOdd+" odd numbers and their sum is "+sumOfOdd+".");
System.out.println("There is a total of "+countOfEven+" even numbers and their sum is "+sumOfEven+".");
}
}
Comments
Leave a comment