Introduction Assignment 11 — Add, Multiply, Subtract, Divide Two Numbers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Accept Two Numbers and Calculate Addition, Multiplication, Subtraction, and Division

📑 On this page:
  • The four operations and what they do
  • Designing the four-operation program
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to read two values and apply all four basic arithmetic operators
  • How to store intermediate results in named variables for clarity
  • How to print four results in a clear, tabular layout
  • How to guard against division by zero
  • Why the order of operations (precedence) matters when combined
  • How to extend this to a mini-calculator using switch

The four operations and what they do

The four basic arithmetic operations are the foundation of every calculator, spreadsheet, and financial application. In C, each is a single operator:

  • Addition (+) — combines two values. 7 + 2 = 9.
  • Subtraction (−) — finds the difference. 7 − 2 = 5.
  • Multiplication (*) — repeated addition. 7 * 2 = 14.
  • Division (/) — splits into equal groups. 7 / 2 = 3.5 (with doubles) or 3 (with integers).

Each operator is binary — it takes two operands — and produces a result. The result type follows the operands: two int operands give an int; two double operands give a double. Mixing types promotes the narrower operand to the wider type, so int + double = double.

Division is the only one with a special case: division by zero. In mathematics, x / 0 is undefined. In C, integer division by zero is undefined behavior (usually a crash with SIGFPE); floating-point division by zero gives infinity or NaN on IEEE 754 systems. Both are problems, so the program should check for a zero divisor before dividing.

The assignment is a complete calculator for two operands. It should read a and b, compute a + b, a - b, a * b, and a / b, and print all four. That's the minimal version. A more polished version handles division by zero, aligns the output nicely, and maybe loops so the user can keep going. But the core is simple — four operators, one program.

💡 In one line: read a and b, compute a+b, a-b, a*b, and a/b, print each — but check b != 0 before dividing.

Two boxes labelled a and b feeding into four operation symbols (+, −, ×, ÷), with the results displayed beside each.

Designing the four-operation program

Here are the key design decisions:

Decision Choice Reason
Variable typedoublePreserves fractional results from division and supports fractional inputs.
Number of variablesa, b, sum, diff, prod, quotNaming each result makes the output clearer and the code easier to follow.
Division guardif (b != 0)Prevents undefined behavior; prints an error instead.
Output format%.2lf, aligned labelsConsistent decimal places, easy to compare.

Why store results in named variables? You could inline each computation in the printf — printf("Sum = %.2lf\n", a + b) — and that would work. But naming the variables has two benefits: it makes the output clearer (each label matches a variable name), and it allows you to inspect or reuse the results later without recomputing them. For a program with only four outputs, either style works; for a larger program, named variables are usually better.

The division guard is essential. The formula quot = a / b; is undefined when b == 0, so the program should test b != 0 before dividing. If b is zero, print an error message instead.

🎯 Key idea: even a program this simple has two non-obvious concerns — choosing the right type (double, not int) and handling division by zero. Address both, and the program is correct. Skip either, and it might pass casual tests but fail on edge cases.

Complete C Programs

Here is the complete program with named variables and division-by-zero handling:

Program: four operations with named results

#include <stdio.h>

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

    printf("Enter first number:  ");
    scanf("%lf", &a);
    printf("Enter second number: ");
    scanf("%lf", &b);

    sum  = a + b;
    diff = a - b;
    prod = a * b;

    printf("\n--- Results ---\n");
    printf("Addition:       %.2lf + %.2lf = %.2lf\n", a, b, sum);
    printf("Subtraction:    %.2lf - %.2lf = %.2lf\n", a, b, diff);
    printf("Multiplication: %.2lf * %.2lf = %.2lf\n", a, b, prod);

    if (b != 0.0) {
        quot = a / b;
        printf("Division:       %.2lf / %.2lf = %.4lf\n", a, b, quot);
    } else {
        printf("Division:       %.2lf / %.2lf is undefined (division by zero)\n", a, b);
    }

    return 0;
}
                                    

