Find the minimum-tutorial
In Java, finding the minimum number in an array is a common operation in programming. This is useful for real-time applications such as tracking the lowest score, budget, temperature, etc.
Key Point
- Start with assuming the first element is the minimum.
- Traverse the array using a loop.
- Compare each value and update if a smaller number is found.
Example: Find Minimum in Array
package com.quipohouse;
import java.util.Scanner;
public class Main { public static void main(String[ ] args) {
System.out.println("Finding minimum number");
Scanner input1 = new Scanner(System.in); System.out.println("Enter array size"); int num1 = input1.nextInt();
int[] arr = new int[10]; System.out.println("Enter array values"); for (int i = 0; i < num1; i++) { arr[i] = input1.nextInt(); }
int min = arr[0]; // Start with first element int ans = MinValue(arr, min, num1);
System.out.println("Min value is = " + ans); }
public static int MinValue(int[ ] arr, int min, int num1) { for (int j = 0; j < num1; j++) { if (arr[j] < min) { min = arr[j]; } } return min; }}
Output:
Finding minimum numberEnter array size5Enter array values122502Min value is = 0
Explanation
Step | Description |
---|---|
arr[0] | First element is assumed to be the smallest |
for loop | Traverses all array elements |
if (arr[j] < min) | Compares and updates min if a smaller value exists |
return min; | Returns the smallest number |