Problem:
Design an algorithm to find the number of times the maximum occurs in an array of n elements.
Solution:
package array.programs;
import java.util.Scanner;
public class MaximumNumberOccurences {
int[] numbers;
int max;
int counter;
public static void main(String[] args) {
MaximumNumberOccurences maximumNumber = new MaximumNumberOccurences();
maximumNumber.getTheNumbers();
maximumNumber.findMaximum();
maximumNumber.findTheMaximumValueOccurences();
maximumNumber.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 findTheMaximumValueOccurences(){
for (int i = 0; i < numbers.length; i++) {
if(max == numbers[i]){
counter++;
}
}
}
public void printTheResult(){
System.out.println("the maximum value occurences is " + counter);
}
}
Output:
how many numbers
5
enter number
12
enter number
23
enter number
23
enter number
22
enter number
22
the maximum value occurences is 2
Design an algorithm to find the number of times the maximum occurs in an array of n elements.
Solution:
package array.programs;
import java.util.Scanner;
public class MaximumNumberOccurences {
int[] numbers;
int max;
int counter;
public static void main(String[] args) {
MaximumNumberOccurences maximumNumber = new MaximumNumberOccurences();
maximumNumber.getTheNumbers();
maximumNumber.findMaximum();
maximumNumber.findTheMaximumValueOccurences();
maximumNumber.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 findTheMaximumValueOccurences(){
for (int i = 0; i < numbers.length; i++) {
if(max == numbers[i]){
counter++;
}
}
}
public void printTheResult(){
System.out.println("the maximum value occurences is " + counter);
}
}
Output:
how many numbers
5
enter number
12
enter number
23
enter number
23
enter number
22
enter number
22
the maximum value occurences is 2
No comments:
Post a Comment