1.Write a program in java where you prompt the user to choose how many numbers h
ID: 3639933 • Letter: 1
Question
1.Write a program in java where you prompt the user to choose how many numbers he/she wants to calculate the average of. When the user provides you with the input, say 5, then prompt the user to enter 5 numbers. Store all the 5 numbers in an array of integer type (int[] arrayname= new int[5];)2.Make another array that stores only the even numbers entered by the user and print them. For example, the user choses to enter 5 numbers and these numbers are: 2,3,4,5,6 then your new array should be of size 3 (there are three even numbers) and should store 2, 4 and 6. Print the contents of the new array.
Explanation / Answer
One of the ways of solving this question is to first check the number of even elements in the array and then initilaize the new array (here "newarray[]") for storing the even numbers....
import java.util.Scanner;
class t2
{
public static void main(String args[])
{
Scanner a= new Scanner(System.in);
System.out.println("Enter the number of numbers: ");
int b = a.nextInt();
int arrayname[] = new int[b];
int i,c=0,s=0,d=0;
for(i=0;i<b;i++)
{
System.out.println("Enter the "+(i+1)+"th number");
arrayname[i]=a.nextInt();
if (arrayname[i]%2 == 0) c++; //counting the number of even elments in array
s = s + arrayname[i];
}
int newarray[]= new int[c]; //declaring the new array to store even numbers
s = s/b;
System.out.println("The average of the numbers are: "+s);
for(i=0;i<b;i++)
{
if (arrayname[i]%2 == 0) {newarray[d] = arrayname[i]; d++;}
}
System.out.println("The even numbers are");
for(i=0;i<newarray.length;i++)
{
System.out.print(newarray[i]+" ");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.