C Addition Guide: Basics, Advanced Tips & Error Handling

目次

1. Introduction

What is addition in C? A beginner-friendly explanation [From basics to advanced]

In C, addition is one of the most fundamental operations. You can use the “+” operator to add numbers, but its behavior can vary depending on data types and input methods. Among those who have started learning C,
  • “I don’t know how to write addition in C”
  • “I want to know how to calculate using variables”
  • “I want to create a program that sums multiple numbers” Many people have such questions.
In this article, we will explain addition in C from fundamentals to advanced topics in a way that’s easy for beginners to understand. If you want to see code examples right away, please refer to the next section, “2. How to write addition in C [A complete beginner’s guide]”.

2. How to Write Addition in C (Complete Beginner’s Guide)

Basics of the ‘+’ Operator in C

C in addition uses the arithmetic operator ‘+’. It is the basic operator for adding two numbers.

Integer Addition

#include <stdio.h>

int main(void) {
    int a = 10, b = 5;
    int sum = a + b;
    printf("Sum: %d\n", sum);
    return 0;
}
Output
Sum: 15

Cumulative Calculation Using ‘+=’

C provides a shorthand notation for the ‘+’ operator called the ‘+=’ operator. It can be used to add another value to the current variable.
int a = 5;
a += 3; // a becomes 8
The above code is equivalent to writing it as follows.
int a = 5;
a = a + 3; // add 3 to a
Using += improves code readability and allows concise expression.

Behavior of Addition with Negative Numbers and Zero

In C, addition involving negative numbers or zero works without issues.
#include <stdio.h>

int main(void) {
    int a = -5, b = 3;
    int sum = a + b;
    printf("Sum: %d\n", sum);
    return 0;
}
Output
Sum: -2
Also, addition with zero operates normally.
int a = 10;
int sum = a + 0; // result is 10
Without any special handling, C’s addition can handle calculations involving negative numbers and zero.

3. Adding with Variables and User Input

Adding Using C Variables [Using scanf]

In C, you can receive input from the user and perform calculations. To do this, you use the standard input function scanf. The following program prompts the user to enter two numbers and adds them.
#include <stdio.h>

int main(void) {
    int num1, num2, sum;
    printf("Please enter the first integer: ");
    scanf("%d", &num1);
    printf("Please enter the second integer: ");
    scanf("%d", &num2);
    sum = num1 + num2;
    printf("Total: %dn", sum);
    return 0;
}
Example Output
Please enter the first integer: 7
Please enter the second integer: 3
Total: 10

How to Avoid Input Errors

When using scanf, it is important to consider input errors. For example, if the user enters characters instead of numbers, the program may behave unexpectedly. To prevent this, you can check the return value of scanf to verify whether the input was successful.
#include <stdio.h>

int main(void) {
    int num;
    printf("Please enter an integer: ");

    if (scanf("%d", &num) !=) {
        printf("Input error: Please enter an integer.n");
        return 1; // Return an error code and exit
    }

    printf("Entered integer: %dn", num);
    return 0;
}
This program checks the return value of scanf and, if an integer is not entered, displays an error message and exits.

while Loop Re-prompting

If the user provides incorrect input, adding a mechanism to prompt for re-entry makes the program safer.
#include <stdio.h>

int main(void) {
    int num;
    while (1) { // Request input in an infinite loop
        printf("Please enter an integer: ");
        if (scanf("%d", &num) == 1) {
            break; // Exit the loop when input is correct
        } else {
            printf("Error: Please enter an integer.n");
            while (getchar() != 'n'); // Clear the buffer
        }
    }

    printf("Entered integer: %dn", num);
    return 0;
}
With this method, the program does not terminate even if the input is incorrect; it repeatedly prompts until a correct value is entered, making it user-friendly.

4. Three Common Errors in C Language Addition and Their Solutions (Beginner Friendly)

When performing addition in C, beginners often encounter the following errors.
  1. User input errors (mistakes with scanf)
  2. Overflow (variable value exceeds its range)
  3. Data type mismatch (integer and floating-point calculation errors)
In this section, we will explain the causes and solutions for these errors in detail.

