Operators Assignment 2 — Subtract Two Numbers Using the '-' Operator
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Subtract Two Numbers Using the '-' Operator

📑 On this page:
  • The subtraction operator
  • Order matters — a − b vs. b − a
  • How types affect the difference
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How the − operator computes the difference of two operands
  • Why a − b and b − a give different results (unlike addition)
  • How to handle negative results from subtraction
  • How integer subtraction differs from floating-point subtraction
  • What underflow is and how to avoid it
  • How to check the scanf return value for robust input handling

The subtraction operator

The subtraction operator − takes two operands and produces their difference. It's the second arithmetic operator after +, and unlike addition, it's not commutative: a − b is generally not equal to b − a. The result of a − b is −(b − a) — the sign flips. This single fact is the most important thing to remember about subtraction, and it trips up more beginners than any other arithmetic detail.

The operator is binary (two operands) and left-associative: in a − b − c, evaluation is (a − b) − c. Unlike addition, changing the grouping changes the result: (a − b) − c ≠ a − (b − c) in general. For example, (5 − 3) − 1 = 1, but 5 − (3 − 1) = 3. This is why you should always use parentheses when in doubt — the expression means what you think it means only when the grouping is explicit.

For integers, subtraction is exact within the type's range — same as addition. For int (typically 32 bits), the range is roughly ±2.1 billion. Beyond that, integer underflow (or overflow, depending on sign) occurs — undefined behavior in the C standard, wraparound in practice. For floating-point, subtraction preserves about 15 decimal digits of precision for double, but subtracting two nearly-equal values can cause catastrophic cancellation — a loss of precision that leaves you with fewer significant digits than expected.

💡 In one line: a − b gives the first number minus the second. Unlike addition, the order matters — 5 − 3 = 2, but 3 − 5 = −2.

Subtraction of two numbers in C — reading two integers with scanf, subtracting them with the - operator, and printing the difference with printf.

Order matters — a − b vs. b − a

Addition is commutative: a + b == b + a for all values (barring overflow and floating-point rounding). Subtraction is not: a − b == −(b − a), so unless a == b, the two results differ. If a > b, a − b is positive. If a < b, a − b is negative. If a == b, the difference is zero (for integers; for floating-point, it depends on whether the two values are exactly equal).

In a C program, this means the order of operations in diff = a - b matters. If you intended "the larger minus the smaller" (e.g., to compute a positive distance), you need to check which is larger first:

if (a >= b) {
    diff = a - b;
} else {
    diff = b - a;
}

Or, equivalently, use the absolute value: diff = (a > b) ? (a - b) : (b - a);. Either form ensures the difference is non-negative. For most exercises ("subtract two numbers"), the natural interpretation is a − b as written, and the result is signed — possibly negative.

In the assignment "subtract two numbers using the '-' operator", the standard answer is diff = a - b, where a is the first number and b is the second. If a = 10 and b = 3, the output is 7. If a = 3 and b = 10, the output is −7. That's the correct behavior — the program subtracts the second number from the first, and the sign of the result reflects the input order.

🎯 Key idea: subtraction is not commutative. a − b equals −(b − a). If you want a non-negative result (like "distance"), you must order the operands explicitly or use the absolute value.

How types affect the difference

The type of the result follows the same rules as addition: int − int → int, double − double → double, int − double → double. The operator itself is identical — only the meaning of the operands' bits changes. Integer subtraction is bitwise subtraction (with borrow), floating-point subtraction is a more complex operation involving exponent alignment and normalization.

Integer underflow. The most negative int value is INT_MIN (typically −2147483648 on 32-bit systems). Subtracting 1 from INT_MIN gives INT_MIN − 1, which is below the representable range — undefined behavior. On two's-complement systems, it wraps to INT_MAX. Similarly, adding 1 to INT_MAX overflows to INT_MIN. Both are forms of "integer overflow" (the umbrella term for out-of-range integer arithmetic), and both are undefined in C.

Floating-point cancellation. If you subtract two nearly-equal floating-point values, the result can have fewer significant digits than either input. For example, 1.0000001 − 1.0000000 = 0.0000001, which has only one significant digit (not the ~15 digits that double can represent). This is catastrophic cancellation, and it's why numerically-sensitive algorithms (like solving linear systems, computing derivatives) need to be careful about subtraction of nearby values. For simple "subtract two numbers" exercises, this rarely matters, but it's worth knowing.

