Skip to content

← Back to Overview

Java Program - Smallest of Three Numbers

Concept Explanation

What is it?

This program compares three numerical values provided by the user and determines which one is the lowest.

Real-world example

Imagine you have three prices for the same product from different stores. This program helps you find the cheapest option.


Algorithm

  1. Start
  2. Input three numbers: a, b, and c.
  3. Check if a is smaller than both b and c.
  4. Check if b is smaller than both a and c.
  5. Otherwise, c is the smallest.
  6. Display the smallest number.
  7. End

Implementations

import java.util.Scanner;

public class SmallestNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter three numbers:");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        int smallest;

        if (a <= b && a <= c) {
            smallest = a;
        } else if (b <= a && b <= c) {
            smallest = b;
        } else {
            smallest = c;
        }

        System.out.println("The smallest number is: " + smallest);
        sc.close();
    }
}

Explanation

  • Java
  • Logical AND (&&): Used to combine two conditions. Both must be true for the whole expression to be true.
  • Comparison Operators (<=): Handles cases where numbers might be equal.

Complexity Analysis

  • Time Complexity: O(1)
  • Space Complexity: O(1)


"Logic will get you from A to B. Imagination will take you everywhere." - Albert Einstein