Operators Assignment 14 — Check if a Number Is Negative Without Using 'if'
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check if a Number Is Negative Without Using 'if'

📑 On this page:
  • How to check a number without 'if'
  • Method 1 — arithmetic right shift
  • Method 2 — sign-bit mask
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Warnings and caveats
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to check whether a number is negative without using if
  • How to identify negative, zero, and positive values
  • How the arithmetic right-shift operator works on signed integers
  • How to use an array index to select a result
  • Why bitwise sign tests can be implementation-dependent in C

How to check a number without 'if'

A number can be negative, zero, or positive. Normally, we use an if...else statement to test these cases. In this assignment, we avoid if by calculating an index and using it to select a label from an array.

const char *str[] = { "Negative", "Zero", "Positive" };

The array has three labels: index 0 is "Negative", index 1 is "Zero", and index 2 is "Positive". The program calculates which index to use from the input number.

  • Arithmetic right-shift method: numType = (n >> (BITS - 1)) - (-n >> (BITS - 1)) + 1;
  • Sign-bit mask method: numType = ((n >> (BITS - 1)) & 1) + (n != 0);
💡 In one line: the sign bit of a negative signed integer is 1, while the sign bit of zero or a positive number is 0; shifting and arithmetic can turn that information into an array index.
C program to check whether a number is negative without using the if statement, using bitwise shift and an array of labels.

Method 1 — arithmetic right shift

On a typical two’s-complement system, right-shifting a negative signed integer by BITS - 1 produces -1, while right-shifting zero or a positive integer produces 0. This behavior is commonly used in bitwise sign tests, but C does not guarantee it for every implementation.

Trace with n = -10:

Step Operation Result Note
0 Initial value n = -10 The input is negative
1 n >> (BITS - 1) -1 Arithmetic right shift preserves the sign
2 -n >> (BITS - 1) 0 10 is positive, so the shifted result is 0
3 1 + (-1) - 0 0 Index 0 selects "Negative"

Therefore, the program prints -10 is Negative.

Method 2 — sign-bit mask

A more portable approach is to inspect the sign bit directly. First, convert the signed integer to an unsigned integer, then shift the sign bit into the lowest-bit position and mask it with 1.

unsigned int sign = ((unsigned int)n >> (BITS - 1)) & 1;

If sign is 1, the number is negative. If it is 0, the number is either zero or positive. We then distinguish zero from positive using the expression n != 0, which evaluates to 1 for nonzero values and 0 for zero.

Trace with n = 25:

Step Operation Result Note
0 Initial value n = 25 The input is positive
1 ((unsigned int)n >> (BITS - 1)) & 1 0 The sign bit is 0
2 n != 0 1 25 is not zero
3 0 + 1 1 Index 1 selects "Zero" in the original array

To make this method select the correct label, use the array order { "Zero", "Positive", "Negative" }, or adjust the index formula accordingly.

Complete C Programs

Program 1 — using arithmetic right shift:

Program 1: Check negative, zero, or positive using shift

#include <stdio.h>

#define BITS (sizeof(int) * 8)

int main(void) {
    int n;
    int numType;

    const char *str[] = { "Negative", "Zero", "Positive" };

    printf("Enter any number: ");
    scanf("%d", &n);

    numType = (n >> (BITS - 1)) - (-n >> (BITS - 1)) + 1;

    printf("%d is %s\n", n, str[numType]);

    return 0;
}
                                

Program 2 — using a portable sign-bit mask:

Program 2: Check negative, zero, or positive using sign-bit mask

#include <stdio.h>
#include <limits.h>

#define BITS (sizeof(int) * CHAR_BIT)

int main(void) {
    int n;
    unsigned int sign;
    int numType;

    const char *str[] = { "Negative", "Zero", "Positive" };

    printf("Enter any number: ");
    scanf("%d", &n);

    sign = ((unsigned int)n >> (BITS - 1)) & 1;
    numType = sign + (n != 0);

    printf("%d is %s\n", n, str[numType]);

    return 0;
}
                                

Program 1 is shorter and matches the classic bitwise puzzle. Program 2 is more portable because it does not depend on the behavior of right-shifting a negative signed integer.

Program Output

Running Program 1 with -10:

