Operators Assignment 1 — Add Two Numbers Using the '+' Operator
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Add Two Numbers Using the '+' Operator

📑 On this page:
  • The addition operator
  • How types affect the sum
  • Complete C Programs
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to declare and initialize integer and floating-point variables
  • How to read input from the user with scanf
  • How the + operator computes the sum of two operands
  • How integer addition differs from floating-point addition
  • How to print output with printf using the correct format specifiers
  • What happens on overflow and how to avoid it

The addition operator

The addition operator + is the first arithmetic operator every C programmer learns. It takes two operands and produces their sum. The operator itself is simple, but the behavior of the operator depends entirely on the types of its operands. Two int operands produce an int sum. Two double operands produce a double sum. A mixed pair (one int, one double) promotes the integer to a double and produces a double sum.

The + operator is binary — it takes exactly two operands. It's also left-associative: in an expression like a + b + c, the operations are grouped as (a + b) + c, evaluated left to right. This doesn't usually matter for addition (since it's commutative and associative over integers), but it can matter for floating-point precision — (a + b) + c and a + (b + c) might differ in the last decimal place due to rounding.

For integers, addition is exact within the type's range. For int (typically 32 bits), the range is approximately ±2.1 billion. Beyond that, integer addition overflows — undefined behavior in the C standard, wraparound in practice on two's-complement hardware. For floating-point, addition is almost exact within the type's precision (about 15 decimal digits for double), but values can be rounded when the exact sum needs more bits than the type provides.

💡 In one line: a + b gives an int if both operands are int, and a double if either is double. Pick types based on the range and precision you need.

Addition of two numbers in C — reading two integers with scanf, adding them with the + operator, and printing the sum with printf.

How types affect the sum

The type of the sum follows the "usual arithmetic conversions": if either operand is a floating-point type, the other operand is promoted to that type, and the result is that type. If both operands are integers, they're promoted to a common integer type (typically int), and the result is that integer type.

In practice:

  • int + int → int — exact within the integer range, wraps on overflow.
  • double + double → double — exact within precision, rounds or becomes inf on overflow.
  • int + double → double — the int is promoted to double, then double addition applies.
  • float + double → double — the float is promoted to double (float has less precision).

What about the sign? Mixed signs work naturally — 5 + (−3) = 2, (−5) + 3 = −2. No special handling needed. The result is the mathematical sum, as long as it doesn't overflow.

Overflow is the one tricky case. For int, adding two large positive values can overflow to a negative result. For double, adding two very large values can overflow to infinity (represented as inf in printf). Both are undefined behavior in the C standard, though the practical behavior on most systems is wraparound for ints and inf for doubles. To handle large values safely, use long long for integers (range ±9.2 quintillion) or check for overflow before adding.

Complete C Programs

Here is the simplest version — adding two integers:

Program 1: Add two integers

#include <stdio.h>

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

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

    sum = a + b;

    printf("Sum = %d\n", sum);

    return 0;
}
                                

That's it — declare, read, add, print. The + operator does all the arithmetic. The two format specifiers in scanf (%d %d) read two decimal integers, and the format specifier in printf (%d) prints the result as a decimal integer.

Here's a variant that handles floating-point numbers, useful when the inputs might have fractional parts:

Program 2: Add two doubles

#include <stdio.h>

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

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

    sum = a + b;

    printf("Sum = %.2lf\n", sum);

    return 0;
}
                                

The only differences are the types (double instead of int), the format specifiers (%lf for reading, %.2lf for printing with two decimals), and the fact that the sum preserves fractional parts. For 3.5 + 2.5, the first program would give an error (or truncate the inputs to 3 and 2), while the second gives 6.00.

A third variant — for maximum flexibility — combines both. It reads two values as double, so integer inputs are automatically converted:

Program 3: Accept both integers and decimals

#include <stdio.h>

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

    printf("Enter two numbers (integers or decimals): ");
    if (scanf("%lf %lf", &a, &b) != 2) {
        printf("Error: invalid input.\n");
        return 1;
    }

    sum = a + b;

    /* Print as integer if the sum is whole, else as double */
    if (sum == (int)sum) {
        printf("Sum = %d\n", (int)sum);
    } else {
        printf("Sum = %.2lf\n", sum);
    }

    return 0;
}
                                

This version's extra logic is a nice touch: it prints Sum = 7 for 3 + 4, and Sum = 7.50 for 3.5 + 4.0. The check sum == (int)sum determines whether the sum is a whole number by comparing the double to its integer truncation. If they're equal, the sum has no fractional part, so printing it as an integer is fine (and looks cleaner).

All three programs are valid. Program 1 is the canonical answer for exercises that specify "two integers." Program 2 is the right answer for more general "two numbers." Program 3 is a nice middle ground that shows how to unify the two cases without duplicate code. In an interview or assignment, Program 1 is the safest answer for "add two integers" — don't overthink it.

Program Output

Here's a sample run of Program 1:

Enter two integers: 5 7
Sum = 12
                            

