Program to find out Largest and Smallest Value in an Array

🔺 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

[35, 21, 44, 55, 22, 1, 7]

Then:
Largest value = 55
Smallest value = 1


⚙️ How it works (step by step)

  1. Initialize two variables:

    • largest = first element in the array (numbers[0])

    • smallest = first element in the array (numbers[0])

  2. Iterate through the array starting from the second element (index 1).

  3. For each element:

    • If the element is greater than largest, update largest.

    • If the element is smaller than smallest, update smallest.

  4. After scanning all elements, print both values.


🧠 Example Walkthrough

Let’s trace the logic for:

numbers = [35, 21, 44, 55, 22, 1, 7]
StepCurrent NumberLargestSmallest
Start353535
1213521
2444421
3555521
4225521
51551
67551

✅ Final Output:

Largest value 55 Smallest value 1


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

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts