Find the Greatest of the Two Numbers in Javascript
We will discuss three methods to solve this problem using javascript
Introduction
Hi everyone today we find the Greatest of the Two Numbers in Javascript. let's discuss how to solve this problem statement. if you want to check out yesterday's problem click here.
The goal is to create a Javascript program that compares the two integer inputs Number1 and Number2 and finds the greater of the two numbers. To do this, we'll employ if-else clauses and print the result. Below are a few solutions to the problem indicated above.
Method 1: Using if-else Statement
Method 2: Using Ternary Operator
Method 3: Using the inbuilt max function
All the above-mentioned methods are discussed in detail in this article.
Method 1: Using if-else Statement
Algorithm
step 1: Take two number inputs from the user
step 2: check if both numbers are equal, print "Equal" if true
step 3: check if number 1 > number 2 print "Number 1 is greater" if true
step 4: check if number 1 < number 2 print "Number 2 is greater" if true
step 5: stop
Javascript Code
// using if-else statements
let num1 = 10,num2 = 20;
// console.log(num1,num2)
if(num1 == num2){
console.log("both are equal")
}else if(num1>num2){
console.log(num1+" is greater")
}else{
console.log(num2+" is greater")
}
Output
20 is greater
Method 2: Using Ternary Operator
Algorithm
step 1: Take two number inputs from the user
step 2: Initialize temporary value
step 3: check if both numbers are equal, print "Equal" if true
step 4: Check for the greatest among the two using Ternary Operator and store it into a temporary variable.
step 5: print the temporary number
Javascript Code
// ternary operator
let num1 = 10,num2 = 20, temp;
if(num1 == num2){
console.log("both are equals")
}else {
temp = num1 > num2 ? num1 : num2;
console.log(temp+ " is largest")
}
Output
20 is largest
Method 3: Using the inbuilt max function
Algorithm
step 1: Take two number inputs from the user
step 2: Call the inbuilt max function with number1 and number2 as arguments.
step 3: Print the returned value.
Javascript Code
// Using inbuilt max Function
let num1 = 12,num2 = 21;
if(num1 == num2){
console.log("Both are equal")
}else{
// Math.max(num1,num2) is used for finding maximum number.
console.log(Math.max(num1,num2)+" is greater")
}
Output
21 is greater
Conclusion
So this article we solved the problem statement using javascript language. I hope you found this article helpful for your web development journey.
If you fill this article informative please like this article, if you have any suggestions please comment on this article, share it on social media and follow me on
Hashnode - Gaurav Patil
Twitter - @GauravYPatil