The user types 5 7, and the program prints Sum = 12. The math is 5 + 7 = 12, which the + operator computes internally.

And here's Program 2 with decimal inputs:

Enter two numbers: 3.5 2.5
Sum = 6.00
                            

Note the .00 in the output — the result is exact (3.5 + 2.5 = 6.0), but formatted with two decimal places because of %.2lf. If you used %lf alone, you'd see 6.000000 (six decimals). If you used %.0lf, you'd see 6. Formatting is entirely under your control via the format specifier.

What about mixing types? Here's the third program with 3 and 4:

Enter two numbers (integers or decimals): 3 4
Sum = 7
                            

Since the sum (7.0) has no fractional part, it's printed as 7. And with 3.5 and 4:

Enter two numbers (integers or decimals): 3.5 4
Sum = 7.50
                            

The sum has a fractional part, so it's printed with two decimals. The same program handles both cases.

Edge case — overflow with large integers:

Enter two integers: 2147483647 1
Sum = -2147483648
                            

Wait — 2147483647 + 1 should be 2147483648, but the program prints −2147483648. That's integer overflow: INT_MAX (2147483647) plus 1 wraps around to INT_MIN (−2147483648) on two's-complement systems. On other systems, behavior may differ (or the program could even crash). Overflow of signed integers is undefined behavior in C — the result isn't guaranteed to be wraparound. This is a real problem for financial code, embedded systems, and anything that handles large values. Use long long (range ±9.2 quintillion) if you expect large inputs.

🔍 Try this: run Program 1 with 5 7, 0 0, -3 8, and 2147483647 1. The first three should print 12, 0, and 5. The last one shows the wraparound behavior (or a crash, depending on the system). Then try the same inputs with Program 2 — you'll get exact results even for very large values (up to double's range, about 10308).

Step-by-Step Explanation

Let's walk through Program 1 line by line.

1. #include <stdio.h>

Includes the standard I/O library, which provides printf and scanf. Without this line, the compiler wouldn't know what printf means — you'd get a "function undeclared" error (or a warning, in older C dialects).

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

