Operators Assignment 13 — Find the Minimum of Two Numbers Without Using 'if'
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Minimum of Two Numbers Without Using the 'if' Statement

📑 On this page:
  • Three ways to find the minimum
  • Method 1 — ternary operator
  • Method 2 — arithmetic formula
  • Method 3 — bitwise sign trick
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to find the minimum with the ternary operator ? :
  • The arithmetic min formula: (a + b − |a − b|) / 2
  • A bitwise sign-extraction trick that avoids if, abs(), and ?:
  • How the sign bit of (a − b) encodes which operand is smaller
  • Which method is clearest, which is fastest, and which is safest

Three ways to find the minimum

The obvious way to find the minimum uses an if:

int min;
if (a < b) min = a;
else min = b;

But the assignment forbids if. There are three classic alternatives:

  • Ternary operator: (a < b) ? a : b — the idiomatic branchless form.
  • Arithmetic formula: (a + b − abs(a − b)) / 2 — no conditional at all, just arithmetic.
  • Bitwise sign trick: use the sign bit of (a − b) to select a or b without a conditional.

All three give the same answer. The ternary is clearest, the arithmetic is the most "forbidden-if" pure form, and the bitwise is the fastest — but each has tradeoffs you should know about.

💡 In one line: (a < b) ? a : b is the ternary form, (a + b − abs(a − b)) / 2 is the arithmetic form, and the sign bit of (a − b) is the bitwise trick.
Find the minimum of two numbers in C without if — comparing the ternary, arithmetic, and bitwise approaches.

Method 1 — ternary operator

The conditional operator ? : evaluates one of two expressions based on a condition. It's the branchless-friendly alternative to if/else when the branch is a simple choice between two values:

(a < b) ? a : b

Read as: "if a is less than b, the result is a; otherwise, it's b." That's the minimum. The ternary operator is technically a conditional (it uses a condition), but it's an expression, not a statement — so it satisfies the strictest reading of "no if statement."

On modern CPUs, compilers often compile (a < b) ? a : b into a branchless sequence using CMOV (conditional move) — so this form is both clear and fast. It's the idiomatic answer for "min without if."

Method 2 — arithmetic formula

The arithmetic minimum uses the identity:

min(a, b) = (a + b − |a − b|) / 2

Why it works: consider a = 5, b = 3.

  • a + b = 8
  • |a − b| = 2
  • (8 − 2) / 2 = 6 / 2 = 3

Result: min(5, 3) = 3. Correct.

For a = 3, b = 5 (reversed):

  • a + b = 8
  • |a − b| = |−2| = 2
  • (8 − 2) / 2 = 3

Result: min(3, 5) = 3. Correct — the formula is symmetric.

The key insight: (a + b) is the sum, |a − b| is the difference. Subtracting the difference from the sum and dividing by 2 discards the larger value, leaving the smaller one. The formula is a standard identity, and it uses only arithmetic — no conditional, no comparison, no bit operation.

⚠️ Caution: this formula can overflow if a + b exceeds the type's range. For int, if a and b are both near 2 billion, their sum overflows. Use long long for the intermediate computations if the inputs might be large. For small inputs (say, under a billion), it's safe.

Method 3 — bitwise sign trick

For the truly branchless form, extract the sign bit of (a − b) and use it as a selector mask. The sign bit is the highest bit of a signed integer: 0 for non-negative, 1 for negative. In 32-bit two's complement, it's 0x80000000.

The trick:

int d = a − b;
int m = d >> (sizeof(int) * 8 − 1);  /* m = 0 or −1 */
int min = b + (d & m);

Here's what each line does:

  • d = a − b — the difference. Sign tells you which is smaller: negative if a < b, non-negative otherwise.
  • m = d >> 31 — arithmetic right shift of the sign bit. If d is negative, m = −1 (all 1s). If non-negative, m = 0 (all 0s). This works because the arithmetic right shift fills the vacated high bits with copies of the sign bit.
  • d & m — if m = −1, this is d; if m = 0, this is 0. So d & m is either d or 0, depending on whether d is negative.
  • b + (d & m) — if d is negative (a < b), add d = a − b to b: b + (a − b) = a. If non-negative, add 0: b.

