Skip to content

← Back to Overview

Zero or Non-Zero Check

Concept Explanation

What is it?

This program classifies a numerical input as either zero or non-zero. It's a binary classification that is foundational to many control flow decisions in programming.

Why is it important?

Checking for zero is a frequent operation in computing. It's often used to prevent errors (like division by zero), to terminate loops (e.g., counting down to zero), or to validate conditions (e.g., if a quantity is empty).

Where is it used?

  • Error Prevention: Most crucially, before performing division, checking if the divisor is non-zero.
  • Loop Control: Iterating until a counter reaches zero.
  • Game Development: Checking if a player's health is zero (game over), or if a resource count is zero.
  • Financial Systems: Validating if a transaction amount is zero or non-zero.

Real-world example

Imagine a traffic light system. If the timer for the green light reaches zero, it should change. If the timer is non-zero, the light remains green. This program implements the basic logic for such a decision.


Algorithm

  1. Start.
  2. Get a number (num) from the user.
  3. If num is equal to 0: a. Display that num is zero.
  4. Else (num is not equal to 0): a. Display that num is non-zero.
  5. End.

Edge Cases: - Non-numeric input (handled by language-specific error mechanisms or explicit validation). - Floating-point numbers: Direct equality (==) checks with floats can be problematic due to precision issues; using a small epsilon value for "near equality" is often preferred for more robust comparisons. This example uses direct comparison for simplicity.


Implementations

import java.util.Scanner;

public class ZeroOrNonZero {
    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 ZERO.");
        } else {
            System.out.println("The number is NON-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 ZERO.")
else:
    print("The number is NON-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 ZERO.");
    } else {
        printf("The number is NON-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 ZERO.');
  ELSE
    DBMS_OUTPUT.PUT_LINE('The number is NON-ZERO.');
  END IF;
END;
/

Explanation

  • Java: Uses a simple if-else statement with the == operator for comparison. Scanner handles double input.
  • Python: Employs an if-else statement. float() converts string input to numbers.
  • C: Reads double input using scanf("%lf", ...). Compares the number with 0 using if-else and displays the result with printf().
  • Oracle: Implemented in PL/SQL. Uses NUMBER data type for numerical comparison within an IF-ELSE block. Substitution variables for interactive input.

Complexity Analysis

  • Time Complexity: O(1) - A single comparison is 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 ZERO]
    C -- No --> E[Display NON-ZERO]
    D --> F[End]
    E --> F

Sample Dry Run

Step Number Number == 0? Description
Input 5 - User enters 5
Decision 5 False 5 is not equal to 0
Output - - Display "The number is NON-ZERO."
End - - Program terminates
Input 0 - User enters 0
Decision 0 True 0 is equal to 0
Output - - Display "The number is ZERO."
End - - Program terminates

Practice Problems

Easy

  • Modify the program to check if a number is positive, negative, or zero.
  • Extend the program to check if a number is even or odd.

Medium

  • Write a program that counts the number of zero and non-zero values in a list of numbers.
  • Add input validation to ensure the user enters a valid number.

Hard

  • Implement a robust numeric input parsing function that handles various string formats (e.g., "0", "0.0", " 0 ") and correctly identifies them as zero or non-zero.

"The computer does not care about your feelings, it only cares about your logic." - Anonymous