Each line of output shows the full expression — "7.50 + 2.00 = 9.50" — which makes it easy to verify each result by hand. The division is printed with four decimal places (%.4lf) instead of two, because division often produces more decimals than the other operations and showing them is more informative.

And here's a compact version that computes each result inline, without intermediate variables:

Variant: compact, inline computation

#include <stdio.h>

int main(void) {
    double a, b;

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

    printf("a + b = %.2lf\n", a + b);
    printf("a - b = %.2lf\n", a - b);
    printf("a * b = %.2lf\n", a * b);
    if (b != 0.0)
        printf("a / b = %.4lf\n", a / b);
    else
        printf("a / b = undefined (division by zero)\n");

    return 0;
}
                                    

Both versions produce identical results. The compact version is shorter; the named-variable version is easier to extend (e.g., to add a division result, print the intermediate values, or feed one result into another calculation). Choose based on context — for a quick demo, inline; for anything you'll build on, named.

And here's a version that runs the four operations in a loop, so the user can keep computing:

Variant: loop until the user quits

#include <stdio.h>

int main(void) {
    double a, b;
    char again;

    do {
        printf("\nEnter two numbers: ");
        if (scanf("%lf %lf", &a, &b) != 2) break;

        printf("a + b = %.2lf\n", a + b);
        printf("a - b = %.2lf\n", a - b);
        printf("a * b = %.2lf\n", a * b);
        if (b != 0.0)
            printf("a / b = %.4lf\n", a / b);
        else
            printf("a / b = undefined\n");

        printf("Continue? (y/n): ");
        scanf(" %c", &again);
    } while (again == 'y' || again == 'Y');

    return 0;
}
                                    

The do...while loop runs the body at least once, then checks the condition. The user is prompted after each calculation to continue (y) or quit (any other key). The " %c" format string has a leading space — this skips any leading whitespace (including the newline left over from the previous scanf), which is essential when reading a single character after a numeric input. Without the space, the scanf would read the leftover newline as the answer and exit the loop immediately.

Program Output

Here is typical output from the first program:

Enter first number:  7.5
Enter second number: 2.0

--- Results ---
Addition:       7.50 + 2.00 = 9.50
Subtraction:    7.50 - 2.00 = 5.50
Multiplication: 7.50 * 2.00 = 15.00
Division:       7.50 / 2.00 = 3.7500
                                

Check: 7.5 + 2 = 9.5, 7.5 − 2 = 5.5, 7.5 × 2 = 15, 7.5 ÷ 2 = 3.75. All correct.

For division by zero:

Enter first number:  10
Enter second number: 0

--- Results ---
Addition:       10.00 + 0.00 = 10.00
Subtraction:    10.00 - 0.00 = 10.00
Multiplication: 10.00 * 0.00 = 0.00
Division:       10.00 / 0.00 is undefined (division by zero)
                                

The program computes the first three normally and prints the division message without crashing. This is the behavior we want — safe and informative.

For negative numbers:

Enter first number:  -15
Enter second number: 4

--- Results ---
Addition:       -15.00 + 4.00 = -11.00
Subtraction:    -15.00 - 4.00 = -19.00
Multiplication: -15.00 * 4.00 = -60.00
Division:       -15.00 / 4.00 = -3.7500
                                

All operations handle negatives correctly. Check: -15 + 4 = -11, -15 − 4 = -19, -15 × 4 = -60, -15 ÷ 4 = -3.75. Correct.

And the loop version:

Enter two numbers: 12 5
a + b = 17.00
a - b = 7.00
a * b = 60.00
a / b = 2.4000
Continue? (y/n): y

Enter two numbers: 8 0
a + b = 8.00
a - b = 8.00
a * b = 0.00
a / b = undefined
Continue? (y/n): n
                                

The loop handles both a normal case and a division-by-zero case, and exits cleanly when the user types "n".