Result: min(a, b). All in bit operations — no if, no ?:, no abs().

Complete C Programs

Program 1 — ternary operator:

Program 1: Minimum via ternary operator

#include <stdio.h>

int main(void) {
    int a, b, min;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    min = (a < b) ? a : b;

    printf("Minimum = %d\n", min);

    return 0;
}
                                

Program 2 — arithmetic formula (with abs):

Program 2: Minimum via arithmetic formula

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a, b, min;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    min = (a + b - abs(a - b)) / 2;

    printf("Minimum = %d\n", min);

    return 0;
}
                                

Program 3 — bitwise sign trick (truly branchless, no conditionals):

Program 3: Minimum via bitwise sign trick

#include <stdio.h>

int main(void) {
    int a, b, min;

    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    int d = a - b;
    int m = d >> (sizeof(int) * 8 - 1);   /* -1 or 0 */
    min = b + (d & m);

    printf("Minimum = %d\n", min);

    return 0;
}
                                

All three produce identical output for any pair of int values (with the arithmetic formula's overflow caveat for very large inputs, and the bitwise version's "arithmetic shift" assumption, which is true on all modern C compilers).

Program Output

All three programs give the same result. Sample runs:

Enter two integers: 5 3
Minimum = 3
                            

5 > 3, so the minimum is 3. Correct.

Enter two integers: 3 5
Minimum = 3
                            

3 < 5, so the minimum is 3. Correct — the formula is symmetric.

Enter two integers: -7 2
Minimum = -7
                            

−7 < 2, so the minimum is −7. Correct — negative values work.

Enter two integers: 5 5
Minimum = 5
                            

Equal values → the minimum is the common value. Correct.

Step-by-Step Explanation

1. Reading inputs: scanf("%d %d", &a, &b) reads two integers. The & is the address-of operator.