4-1. How to Prevent Input Errors with scanf

Cause of the Error

When using scanf to receive input from the user, there is a possibility that the program will crash if unexpected data (such as strings) is entered.
#include <stdio.h>

int main(void) {
    int num;
    printf("Please enter an integer: ");
    scanf("%d", &num); // entering non-numeric input makes behavior unstable
    printf("Entered integer: %dn", num);
    return 0;
}
Example of Unexpected Input
Please enter an integer: abc
(the program behaves unexpectedly)

Solution 1: Check the Return Value of scanf

#include <stdio.h>

int main(void) {
    int num;
    printf("Please enter an integer: ");

    if (scanf("%d", &num) != 1) {
        printf("Input error: please enter an integer.\n");
        return 1; // return error code and exit
    }

    printf("Entered integer: %dn", num);
    return 0;
}

Solution 2: Re-prompt Using a while Loop

#include <stdio.h>

int main(void) {
    int num;
    while (1) { // request input in an infinite loop
        printf("Please enter an integer: ");
        if (scanf("%d", &num) == 1) {
            break; // exit loop when input is correct
        } else {
            printf("Error: please enter an integer.\n");
            while (getchar() != 'n'); // clear buffer
        }
    }

    printf("Entered integer: %dn", num);
    return 0;
}

4-2. Overflow Errors Occurring in Addition

Cause of the Error

In C, integer types (such as int and long) have upper and lower limits on the values they can store. If a calculation exceeds the maximum value, unexpected behavior (overflow) occurs.
#include <stdio.h>
#include <limits.h> // needed to use INT_MAX

int main(void) {
    int a = INT_MAX, b = 1;
    int sum = a + b; // overflow occurs here
    printf("Sum: %dn", sum);
    return 0;
}

Solution: Use long long Type

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

int main(void) {
    long long a = LLONG_MAX, b = 1;
    long long sum = a + b;
    printf("Sum: %lldn", sum);
    return 0;
}

4-3. Calculation Errors Due to Data Type Mismatch

Cause of the Error

In C, mixing integer types (int) with floating-point types (float or double) in calculations can produce unintended results due to type conversion.
#include <stdio.h>

int main(void) {
    int a = 5;
    double b = 2.5;
    int sum = a + b; // assigned to int

    printf("Sum: %dn", sum);
    return 0;
}
Output
Sum: 7

Solution: Unify Data Types

#include <stdio.h>

int main(void) {
    double a = 5.0;
    double b = 2.5;
    double sum = a + b; // calculate with double

    printf("Sum: %.2f\n", sum);
    return 0;
}
Output
Sum: 7.50

5. Adding Floating-Point Numbers and How to Avoid Errors

In C, you can work with not only integers (int) but also floating-point numbers (float and double). However, adding floating-point numbers can introduce errors, so you need to be careful.

5-1. Adding Floating-Point Numbers in C (float / double)

Basic Addition with Decimals

#include <stdio.h>

int main(void) {
    double a = 1.2, b = 2.3;
    double sum = a + b;
    printf("Sum: %.2f\n", sum);
    return 0;
}
Output
Sum: 3.50

5-2. The Issue Where 0.1 + 0.2 Does Not Equal 0.3

Running the following program may result in unexpected results.
#include <stdio.h>

int main(void) {
    double a = 0.1, b = 0.2;
    double sum = a + b;
    printf("Sum: %.17f\n", sum);
    return 0;
}
Output
Sum: 0.30000000000000004

Cause: Errors Due to Internal Representation of Floating-Point Numbers

In C, float and double represent fractions in binary, so 0.1 and 0.2 cannot be represented exactly.
0.1 (decimal) = 0.000110011001100... (binary)
0.2 (decimal) = 0.00110011001100... (binary)
Therefore, a tiny error occurs when calculating 0.1 + 0.2.

5-3. Ways to Avoid Floating-Point Errors

① Rounding Errors with the round() Function

#include <stdio.h>
#include <math.h> // needed to use round function

int main(void) {
    double a = 0.1, b = 0.2;
    double sum = round((a + b) * 100) / 100; // round to two decimal places
    printf("Sum: %.2f\n", sum);
    return 0;
}

