Question:
Java Programming: Problem:
Develop a program which allows the user to enter numbers into an array. Input will be as follows: The user will enter the total number of integers to be entered into the array. The user will then enter that number of unique integers (negative or positive). Do not allow the number of values entered to exceed the array size.
Develop methods to: ‘main’ method Print the array Sort the array ( YOU MUST DEVELOP YOUR OWN SORT METHOD
– don’t use someone else’s)
Determine the highest value
Determine the lowest value
Calculate the average value (double)
Answer:
ExampleArray.java
import java.util.Scanner;
public class ExampleArray
{
public static void main(String[] args)
{
int n, sum = 0;
float average;
Scanner s = new Scanner(System.in);
System.out.println("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n ; i++)
{
a[i] = s.nextInt();
sum = sum + a[i];
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.println(a[n - 1]);
System.out.println("lowest value : "+getMinValue(a));
System.out.println("highest value : "+getMaxValue(a));
//System.out.println("Sum:"+sum);
average = (float)sum / n;
System.out.println("Average:"+average);
}
// getting the maximum value
public static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maxValue) {
maxValue = array[i];
}
}
return maxValue;
}
// getting the miniumum value
public static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
Output :-
Enter no. of elements you want in array:5 Enter all the elements:1 5 2 8 9 Ascending Order: 1,2,5,8,9 lowest value : 1 highest value : 9 Average:5.0
0 Comments: