JavaScript Program to Find the Smallest Among Three Numbers

Introduction

Finding the smallest number among multiple inputs is a common problem in programming. It helps in scenarios where you need to determine the minimum value from a given set. This program focuses on comparing three numbers and identifying the smallest one using basic comparison operations in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts three numbers.
  • Determines which of the three numbers is the smallest.
  • Returns and displays the smallest number.

Example:

  • Input: 5, 10, 15

  • Output: 5 is the smallest number

  • Input: -7, 0, -3

  • Output: -7 is the smallest number

Solution Steps

  1. Read the Input Numbers: Provide three numbers either as part of user input or directly within the code.
  2. Compare the Numbers: Use conditional logic (if-else statements) to compare the three numbers and identify the smallest.
  3. Display the Result: Print the smallest number.

JavaScript Program

// JavaScript Program to Find the Smallest Among Three Numbers
// Author: https://www.javaguides.net/

function findSmallestNumber(num1, num2, num3) {
    let smallest;

    // Step 1: Compare the three numbers
    if (num1 <= num2 && num1 <= num3) {
        smallest = num1;
    } else if (num2 <= num1 && num2 <= num3) {
        smallest = num2;
    } else {
        smallest = num3;
    }

    // Step 2: Display the result
    console.log(`${smallest} is the smallest number`);
}

// Example input
let number1 = 5;
let number2 = 10;
let number3 = 15;
findSmallestNumber(number1, number2, number3);

Output

5 is the smallest number

Example with Different Input

let number1 = -7;
let number2 = 0;
let number3 = -3;
findSmallestNumber(number1, number2, number3);

Output:

-7 is the smallest number

Explanation

Step 1: Compare the Three Numbers

  • The function findSmallestNumber() compares three numbers using if-else statements:
    • It first checks if num1 is smaller than or equal to both num2 and num3.
    • If not, it checks if num2 is smaller than or equal to both num1 and num3.
    • If both conditions fail, num3 is the smallest.

Step 2: Display the Result

  • The smallest number is stored in the variable smallest and printed using console.log().

Conclusion

This JavaScript program demonstrates how to find the smallest number among three given numbers using comparison operators. This approach can be applied in many scenarios where minimum values need to be identified from a set of inputs.

Comments