② Convert to Integers for Calculation

#include <stdio.h>

int main(void) {
    int a = 10, b = 20; // convert decimal to integer (multiply by 100)
    int sum = a + b;
    printf("Sum: %.2f\n", sum / 100.0); // convert back to original scale
    return 0;
}

③ Use long double

#include <stdio.h>

int main(void) {
    long double a = 0.1L, b = 0.2L;
    long double sum = a + b;
    printf("Sum: %.20Lf\n", sum);
    return 0;
}

6. How to Add Multiple Numbers (Using Loops)

In C, using loops as a method to add multiple numbers is common. For example, loops are useful for summing multiple numbers stored in an array or for adding numbers entered by the user.

6-1. for Adding Multiple Numbers Using a Loop

Summing Multiple Numbers Using an Array

#include <stdio.h>

int main(void) {
    int numbers[] = {10, 20, 30, 40, 50}; // Store five numbers in the array
    int sum = 0;
    int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of elements in the array

    for (int i = 0; i < size; i++) {
        sum += numbers[i]; // Add each element of the array
    }

    printf("Total: %d\n", sum);
    return 0;
}
Output
Total: 150

6-2. while Summing Numbers Using a Loop

Summing Arbitrary Numbers from User Input

#include <stdio.h>

int main(void) {
    int num, sum = 0;

    printf("Please enter a number (enter 0 to finish): ");

    while (1) { // Infinite loop
        scanf("%d", &num);
        if (num == 0) {
            break; // Exit loop when 0 is entered
        }
        sum += num;
    }

    printf("Total: %d\n", sum);
    return 0;
}
Output
Please enter a number (enter 0 to finish): 5
10
3
0
Total: 18

6-3. do-while Summing Numbers Using a Loop

do-while loop has the characteristic that the body is guaranteed to execute at least once.
#include <stdio.h>

int main(void) {
    int num, sum = 0;

    printf("Please enter a number (enter 0 to finish): ");

    do {
        scanf("%d", &num);
        sum += num; // 0 is also added when entered, but will be corrected later
    } while (num != 0); // Repeat until 0 is entered

    sum -= num; // Subtract 0 to correct
    printf("Total: %d\n", sum);
    return 0;
}
Output
Please enter a number (enter 0 to finish): 4
6
2
0
Total: 12

7. Summary of addition operators

In C, In C, there are multiple operators for performing addition, and it’s important to choose the appropriate one for each use case. In this section, we will explain in detail differences and usage of “+”, “+=”, and “++”.

7-1. + operator (basic addition)

#include <stdio.h>

int main(void) {
    int a = 10, b = 5;
    int sum = a + b;
    printf("Total: %dn", sum);
    return 0;
}
Execution result
Total: 15

7-2. += operator (cumulative addition)

#include <stdio.h>

int main(void) {
    int num = 10;
    num += 5; // same as num = num + 5
    printf("Result: %dn", num);
    return 0;
}
Execution result
Result: 15

7-3. ++ operator (increment)

#include <stdio.h>

int main(void) {
    int num = 5;

    num++; // same as num = num + 1
    printf("Value after increment: %dn", num);

    return 0;
}
Execution result
Value after increment: 6

7-4. Difference between ++a and a++

#include <stdio.h>

int main(void) {
    int a = 5, b, c;

    b = ++a; // prefix increment
    printf("Prefix: a=%d, b=%dn", a, b);

    a = 5; // reset
    c = a++; // postfix increment
    printf("Postfix: a=%d, c=%dn", a, c);

    return 0;
}
Execution result
Prefix: a=6, b=6
Postfix: a=6, c=5

8. Things to Watch Out for When Adding in C

C language addition is a basic operation, but if you don’t understand the constraints of data types and the characteristics of calculations, unexpected errors can occur。 This section provides a detailed explanation of the risks of overflow and how to choose data types

8-1. What Are the Risks of Overflow?

#include <stdio.h>
#include <limits.h> // needed to use INT_MAX

