🔺 Find the Largest and Smallest Number in an Array (Java)
🧩 What problem are we solving?
Given an array of numbers, we need to identify the largest and smallest values without sorting the array.
This is one of the most fundamental problems in programming — often used to teach how to iterate, compare, and track state within a loop.
Example:
If we have
Then:
✅ Largest value = 55
✅ Smallest value = 1
⚙️ How it works (step by step)
-
Initialize two variables:
-
largest= first element in the array (numbers[0]) -
smallest= first element in the array (numbers[0])
-
-
Iterate through the array starting from the second element (index
1). -
For each element:
-
If the element is greater than
largest, updatelargest. -
If the element is smaller than
smallest, updatesmallest.
-
-
After scanning all elements, print both values.
🧠Example Walkthrough
Let’s trace the logic for:
| Step | Current Number | Largest | Smallest |
|---|---|---|---|
| Start | 35 | 35 | 35 |
| 1 | 21 | 35 | 21 |
| 2 | 44 | 44 | 21 |
| 3 | 55 | 55 | 21 |
| 4 | 22 | 55 | 21 |
| 5 | 1 | 55 | 1 |
| 6 | 7 | 55 | 1 |
✅ Final Output:
package com.vinod.test;
/**
*@authorvinodkariyathungalkumaran
*
*/
public class FindLargestAndSmallestNumber {
public static void main(String[] args) {
int numbers[] = new int[] { 35, 21, 44, 55, 22, 1, 7 };
int smallest = numbers[0];
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest value " + largest);
System.out.println("Smallest value " + smallest);
}
}
Output
Largest value 55
Smallest value 1
No comments:
Post a Comment