Monday 28 August 2017

Java Code to find the minimum, maximum and how many times they both occur in an array.

Problem:

Design and implement an algorithm to find the minimum, the maximum, and how many times they both occur in an array of n elements.

Solution:

package array.programs;

import java.util.Scanner;

public class MaximumAndMinimumNumberOccurences {

int[] numbers;
int max;
int maxCounter;
int min;
int minCounter;

public static void main(String[] args) {
MaximumAndMinimumNumberOccurences occurences = new MaximumAndMinimumNumberOccurences();
occurences.getTheNumbers();
occurences.findMaximum();
occurences.findMinimum();
occurences.findTheOccurences();
occurences.printTheResult();

}

public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers");
numbers = new int[scanner.nextInt()];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
scanner.close();
}

public void findMaximum(){
max = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] > max){
max = numbers[i];
}
}
}

public void findMinimum(){
min = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] < min){
min = numbers[i];
}
}
}

public void findTheOccurences(){
for (int i = 0; i < numbers.length; i++) {
if(max == numbers[i]){
maxCounter++;
}
if(min == numbers[i]){
minCounter++;
}
}
}

public void printTheResult(){
System.out.println("the maximum value is " + max + " and the occurences are " + maxCounter);
System.out.println("the minimum value is " + min + " and the occurences are " + minCounter);
}

}


Output:

how many numbers
10
enter number
1
enter number
2
enter number
3
enter number
4
enter number
5
enter number
6
enter number
6
enter number
6
enter number
1
enter number
6
the maximum value is 6 and the occurences are 4
the minimum value is 1 and the occurences are 2


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...