2. The ternary operator: (a < b) ? a : b evaluates the condition a < b. If true, it evaluates to a; if false, to b. Only one of a or b is "returned" as the expression value; both operands are evaluated (they're just variables), so no side effects are duplicated. The result is the minimum.

3. The arithmetic formula: (a + b − |a − b|) / 2 computes the average of "the sum" and "the negative of the difference" — which simplifies to the smaller of the two. Trace for a = 5, b = 3:

  • a + b = 8 (the sum)
  • |a − b| = 2 (the gap)
  • 8 − 2 = 6 (sum minus gap = twice the minimum)
  • 6 / 2 = 3 (the minimum)

For a = 3, b = 5, the same computation gives 3 — the formula doesn't care about order.

4. The bitwise sign trick: For a = 5, b = 3:

  • d = a − b = 2 (positive)
  • m = 2 >> 31 = 0 (non-negative → m is 0)
  • d & m = 2 & 0 = 0
  • min = b + 0 = 3

For a = 3, b = 5:

  • d = a − b = −2 (negative)
  • m = −2 >> 31 = −1 (all 1s in two's complement)
  • d & m = −2 & −1 = −2 (d is preserved)
  • min = b + (−2) = 5 + (−2) = 3

Both cases give 3 — the minimum.

5. Why >> 31 gives 0 or −1: On a 32-bit int, the sign bit is bit 31. Right shift by 31 moves it to bit 0 (the least significant bit). For a non-negative number, this is 0. For a negative number, arithmetic shift fills the high bits with 1s (because the sign bit was 1), producing all 1s — i.e., −1. This is the standard "extract sign" idiom.

6. The & mask: d & m is d & 0 = 0 when d is non-negative, and d & −1 = d when d is negative. So d & m is either 0 (don't add anything) or d (add the negative difference).

7. Adding to b: b + (d & m) is b + 0 = b (when d is non-negative, meaning a ≥ b), or b + (a − b) = a (when d is negative, meaning a < b). Both cases yield the minimum.

8. Which method to use: The ternary operator is the clearest, and modern compilers turn it into branchless code with CMOV on x86. The arithmetic formula is the most "pure arithmetic" but overflows for large inputs. The bitwise trick is the fastest and truly branchless but relies on arithmetic right shift — which is implementation-defined in C for negative values, though all modern compilers do it. Use ternary for readability, bitwise only when you're optimizing a hot path and know your compiler.

🎯 Key idea: "Minimum without if" has three idiomatic answers. The ternary is clearest. The arithmetic formula is cleverest. The bitwise trick is fastest. All three work; choose based on your constraints and readability requirements.

Frequently Asked Questions

1. Is the ternary operator really "without if"?

Yes — the ternary operator ? : is a distinct operator, not the if statement. In many interview contexts, "no if" means "no if keyword," which the ternary satisfies. Strictly speaking, the ternary is a conditional expression, so if the constraint says "no conditionals at all," you'd use the arithmetic or bitwise form instead. But usually, "no if statement" means exactly that — no if (cond) { ... } — and the ternary is fine.

2. Why does the arithmetic formula work?

Because a + b is the sum and |a − b| is the difference. Subtracting the difference from the sum and halving gives the smaller value. Mathematically: (a + b − |a − b|) / 2 = min(a, b). To see it, suppose a ≤ b. Then |a − b| = b − a, so the formula becomes (a + b − (b − a)) / 2 = (2a) / 2 = a = min(a, b). By symmetry, it also gives the correct answer when a > b. This is a well-known identity.

3. Why does the bitwise trick use >> 31?

Because on a 32-bit int, bit 31 is the sign bit. Right-shifting by 31 moves the sign bit to bit 0 (the LSB). For a non-negative number (sign bit 0), the result is 0. For a negative number (sign bit 1), arithmetic shift fills the high bits with 1s, giving all 1s = −1. So d >> 31 is 0 or −1 — a mask that selects or rejects d. This works on all modern C compilers that implement arithmetic right shift (which is virtually all of them). For portability across the C standard (which technically leaves right shift of negative values implementation-defined), cast to unsigned before shifting.

4. Which method is fastest?

The bitwise trick is the fastest at the assembly level — no branches, no overflow checks, just a few AND/XOR/shift instructions. But the ternary operator compiles to a CMOV (conditional move) on most x86 CPUs, which is also branchless and nearly as fast. In practice, for scalar min operations, the three methods are within a factor of 1–2 of each other in performance, and the compiler often generates equivalent code for the ternary and bitwise versions. Use whichever is clearest — the ternary — unless you're optimizing a tight loop and have profiled the difference.

5. What about overflow in the arithmetic formula?

If a + b overflows the type's range, the formula produces a wrong result. For int, the range is about ±2.1 billion, so a + b can overflow if a and b are both large (e.g., both near 2 billion). To avoid this, use long long for the intermediate computations: min = ((long long)a + b - llabs((long long)a - b)) / 2;. Or just use the ternary operator, which doesn't overflow (it just compares).

💡 Tip: the same three techniques apply to finding the maximum. The ternary becomes (a > b) ? a : b; the arithmetic becomes (a + b + abs(a − b)) / 2; the bitwise trick flips the sign of the mask selection. Try implementing all three for "maximum" as a follow-up — the exercise reinforces the underlying algebra.

📖 Related Tutorials

  • Previous: Swap Two Numbers Without a Temp Variable
  • Next: Check if a Number is Negative Without 'if'
  • Check Even/Odd Using Bitwise AND
  • Bitwise Right Shift Using '>>'
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 12. Swap Two Numbers Without a Temporary Variable   ||   Next Topic: -->> 14. Check if a Number is Negative Without Using 'if'


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
    • Initilization of 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
    • Elements Of User Defined Function
    • 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
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • 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
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • 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.