Signed vs. unsigned. If you subtract two unsigned integers and the second is larger than the first, the result "wraps around" to a very large positive number (in the unsigned type). For example, 3u − 5u = 4294967294u (for 32-bit unsigned). This is not the same as −2 in the signed world. If you need negative results, use signed integers. Unsigned subtraction is common in low-level programming (bit manipulation, hashing) where wraparound is intentional, but it's a footgun in general-purpose code.

Complete C Programs

Here is the simplest version — subtracting two integers:

Program 1: Subtract two integers

#include <stdio.h>

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

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

    diff = a - b;

    printf("Difference = %d\n", diff);

    return 0;
}
                                

Only one thing differs from the addition program: the operator. Instead of sum = a + b, we write diff = a - b. Everything else — the declarations, the scanf, the printf — is identical. This is the beauty of arithmetic in C: the operators all have the same syntactic form, only the semantics change.

Here's the variant for floating-point numbers:

Program 2: Subtract two doubles

#include <stdio.h>

int main(void) {
    double a, b, diff;

    printf("Enter two numbers: ");
    scanf("%lf %lf", &a, &b);

    diff = a - b;

    printf("Difference = %.2lf\n", diff);

    return 0;
}
                                

Same shape, different types. double instead of int, %lf instead of %d, %.2lf for two decimal places. For 7.5 − 2.5, this gives 5.00. For 2.5 − 7.5, it gives −5.00. The sign is preserved because floating-point arithmetic is signed by default — same as int.

A third variant — with input validation — shows the robust pattern:

Program 3: Robust subtraction with input validation

#include <stdio.h>

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

    printf("Enter two integers: ");
    if (scanf("%d %d", &a, &b) != 2) {
        fprintf(stderr, "Error: invalid input\n");
        return 1;
    }

    diff = a - b;

    printf("%d - %d = %d\n", a, b, diff);

    return 0;
}
                                

This version adds two improvements. First, it checks that scanf successfully read two integers; if not (e.g., the user typed "abc" or only one number), it prints an error to stderr and exits with code 1. Second, it prints the full expression — 10 - 3 = 7 — not just the result, which makes the output easier to verify at a glance.

All three programs are valid answers to the assignment. Program 1 is the canonical answer for "subtract two integers." Program 2 handles decimals. Program 3 is the robust version you'd write in production code, where inputs come from real users and can be malformed.

Program Output

Here's a sample run of Program 1:

Enter two integers: 10 3
Difference = 7
                            

The user types 10 3, and the program prints Difference = 7. The math is 10 − 3 = 7, straightforward.

Now try reversing the order — enter 3 10 instead:

Enter two integers: 3 10
Difference = -7
                            

The output is −7 — the sign flipped. That's because the program always computes a − b, and if b is larger than a, the result is negative. This is correct behavior for subtraction. If the assignment expects a non-negative result, you need to either reorder the operands or use abs():

#include <stdlib.h> /* for abs() */

int distance = abs(a - b);
printf("Distance = %d\n", distance);

This is the right approach for "how far apart are a and b" — the distance is |a − b|, not a − b. But the assignment says "subtract two numbers", so a − b with the sign preserved is the correct interpretation.

Program 2 with decimal inputs:

Enter two numbers: 7.5 2.5
Difference = 5.00
                            

Program 3 with the expression in the output:

Enter two integers: 10 3
10 - 3 = 7
                            

Edge case — INT_MIN subtraction underflow:

Enter two integers: -2147483648 1
Difference = 2147483647
                            

Wait — −2147483648 − 1 should be −2147483649, which is below INT_MIN (−2147483648). The program prints 2147483647 (which is INT_MAX). That's integer underflow: INT_MIN − 1 wraps to INT_MAX on two's-complement systems. Undefined behavior in C — the result isn't guaranteed to be wraparound. This is a real concern for financial or scientific code that handles near-boundary values.

🔍 Try this: run Program 1 with 10 3, 3 10, 5 5, and -3 -5. The first gives 7, the second gives −7, the third gives 0, and the fourth gives −3 − (−5) = 2. Note that subtracting a negative is the same as adding a positive — that's a fundamental algebraic rule, and C's − operator respects it.

