Adding two integers in C combines two values to produce their sum. The + operator provides the simplest way to perform this operation.
- C also allows addition using increment and bitwise operations.
- These approaches demonstrate different ways to perform the same operation.
Illustration
Input: a = 5, b = 3
Output: 8
Explanation: The sum of 5 and 3 is 8.Input: a = -2, b = 7
Output: 5
Explanation: The sum of -2 and 7 is 5.
Approaches to Add Two Integers
The following approaches can be used to add two integers:
1. Using the + Operator
The + operator directly adds two integer values and returns their sum.
- It works with both integers and floating-point numbers.
- The result is stored in a variable or printed directly.
#include <stdio.h>
int main() {
int a, b, sum = 0;
// Read two numbers from the user
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
// Calculate the addition of a and b
// using '+' operator
sum = a + b;
printf("Sum: %d", sum);
return 0;
}
Output
Enter two integers: 5 3
Sum: 8
Explanation: The program reads two integers, adds them using the + operator, and stores the result in sum.
2. Using the Increment Operator
The ++ operator can be used to add a value repeatedly. For a positive b, a is incremented b times; for a negative b, it is decremented accordingly.
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
if (b >= 0) {
for (int i = 0; i < b; i++)
a++;
}
else {
for (int i = 0; i > b; i--)
a--;
}
printf("Sum = %d", a);
return 0;
}
Output
Enter two integers: 5 3
Sum = 8
Explanation: The program repeatedly increments or decrements a based on the value of b, resulting in a + b.
3. Using Bitwise Operators
Addition can also be performed without the + operator using XOR and AND operations.
Approach
- XOR (^) adds the bits without considering the carry.
- AND (&) identifies the carry bits.
- Left shift (<<) moves the carry to the next position.
- The process repeats until no carry remains.
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
printf("Sum = %d", a);
return 0;
}
Output
Enter two integers: 5 3
Sum = 8
Explanation: a ^ b calculates the sum without carry, while a & b identifies the carry. Shifting the carry left by one position and repeating the process produces the final sum.