Java Program to Check if a number is positive or negative

Logic to check if a number is positive or negative

Java program to check if a number is positive or negative has been shown here. A number n is said to be positive if it is greater than 0 i.e. n > 0 and it is considered as negative if it is less than 0 i.e. n < 0. If n = 0 then it is neither positive nor negative.

The following sections cover the Java program to determine if a number is positive or negative by using the above logic.






1. Algorithm to check if a number is positive or negative


// $n$ is an input number//


1. If $n\gt0$, then Return Positive else

2. If $n=0$, then Return Neither positive nor negative else

3. Return Negative





2. Pseudocode to check if a number is positive or negative


Input: A number $n$

Output: If $n$ is positive or negaive

1. Procedure positiveOrNegative($n$):

2. If $n\gt0$:

3. Return positive

4. Else:

5. If $n==0$:

6. Return Neither positive nor negative

7. Else:

8. Return negative

9. End Procedure





3. Time complexity to check if a number is positive or negative


Time Complexity: O(1)





4. Java Program to check if a number is positive or negative

Code has been copied
/********************************************************
                alphabetacoder.com
Java program to check if a number is positive or negative
*********************************************************/

import java.util.Scanner;
public class Main {
    public static void main(String args[]) {
        // declare variable
        int n;
        
        // declare an instance of scanner class
        Scanner sc = new Scanner(System.in);

        //take input of number
        System.out.print("Enter the number = ");
        n = sc.nextInt();

        //check if n is postive or negative
        if (n > 0)
            System.out.print(n + " is positive");
        else {
            if (n == 0)
                System.out.print(n + " is neither positive nor negative");
            else
                System.out.print(n + " is negative");
        }
    }
}

Output


Case 1:

Enter the number = -5

-5 is negative


Case 2:

Enter the number = 7

7 is positive


Case 3:

Enter the number = 0

0 is neither positive nor negative