Step-by-Step Explanation

Let's walk through Program 1 line by line.

1. #include <stdio.h>

Same as in the addition program — includes the I/O library for printf and scanf. Nothing changes here; every program that reads input or prints output needs this header.

2. int main(void) { ... }

The entry point. Same as before. The int return type means the function returns an integer to the operating system, and the void argument list means main takes no arguments.

3. int a, b, diff;

Declares three integers. a and b hold the inputs; diff holds the result. Note the variable name: diff, not sum. Using meaningful names (diff for "difference", sum for "sum", prod for "product") makes code much easier to read. A reviewer glancing at the code knows instantly what the variable represents.

4. printf("Enter two integers: ");

Prompts the user. Same as before. The prompt text is slightly different ("Enter two integers" instead of "Enter two numbers") because the type is int, not double. This is a small but useful convention: match the prompt to the input type, so the user knows what kind of input is expected.

5. scanf("%d %d", &a, &b);

Reads two integers. The & is essential — forgetting it is the most common scanf bug. The format string "%d %d" reads two decimal integers, skipping leading whitespace between them. If the user types 10 3 (with a space), both numbers are read correctly. If the user types 10,3 (with a comma), scanf reads 10, then stops at the comma (since %d expects a digit or sign, not a comma), and the second %d fails — b is left unassigned (garbage value). This is why input format matters.

6. diff = a - b;

The heart of the program. a − b computes the difference. For a = 10, b = 3, the result is 7 — the bits of 10 (1010) minus the bits of 3 (0011) gives 0111 (7). This is bitwise subtraction with borrow, but you don't need to think about that — the result is the arithmetic difference.

For a = 3, b = 10, the result is −7. How does that work? The integer subtraction computes 3 − 10 = −7, which is represented in two's complement as the bit pattern for −7 (all the bits of 7, inverted, plus 1). The hardware handles this transparently; the programmer only sees "−7" printed via %d, which knows how to decode the two's-complement representation into a decimal string.

7. printf("Difference = %d\n", diff);

Prints the result. The %d format specifier is the same as in the addition program — it prints a signed decimal integer, including a leading minus sign for negative values. The \n is a newline, moving the cursor to the next line for clean output.

For diff = 7, the output is Difference = 7. For diff = −7, the output is Difference = -7. The format specifier handles both cases — you don't need to check the sign manually.

8. return 0;

Returns 0 to the operating system, signaling success. Same as before.

9. Floating-point subtraction — Program 2

Program 2 changes the types to double and the format specifiers to %lf / %.2lf. The subtraction operator works the same way — bit-level arithmetic, but on the IEEE 754 representation instead of two's complement. Floating-point subtraction involves aligning the exponents of the two operands, subtracting the mantissas, and renormalizing the result. The programmer doesn't need to know the details; the result is the arithmetic difference, with a precision of about 15 decimal digits.