Enter any number: -10
-10 is Negative
                            

The arithmetic right shift produces -1 for a negative value, so the calculated index becomes 0.

Running Program 1 with 25:

Enter any number: 25
25 is Positive
                            

For a positive number, the first shift produces 0 and the second produces -1, so the calculated index becomes 2.

Running Program 1 with 0:

Enter any number: 0
0 is Zero
                            

For zero, both shifted values are 0, so the calculated index becomes 1.

Step-by-Step Explanation

1. Reading input: scanf("%d", &n) reads an integer from the user and stores it in n. The & operator gives scanf() the address of n.

2. Why the shift method works: BITS is the number of bits in an int, commonly 32. Shifting a negative signed value right by BITS - 1 fills the result with sign bits, producing -1 on typical two’s-complement systems.

3. Why the formula produces 0, 1, and 2: For a negative number, n >> (BITS - 1) is -1 and -n >> (BITS - 1) is 0, giving 1 + (-1) - 0 = 0. For zero, both are 0, giving 1. For a positive number, the first is 0 and the second is -1, giving 1 + 0 - (-1) = 2.

4. Why the array works: The array str[] stores the labels in the exact order needed by the calculated index: "Negative" at index 0, "Zero" at index 1, and "Positive" at index 2.

5. Why the sign-bit method is safer: Converting the value to unsigned int before shifting makes the right shift well-defined. The mask & 1 extracts only the sign bit, avoiding reliance on implementation-defined arithmetic shift behavior.

⚠️ Caution: Right-shifting a negative signed integer is implementation-defined in C. The first program is a useful bitwise-learning exercise, but the second program is safer for portable production code.

Warnings and caveats

Before using bitwise sign tests, understand their limitations:

  • Implementation-defined shift. The result of right-shifting a negative signed integer is implementation-defined, so Program 1 may not behave identically on every compiler or platform.
  • Overflow in -n. If n is INT_MIN, then -n overflows because its positive equivalent cannot be represented in an int.
  • Array bounds. The calculated index must always be 0, 1, or 2. An incorrect formula can access outside the array and cause undefined behavior.
  • Readability. Bit manipulation is compact but harder to understand than a simple if...else statement.
  • Production code. For real applications, use if (n < 0), else if (n == 0), and else. It is clearer, safer, and easier to maintain.

The bitwise method is excellent for learning how signed integers and shift operators work, but it should not be preferred over straightforward conditional statements in normal application code.

Frequently Asked Questions

1. Can we check a negative number without using if?

Yes. Use bitwise shifting and an array index. For example, calculate an index of 0 for negative, 1 for zero, and 2 for positive, then print the matching label.

2. What does n >> (BITS - 1) do?

It shifts the number right by one less than its total bit width. On many systems, this leaves only the sign information: -1 for a negative signed value and 0 for zero or a positive value.

3. Why is the result implementation-defined?

Because C does not specify whether right-shifting a negative signed integer performs an arithmetic shift or a logical shift. The result depends on the compiler and platform.

4. Does this program work for zero?

Yes. Zero is neither negative nor positive. The program assigns it index 1 and prints Zero.

5. Which version should be used in real projects?

Use a simple if...else statement for real projects. It is easier to read, avoids implementation-defined behavior, and clearly expresses the intended logic.

💡 Tip: Test the program with -1, 0, 1, INT_MAX, and INT_MIN. The INT_MIN case is especially important because negating it causes signed integer overflow.

📖 Related Tutorials

  • Previous: Find the Minimum of Two Numbers Without Using 'if'
  • Next: Toggle a Particular Bit Using Bitwise XOR
  • Bitwise Right Shift Using '>>'
  • Bitwise AND on Two Numbers Using '&'
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 13. Find the Minimum of Two Numbers Without Using 'if'   ||   Next Topic: -->> 15. Toggle a Particular Bit Using Bitwise XOR


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope, Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Accessing Structure Members
    • Structure Initialization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • Accessing Pointers — Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Using Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • Count Words, Lines in a File
    • Copy Files
    • Update File
    • Count Vowels in a File
  • Preprocessor
    • Macro Substitution Division
    • File Inclusion
    • Conditional Compilation
    • Other Directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage Classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage Classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage Classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.