int main(void) {
    int a = INT_MAX, b = 1;
    int sum = a + b; // overflow occurs here
    printf("Sum: %dn", sum);
    return 0;
}
Output
Sum: -2147483648

8-2. Countermeasure Using the long long Type

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

int main(void) {
    long long a = LLONG_MAX, b = 1;
    long long sum = a + b;
    printf("Sum: %lldn", sum);
    return 0;
}

8-3. How to Choose Data Types

Data TypeBit WidthRange
int32bit-2,147,483,648 ~ 2,147,483,647
long32bit or 64bitDepends on the environment
long long64bit-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807
float32bitApproximately ±3.4×10³⁸
double64bitApproximately ±1.7×10³⁰⁸

8-4. Beware of Overflow (Loss of Significance) in Computation Results

#include <stdio.h>

int main(void) {
    double a = 1000000000.0;
    double b = 0.0000001;
    double sum = a + b;

    printf("Sum: %.10fn", sum);
    return 0;
}
Output
Sum: 1000000000.0000000000

9. Advanced: Adding Large Numbers

C language’s standard data types (int, long, long long) have a limited range of representable values. However, there are cases where you need to handle large numbers (multiple-precision integers).

9-1. Using unsigned

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

int main(void) {
    printf("Maximum value of unsigned int: %un", UINT_MAX);
    printf("Maximum value of unsigned long long: %llun", ULLONG_MAX);
    return 0;
}
Result
Maximum value of unsigned int: 4294967295
Maximum value of unsigned long long: 18446744073709551615

9-2. Adding Large Numbers Using Strings

#include <stdio.h>
#include <string.h>

#define MAX 1000 // Maximum number of digits

void addLargeNumbers(char num1[], char num2[], char result[]) {
    int len1 = strlen(num1);
    int len2 = strlen(num2);
    int carry = 0, i, j, k = 0;
    char temp[MAX];

    i = len1 - 1;
    j = len2 - 1;

    while (i >= 0 || j >= 0 || carry) {
        int digit1 = (i >= 0) ? num1[i] - '0' : 0;
        int digit2 = (j >= 0) ? num2[j] - '0' : 0;

        int sum = digit1 + digit2 + carry;
        carry = sum / 10;
        temp[k++] = (sum % 10) + '0';

        i--;
        j--;
    }

    temp[k] = '\0';
    int len = k;
    for (i = 0; i < len; i++) {
        result[i] = temp[len - 1 - i];
    }
    result[len] = '\0';
}

int main(void) {
    char num1[MAX], num2[MAX], result[MAX];

    printf("Enter the first large number: ");
    scanf("%s", num1);
    printf("Enter the second large number: ");
    scanf("%s", num2);

    addLargeNumbers(num1, num2, result);
    printf("Sum: %s\n", result);

    return 0;
}
Result
Enter the first large number: 987654321987654321987654321
Enter the second large number: 123456789123456789123456789
Sum: 1111111111111111111111111110

10. Common Pitfalls for Beginners in C Language Addition Q&A

Q1. How can you efficiently add multiple numbers in C?

A1. Using arrays and loops is the best!

#include <stdio.h>

int main(void) {
   [] = {10, 20, 30, 40, 50};
    int sum = 0;
    int size = sizeof(numbers) / sizeof(numbers[0]);

    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }

    printf("Total: %d\n", sum);
    return 0;
}
Output
Total: 150

Q2. Why does the addition result differ from what I expected?

A2. The main causes are overflow or type conversionh4>

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

int main(void) {
    int a = INT_MAX, b = 1;
    int sum = a + b;
    printf("Total: %d\n", sum);
    return 0;
}
Output
Total: -2147483648

Solutions

  1. Use the long long type
  2. Check for overflow in advance with if (a > INT_MAX - b)

Q3. What is the difference between a++ and ++a?

#include <stdio.h>

int main(void) {
    int a = 5, b, c;

    b = ++a; // pre-increment
    printf("Pre: a=%d, b=%d\n", a, b);

    a = 5; // reset
    c = a++; // post-increment
    printf("Post: a=%d, c=%d\n", a, c);

    return 0;
}
Output
Pre: a=6, b=6
Post: a=6, c=5