Skip to content

← Back to Overview

Positive or Negative Number Check

Concept Explanation

What is it?

This program classifies a numerical input as either positive (greater than zero), negative (less than zero), or zero (equal to zero). It's a fundamental conditional check based on the number line.

Why is it important?

Identifying the sign of a number is a basic yet crucial operation in many programming scenarios. It dictates different behaviors, calculations, or validations depending on whether a value represents an increase, a decrease, or no change.

Where is it used?

  • Financial Applications: Checking if a balance is positive (credit) or negative (debt).
  • Game Development: Determining if a player has positive health, negative score, or zero resources.
  • Data Validation: Ensuring that input values fall within an expected range (e.g., ages must be positive).
  • Control Systems: Adjusting actions based on sensor readings being above, below, or at a set point.

Real-world example

When you check your bank account balance, if it's positive, you have money. If it's negative, you're overdrawn. If it's exactly zero, your account is empty. This program performs the same basic classification.


Algorithm

  1. Start.
  2. Get a number (num) from the user.
  3. If num is greater than 0: a. Display that num is positive.
  4. Else if num is less than 0: a. Display that num is negative.
  5. Else (num is equal to 0): a. Display that num is zero.
  6. End.

Edge Cases: - Non-numeric input (handled by language-specific error mechanisms or explicit validation). - Floating-point numbers: Comparisons should work correctly for double or float types.


Implementations

import java.util.Scanner;

public class PositiveOrNegative {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        double number = scanner.nextDouble();

        System.out.println("Number entered: " + number);

        if (number > 0) {
            System.out.println("The number is POSITIVE.");
        } else if (number < 0) {
            System.out.println("The number is NEGATIVE.");
        } else {
            System.out.println("The number is ZERO.");
        }

        scanner.close();
    }
}
# Get a number from the user
num_str = input("Enter a number: ")
num = float(num_str)

print(f"Number entered: {num}")

if num > 0:
    print("The number is POSITIVE.")
elif num < 0:
    print("The number is NEGATIVE.")
else:
    print("The number is ZERO.")
#include <stdio.h>

int main() {
    double num;

    printf("Enter a number: ");
    scanf("%lf", &num);

    printf("Number entered: %.2lf", num);

    if (num > 0) {
        printf("The number is POSITIVE.");
    } else if (num < 0) {
        printf("The number is NEGATIVE.");
    } else {
        printf("The number is ZERO.");
    }

    return 0;
}
SET SERVEROUTPUT ON;
DECLARE
  input_num   NUMBER := &Enter_a_Number;
BEGIN
  DBMS_OUTPUT.PUT_LINE('Input Number: ' || input_num);

  IF input_num > 0 THEN
    DBMS_OUTPUT.PUT_LINE('The number is POSITIVE.');
  ELSIF input_num < 0 THEN
    DBMS_OUTPUT.PUT_LINE('The number is NEGATIVE.');
  ELSE
    DBMS_OUTPUT.PUT_LINE('The number is ZERO.');
  END IF;
END;
/

Explanation

  • Java: Uses if-else if-else structure with > and < comparison operators. Scanner handles double input, suitable for any real number.
  • Python: Employs if-elif-else statements. float() converts string input to numbers. The comparison logic is straightforward.
  • C: Reads double input using scanf("%lf", ...). The comparisons are performed with if-else if-else, and printf() displays the result.
  • Oracle: Implemented in PL/SQL. Uses NUMBER data type for numerical comparison within IF-ELSIF-ELSE blocks. Substitution variables for interactive input.

Complexity Analysis

  • Time Complexity: O(1) - A fixed number of comparisons are performed.
  • Space Complexity: O(1) - A fixed number of variables are used.

Flowchart

graph TD
    A[Start] --> B[Get Number]
    B --> C{Number > 0?}
    C -- Yes --> D[Display POSITIVE]
    C -- No --> E{Number < 0?}
    E -- Yes --> F[Display NEGATIVE]
    E -- No --> G[Display ZERO]
    D --> H[End]
    F --> H
    G --> H

Sample Dry Run

Step Number Number > 0? Number < 0? Description
Input 10 - - User enters 10
Decision 10 True - 10 is greater than 0
Output - - - Display "The number is POSITIVE."
End - - - Program terminates
Input -5 - - User enters -5
Decision -5 False - -5 is not greater than 0
Decision -5 - True -5 is less than 0
Output - - - Display "The number is NEGATIVE."
End - - - Program terminates
Input 0 - - User enters 0
Decision 0 False - 0 is not greater than 0
Decision 0 - False 0 is not less than 0
Output - - - Display "The number is ZERO."
End - - - Program terminates

Practice Problems

Easy

  • Modify the program to check if the number is positive, negative, or exactly equal to a specific value (e.g., 100).
  • Extend the program to check if a number is even or odd.

Medium

  • Implement a function that takes a list of numbers and returns counts of positive, negative, and zero values.
  • Add input validation to ensure the user enters a valid number.

Hard

  • Create a system that categorizes a set of financial transactions as income (positive), expense (negative), or neutral.

"The only way to do great work is to love what you do." - Steve Jobs