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 number){
boolean flag = false;
if(number % 2 == 0)
flag = true;
return flag;
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int oddSum=0;
int evenSum=0;
int oddCount=0;
int evenCount=0;
System.out.print("Enter the number of numbers in the array: ");
int number = in.nextInt();
int array[]=new int[number ];
for(int i =0;i<number ;i++)
{
System.out.print("Enter the "+(i+1)+" array element: ");
array[i]=in.nextInt();
}
for(int i =0;i<number;i++)
{
if(get_even(array[i])){
evenSum=evenSum+array[i];
evenCount= evenCount+1;
System.out.println(array[i]+" is an even number");
}
else{
oddSum=oddSum+array[i];
oddCount=oddCount+1;
System.out.println(array[i]+" is an odd number");
}
}
System.out.println("There is a total of "+oddCount+" odd numbers and their sum is "+oddSum+".");
System.out.println("There is a total of "+evenCount+" even numbers and their sum is "+evenSum+".");
}
}
Comments
Leave a comment