One subtlety: floating-point subtraction of nearby values is exact (there's no rounding to introduce — the result is exactly representable if the inputs are close). But floating-point subtraction of very different values can lose the smaller one — subtracting 1e-20 from 1.0 gives 1.0, because the tiny difference is below the precision of the result. This is a form of rounding, not a bug — it's the fundamental limitation of finite-precision floating-point.

10. Subtraction of negative numbers

C handles negatives naturally. If a = -3 and b = 5, then a − b = −3 − 5 = −8. If a = -3 and b = -5, then a − b = −3 − (−5) = −3 + 5 = 2. The subtract operator "flips the sign" of the second operand before adding: a − b == a + (−b). That's the mathematical definition, and C respects it.

This is worth remembering: − is just + with the second operand negated. So subtraction of a negative is addition of a positive. And subtraction of a positive is addition of a negative. Both cases are handled by the same hardware operation — there's no special-case code path for negatives.

11. Integer underflow

The int type on most modern systems is 32 bits, representing values from −2,147,483,648 (INT_MIN) to 2,147,483,647 (INT_MAX). Subtracting 1 from INT_MIN gives −2,147,483,649, which is below the range — it can't be represented. On two's-complement hardware, the value wraps to INT_MAX (2,147,483,647). On other hardware (rare today), it might trap or saturate. The C standard says it's undefined behavior — no guarantees. To avoid it, use long long (range ±9.2 quintillion) or check for underflow explicitly.

A common defensive pattern:

if (b > 0 && a < INT_MIN + b) {
    /* underflow */
} else {
    diff = a - b;
}

This checks whether a − b would underflow before actually performing the subtraction. For simple exercises, this check is overkill. For production code that handles user input, it's essential.

12. Extending the program

The natural extension is a calculator that asks the user which operation to perform, then reads two numbers and prints the result. For subtraction, the calculator distinguishes a − b from b − a — a good UI displays the expression so the user knows what was computed. You'll see this pattern in Assignment 3 (multiplication) and Assignment 4 (division), where the operator changes but the structure stays the same.

🎯 Key idea: subtraction is not commutative. a − b and b − a differ by a sign. If the result is negative, that's correct — the second number was larger than the first. Use abs(a − b) if you want a non-negative distance, but for "subtract two numbers," the signed result is the answer.

Frequently Asked Questions

1. Why does my program print a negative number?

Because the second number is larger than the first. The program computes a − b, and if b > a, the result is negative. For example, entering 3 10 gives Difference = -7. This is correct behavior — the result is signed, and the sign reflects the input order. If you want a non-negative result, swap the operands (b − a) or use abs(a − b) from <stdlib.h>.

2. Can I subtract a larger number from a smaller one?

Yes — subtraction is defined for all integer pairs (within the type's range). 3 − 10 = −7, −5 − 10 = −15, etc. C's arithmetic is signed by default, so negative results are normal. The only case that fails is when the result underflows the type's range (e.g., INT_MIN − 1), which is undefined behavior. For normal-sized inputs, there's no issue.

3. What's the difference between a - b and b - a?

They differ by a sign: a − b = −(b − a). For a = 10, b = 3, a − b = 7 and b − a = −7. For a = 3, b = 10, a − b = −7 and b − a = 7. The absolute values are the same, but the signs are opposite. If you're computing a distance or a magnitude, use abs(a − b) to get a non-negative result regardless of input order.

4. What happens if the result underflows?

For int, underflow (result below INT_MIN) is undefined behavior. On two's-complement systems, it wraps to a positive value. For example, INT_MIN − 1 gives INT_MAX. On some systems, it may trap or produce a completely wrong value. To avoid underflow, use long long (range ±9.2 quintillion) or check for underflow before subtracting. For most programs, underflow only matters for extreme inputs, and simple exercises don't encounter it.

5. Can subtraction be used with floating-point numbers?

Yes — C's − operator works on both integers and floating-point types. For double, subtraction follows the IEEE 754 rules (alignment, mantissa subtraction, renormalization), with about 15 significant digits of precision. Subtraction of nearby floating-point values can cause catastrophic cancellation — a loss of precision that leaves you with fewer significant digits than expected. For example, 1.0000001 − 1.0000000 = 0.0000001 has only one significant digit. For simple exercises, this doesn't matter, but for numerical algorithms, it does.

6. Why is the variable called diff and not sub or result?

Any name works — diff, result, answer, difference, x. Short names are fine for small programs, but meaningful names (like diff for "difference") make code self-documenting. A reviewer glancing at the code sees "diff" and immediately knows it holds the difference, not the sum or the product. In production code, this small clarity is worth the extra characters.

💡 Tip: once this works, extend it to a mini calculator that asks which operation to perform (+, −, *, /), then reads two numbers and prints the result. For subtraction, the calculator should display the expression (a − b = result) so the user knows which operand was subtracted from which. That's the natural next step — Assignments 3 and 4 build on the same skeleton, so you'll be writing four programs that differ only in the operator and the variable name.

📖 Related Tutorials

  • Previous: Add Two Numbers Using the '+' Operator
  • Next: Multiply Two Numbers Using the '*' Operator
  • All 15 Operator Assignments in C
  • Arithmetic Operators in C
  • Operators and Expressions
  • Built-in Data Types in C
  • Basic Input/Output Statements
  • Operators FAQ

Previous Topic: -->> 1. Add Two Numbers Using the '+' Operator   ||   Next Topic: -->> 3. Multiply Two Numbers Using the '*' Operator


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.