The entry point of the program. The void in parentheses means main takes no arguments (it doesn't read from the command line). The int before main means main returns an integer to the operating system — 0 for success, nonzero for failure. Modern C compilers expect this signature.

3. int a, b, sum;

Declares three integer variables. a and b hold the inputs, sum holds the result. All three are uninitialized — they contain garbage until assigned. If you read them before assigning, you'd get undefined values. The program assigns them via scanf (for a and b) and the assignment statement (for sum), so they're safely initialized before use.

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

Prints a prompt, telling the user to enter two integers. The trailing space after the colon is aesthetic — it separates the prompt from the user's typed input, which scanf reads from the same line. Without the prompt, the program would just sit there, waiting for input, and the user might not know what to do.

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

Reads two integers from standard input. The format string "%d %d" specifies two decimal integers separated by whitespace. The & before each variable name takes the address of that variable, so scanf knows where to store the result. Without &, scanf would receive the garbage value of the uninitialized variable — and writing to that address would crash the program. This is the classic beginner mistake: forgetting &.

The return value of scanf is the number of successful conversions. For two integers, scanf returns 2 on success, 1 if only the first conversion succeeded, 0 if neither did, or EOF on end-of-input. Robust code checks the return value: if (scanf("%d %d", &a, &b) != 2) { /* handle error */ }. In simple programs, this is skipped, but it's worth knowing.

6. sum = a + b;

The heart of the program. a + b computes the arithmetic sum of the two integers. The = is assignment (not equality) — it stores the result in the sum variable. After this line, sum holds the sum, and a and b are unchanged.

Both operands are int, so the addition is integer addition. The result is exact if no overflow occurs. For a = 5 and b = 7, sum = 12. For a = -3 and b = 8, sum = 5. Signs work naturally.

7. printf("Sum = %d\n", sum);

Prints the result. The %d is a format specifier — it says "print an integer in decimal." The \n moves to the next line. The sum is passed by value to printf; printf substitutes %d with the decimal representation of the value.

If sum = 12, the output is Sum = 12\n. If sum = -5, the output is Sum = -5\n. The format specifier handles the sign, the digits, everything. You don't need to convert to a string manually.

8. return 0;

Exits main and returns 0 to the operating system. 0 conventionally means "success." Nonzero values mean errors — for example, if the program failed to read its inputs, it could return 1. Most simple programs return 0 unconditionally.

9. Reading doubles — what changes in Program 2

In Program 2, the declarations change to double a, b, sum;, the format string in scanf changes to "%lf %lf", and the format in printf changes to "%.2lf". Everything else is identical. This is the beauty of C's design — the same operator +, the same assignment, the same printf, just different types.

%lf in scanf means "read a double" (the l modifier makes it long, which for float/double means double). %lf in printf also prints doubles, though technically %f works for both float and double in printf (because of default argument promotions, float is promoted to double when passed to variadic functions). Using %lf in printf is legal but unnecessary — %f is more idiomatic.

The %.2lf means "print a double with 2 decimal places." For 6.0, this prints 6.00. For 6.123, this prints 6.12 (truncation, not rounding — wait, actually printf rounds, so 6.126 → 6.13). This is worth knowing for financial output, where precision matters.

10. Reading mixed input

What if the user enters 3.5 4 for Program 1? The scanf("%d %d", ...) would read 3 from the "3.5", stop at the '.', fail to read a second integer (because the input stream now has ".5 4"), and possibly return 1 (only one conversion succeeded). sum would be assigned a garbage value or left unchanged.

This is why you must match the format specifier to the input type. If the input might be 3.5, use %lf and declare double. If the input is guaranteed to be an integer, use %d and declare int. A mismatch causes silent truncation or garbage values — the program doesn't usually crash, which makes the bug harder to find.

Program 3 handles this gracefully: it reads everything as double, so integer inputs are automatically promoted. There's no mismatch, and no need to choose format specifiers based on input type.

11. The scanf return value

scanf returns the number of variables it successfully filled. For "%d %d", it returns 2 on full success, 1 if only one integer could be read, 0 if none (e.g., the user typed a letter), or EOF if the input stream is exhausted. Robust programs check this:

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

This catches invalid input early, rather than proceeding with garbage values. For simple exercises, it's often skipped, but for production code, it's essential.

12. Extending the program

The natural extension is to add more operations: subtraction, multiplication, division. A mini calculator reads two numbers and an operator, then computes the result:

printf("Enter: a op b > ");
scanf("%lf %c %lf", &a, &op, &b);
switch (op) {
  case '+': printf("%lf\n", a + b); break;
  case '-': printf("%lf\n", a - b); break;
  ...
}

That combines scanf, switch, and all four arithmetic operators in one program. It's the classic "second program" after "add two numbers" — the natural next step. Assignment 2 (subtraction) and Assignment 3 (multiplication) build on the same skeleton, so you'll see the pattern quickly.

🎯 Key idea: the + operator computes the sum of its two operands, and the type of the result depends on the operand types. Two ints give an int; two doubles give a double; mixed gives a double. Integer overflow is undefined behavior — use larger types (long long, double) or check for overflow before adding.

Frequently Asked Questions

1. Why does my program print a garbage value instead of the sum?

Most likely you forgot the & in scanf("%d %d", &a, &b). Without &, scanf receives the uninitialized value of a (or b) and tries to write to that address — undefined behavior, often a crash or silent corruption. The second possibility: your format specifier doesn't match the type (e.g., %f for int), which also gives garbage. Always match specifier to type and always use & in scanf.

2. What happens if the sum overflows?

For int, overflow is undefined behavior. On two's-complement systems, the value wraps around: INT_MAX + 1 = INT_MIN. On some systems or with aggressive optimization, the compiler may produce a completely wrong value. For double, overflow produces inf (infinity). To handle large values, use long long (range ±9.2 quintillion) or check for overflow before adding: if (a > 0 && b > INT_MAX - a) { /* overflow */ }. In simple exercises, overflow is rare; in real code, it matters.

3. Can I add more than two numbers?

Yes — just chain the + operator: sum = a + b + c + d; C evaluates left to right: ((a + b) + c) + d. For int, this is exact (unless intermediate sums overflow). For double, floating-point rounding may cause tiny differences depending on the order of operations — (a + b) + (c + d) and ((a + b) + c) + d might differ in the last decimal place. For most use cases, this doesn't matter.

4. Why use double instead of float?

Because double has about twice the precision of float (15 decimal digits vs. 7), and the same range (approximately ±10308 vs. ±1038 — actually double has a much larger range too). Modern CPUs perform double arithmetic at essentially the same speed as float, so there's no performance reason to prefer float. The only reason to use float is to save memory (4 bytes vs. 8 bytes per value) — for example, in arrays of millions of elements. For a single sum, double is the safer choice.

5. Why do I need #include <stdio.h>?

Because printf and scanf are declared there. Without the include, the compiler doesn't know what printf means — it would either produce a warning (older C dialects) or an error (C99 and later). Some compilers implicitly declare functions with an assumed return type, but this is fragile and non-standard. Always include the right header.

6. Can the user enter a negative number?

Yes — scanf("%d", &a) reads a signed integer, which includes negatives. For example, entering -5 7 gives a = -5, b = 7, sum = 2. The + operator handles signs naturally, since signed arithmetic is what it does. No special handling is needed. Note that the minus sign must be part of the input string — the user types -5, not - 5.

💡 Tip: once this works, extend it to a mini calculator that asks the user which operation to perform (+, -, *, /), then reads two numbers and prints the result. You'll need a switch statement or an if/else chain. That's the natural next exercise — a real calculator, not just a one-off demo.

📖 Related Tutorials

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

Previous Topic: -->> Introduction to C — All Assignments   ||   Next Topic: -->> 2. Subtract 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.