🔍 Try this: modify the program to accept only integers and change double to int, %lf to %d, %.2lf to %d. Run with 7 and 2. Notice that the division now gives 3, not 3.5 — integer division truncates. That's the type sensitivity in action. Then try with -7 and 2 — the division gives -3, not -4, because C truncates toward zero (not toward negative infinity).

Step-by-Step Explanation

Let's walk through the named-variable version — the most instructive of the three.

1. Declarations

double a, b; — the two operands. Both double because we want fractional inputs and fractional results. double sum, diff, prod, quot; — four intermediate variables for the four results. Naming them makes the code self-documenting: sum holds the sum, diff holds the difference, and so on.

2. Reading the inputs

Two separate prompts and two separate reads, one for each operand. This is more user-friendly than a combined prompt because the user knows exactly which number they're typing at each moment. The %lf specifier matches double, and the & passes the address so scanf can write into the variable.

3. The three unconditionally-safe operations

sum = a + b;, diff = a - b;, prod = a * b; — addition, subtraction, and multiplication are always safe (well, unless they overflow, but double's range is huge). Each assigns the result to its named variable. Since all operands are double, all arithmetic is in double precision — no truncation, no integer division surprises.

4. The division guard

if (b != 0.0) — checks that the divisor is non-zero before dividing. If b == 0, division is undefined, so we print an error message instead. Note the use of 0.0 (not 0) — comparing a double to an int literal is fine, but 0.0 makes the intent clear.

Strictly speaking, comparing floating-point values with != can be problematic because of rounding error. But here, b comes directly from user input, and 0.0 is exactly representable in IEEE 754 — so the comparison is exact. If b were the result of some calculation, we'd want a tolerance (e.g., if (fabs(b) < 1e-9)), but for direct user input, the simple comparison works.

5. The four printf lines

Each line prints the full expression: "Addition: %.2lf + %.2lf = %.2lf\n", a, b, sum. This shows the operands and the result, making each line self-contained and easy to verify.

The three arithmetic lines use %.2lf (two decimals), while the division line uses %.4lf (four decimals). Why the difference? Division often produces more decimals than the other operations, and truncating to two might hide interesting precision. For example, 10 / 3 = 3.3333... — two decimals give 3.33, four give 3.3333. The extra precision is more informative for division.

You could use the same precision for all four — either two or four — for consistency. The choice is aesthetic; what matters is being deliberate.

6. Why the division is inside the if-else

The division quot = a / b; only happens if b != 0.0. This is because the computation itself would be undefined if b were zero. The printf for the division result is also inside the if-branch, because we only want to print the division if it succeeded. If b == 0, the else-branch prints an error message instead.

An alternative would be to set quot to a sentinel value (like NAN from <math.h>) and print it anyway. But a clear error message is friendlier than "NaN" (which most users wouldn't understand).

7. Operator precedence

In this program, each operation is a separate statement, so there's no precedence conflict. But if you combined them — e.g., a + b * c — precedence would matter: * has higher precedence than +, so it would parse as a + (b * c), not (a + b) * c. Use parentheses to make precedence explicit when in doubt.

Precedence (highest to lowest): * / %, then + -, then comparisons, then logical operators. When mixing, parenthesize to avoid surprises.

8. Associativity

Operators with the same precedence associate left to right. So a - b - c means (a - b) - c, not a - (b - c). For addition and multiplication, this doesn't matter (both are associative), but for subtraction and division it does. 10 - 3 - 2 = 5 (not 9), and 20 / 4 / 5 = 1 (not 25). Always be explicit with parentheses when combining same-precedence subtraction or division.

9. The loop version's newline gotcha

The loop version has one subtlety: scanf(" %c", &again) with a leading space. Without the space, scanf would read the newline character left over from the previous scanf and treat it as the answer to "Continue?" — so the loop would exit after the first iteration regardless of what the user typed. The space in the format string tells scanf to skip whitespace before reading the character, so it reads the actual letter the user typed.

This is one of the most common gotchas in C's input handling. The pattern " %c" (space before the percent) is a standard idiom for reading a single character after other input. Remember it.

10. Extending to a real calculator

The natural next step is a menu-driven calculator that asks which operation to perform:

int choice;
printf("1. Add  2. Subtract  3. Multiply  4. Divide\n");
scanf("%d", &choice);
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);

switch (choice) {
    case 1: printf("%.2lf\n", a + b); break;
    case 2: printf("%.2lf\n", a - b); break;
    case 3: printf("%.2lf\n", a * b); break;
    case 4: if (b != 0) printf("%.2lf\n", a / b);
            else printf("Error: division by zero\n");
            break;
    default: printf("Invalid choice\n");
}
                                

This is the classic "switch case calculator" — a common beginner exercise that combines input, arithmetic, and conditional logic. It's a natural follow-up to this assignment.

🎯 Key idea: the four basic operations are simple, but writing a correct program that uses them requires attention to types (double vs. int), division by zero, and output formatting. Master these small concerns now, and the larger programs you write later will be correct by construction.

Frequently Asked Questions

1. Why use double instead of int for the operands?

Because the user can enter fractional values (e.g., 7.5), and even whole-number inputs produce fractional results from division (e.g., 7 / 2 = 3.5). int would truncate both the inputs and the division result, silently producing wrong answers. double preserves fractional precision and matches the expected behavior of a calculator.

2. What happens if I don't guard against division by zero?

For double, IEEE 754 systems (Linux, macOS, Windows) return infinity or NaN, and the program continues — printing "inf" or "nan" instead of a number. For int, most systems crash with SIGFPE, terminating the program. Both behaviors are undesirable; a graceful error message is better than a cryptic "inf" or a crash. Guard against b == 0 before dividing.

3. Why does the division line use %.4lf instead of %.2lf?

For more precision. Division often produces more decimals than the other operations. For example, 10 / 3 = 3.3333... — two decimals give 3.33, four give 3.3333. The extra precision is useful for comparison and verification. It's a stylistic choice — you could use two for all four operations if you prefer consistency, but showing more decimals for division highlights its different nature.

4. What's the leading space in scanf(" %c", &again) for?

It skips leading whitespace before reading the character. Without the space, scanf would read the newline character left over from the previous numeric input and interpret it as the user's answer — causing the loop to exit prematurely. The space is a standard idiom for reading a single character after other input. Remember it whenever you mix %d or %lf with %c in the same program.

5. Can I use this program for more than two numbers?

Yes, but you'd need a more general design. For two numbers, the four operations are hardcoded. For three or more, you'd read them into an array and loop over combinations, or implement a stack-based calculator (like the HP-15C). The simplest extension is to add a third number c and compute a+b+c, etc., but the formula for division becomes ambiguous ("a/b/c" could be (a/b)/c or a/(b/c)). A proper solution requires thinking about what the user wants.

6. What if the user enters very large or very small numbers?

double has an enormous range — up to about 10308 — so virtually any real-world input is fine. Very small values (close to zero) can lose precision relative to the value's magnitude, but this rarely matters in practice. If the input exceeds double's range, it becomes infinity (or undefined behavior); if it's smaller than double's smallest positive value, it becomes zero. For a simple calculator, neither case is a concern; for numerical computing, you'd check input ranges carefully.

💡 Tip: once this works, extend it into the classic "menu-driven calculator" with switch (shown in the explanation). Then try making it interactive with a loop, and add a "history" that remembers the last few results. Each enhancement teaches a new C concept (switch, loops, arrays, functions) without losing sight of the simple core — read, compute, print.

📖 Related Tutorials

  • Previous: Perform Basic Arithmetic Operations on Various Data Types
  • Next: Input User Name and Age and Display Them
  • Arithmetic Operators in C
  • Operators and Expressions
  • Basic Input/Output Statements
  • Built-in Data Types in C
  • All 13 Introduction to C Assignments

Previous Topic: -->> 10. Perform Basic Arithmetic Operations on Various Data Types   ||   Next Topic: -->> 12. Input User Name and Age and Display Them


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.