Problem:
Design and Implement an algorithm to find the minimum in an array.
Solution:
package array.programs;
import java.util.Scanner;
public class MinimumNumberInArray {
int[] numbers;
int min;
public static void main(String[] args) {
MinimumNumberInArray minimumNumber = new MinimumNumberInArray();
minimumNumber.getTheNumbers();
minimumNumber.findMinimum();
minimumNumber.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 findMinimum(){
min = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] < min){
min = numbers[i];
}
}
}
public void printTheResult(){
System.out.println("the minimum value is " + min);
}
}
Output:
how many numbers
10
enter number
12
enter number
34
enter number
33
enter number
33
enter number
12
enter number
2
enter number
2
enter number
34
enter number
34
enter number
34
the minimum value is 2
Design and Implement an algorithm to find the minimum in an array.
Solution:
package array.programs;
import java.util.Scanner;
public class MinimumNumberInArray {
int[] numbers;
int min;
public static void main(String[] args) {
MinimumNumberInArray minimumNumber = new MinimumNumberInArray();
minimumNumber.getTheNumbers();
minimumNumber.findMinimum();
minimumNumber.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 findMinimum(){
min = numbers[0];
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] < min){
min = numbers[i];
}
}
}
public void printTheResult(){
System.out.println("the minimum value is " + min);
}
}
how many numbers
10
enter number
12
enter number
34
enter number
33
enter number
33
enter number
12
enter number
2
enter number
2
enter number
34
enter number
34
enter number
34
the minimum value is 2
No comments:
Post a Comment