Introduction
In many programming scenarios, it's essential to compare multiple values and determine which is the largest. This task involves finding the largest number from three provided numbers using basic comparison operators in JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts three numbers.
- Determines which of the three numbers is the largest.
- Returns and displays the largest number.
Example:
Input:
5
,10
,15
Output:
15 is the largest number
Input:
-7
,0
,-3
Output:
0 is the largest number
Solution Steps
- Read the Input Numbers: Provide three numbers either as part of user input or directly within the code.
- Compare the Numbers: Use basic conditional logic (
if-else
statements) to compare the three numbers and identify the largest. - Display the Result: Print the largest number.
JavaScript Program
// JavaScript Program to Find the Largest Among Three Numbers
// Author: https://www.javaguides.net/
function findLargestNumber(num1, num2, num3) {
let largest;
// Step 1: Compare the three numbers
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
// Step 2: Display the result
console.log(`${largest} is the largest number`);
}
// Example input
let number1 = 5;
let number2 = 10;
let number3 = 15;
findLargestNumber(number1, number2, number3);
Output
15 is the largest number
Example with Different Input
let number1 = -7;
let number2 = 0;
let number3 = -3;
findLargestNumber(number1, number2, number3);
Output:
0 is the largest number
Explanation
Step 1: Compare the Three Numbers
- The function
findLargestNumber()
compares three numbers usingif-else
statements.- First, it checks if
num1
is greater than or equal to bothnum2
andnum3
. - If not, it checks if
num2
is greater than or equal to bothnum1
andnum3
. - If both conditions fail,
num3
is considered the largest.
- First, it checks if
Step 2: Display the Result
- The largest number is stored in the variable
largest
and displayed usingconsole.log()
.
Conclusion
This JavaScript program demonstrates how to find the largest number among three given numbers using comparison operators. This approach is essential in scenarios where comparisons need to be made between multiple values. By understanding how to implement conditional logic, you can extend this program to compare even more numbers or add more complex conditions.
Comments
Post a Comment
Leave Comment