Check if the Number is Positive or Negative in javascript❔ 😕
We will see three methods for this problem statement
Introduction
Hi everyone In this article we will create a javascript program to check number is positive or Negative. follow conditions are used
N>0 then, Number is positive
N<0 then, Number is Negative
N=0 then, Number is zero
To solve this problem we will write code javascript code using three different methods
Method 1: Using Brute Force
Method 2: Using a Nested if-else statement
Method 3: Using the Ternary operator
Flow Chart
Method: 1
Using the Brute Force method
Algorithm
step1 Start
step 2 Insert Number.
step 3 If the number is greater than Zero then print “The number is Positive”
step 4 If the number is smaller than zero, then print, “The number is Negative”
step 5 Else print, “The number is Zero”
step 6 stop
Javascript Code
let num = 5;
//Conditions to check if the number is negative or positive
if (num > 0) {
console.log("The number is positive");
} else if (num < 0) {
console.log("The number is negative");
} else {
console.log("Zero");
}
Output:
The number is positive
Method: 2
Using nested if-else statement
Algorithm
step 1 Start
step 2 Insert the number.
step 3 If the number is the greater or equal move to the inner nested loop4
step 3.1 If the number is zero, print Zero
- step 3.2 Else print The Number is Positive
step 4 Else the number has to be negative, Print The number is Negative
step 5 stop
Javascript Code
let num1 = -5;
if(num1 => 0){
if(num === 0){
console.log("zero")
}else{
console.log("The number is positive");
}
}else{
console.log("The number is negative");
}
Output:
The number is negative
Method: 3
Algorithm
step 1 Start
step 2 Insert the number.
step 3 If the number is equal to zero, the Print Number is Zero
step 4 Else do the following – (num > 0)? “Positive”: “Negative”;
step 5 stop
Javascript Code
Using Ternary operator
let num2 = 0;
if(num2 === 0){
console.log("The number is zero")
}else{
let result = num2>0 ? "The number is positive" : "The number is negative";
console.log(result)
}
Output:
The Number is zero