C++ Program to Check if a number is positive or negative

Logic to check if a number is positive or negative

C++ 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 C++ 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. C++ Program to check if a number is positive or negative

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

#include <iostream>

using namespace std;

int main() {
    // declare variable
    int n;

    //take input
    cout << "Enter the number = ";
    cin >> n;

    //check if n is postive or negative
    if (n > 0)
        cout << n << " is positive";
    else {
        if (n == 0)
            cout << n << " is neither positive nor negative";
        else
            cout << n << " is negative";
    }

    return 0;
}

Output


Case 1:

Enter the number = -9

-9 is negative


Case 2:

Enter the number = 11

11 is positive


Case 3:

Enter the number = 0

0 is neither positive nor negative