C Program to Add Two Numbers - Using + Operator & Bitwise Addition

Add Two Numbers Using + Operator

#include <stdio.h>
int main() {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    int sum = a + b;
    printf("Sum = %d\n", sum);
    return 0;
}
Enter two integers: 5 3
Sum = 8
        

Using the + operator is the simplest and most common way to add two integers in C. After reading the inputs with scanf(), the sum is stored in a third variable and printed.

Add Two Numbers Using Bitwise Operators

#include <stdio.h>
int add(int a, int b) {
    while (b != 0) {
        int carry = a & b;
        a = a ^ b;
        b = carry << 1;
    }
    return a;
}
int main() {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);
    printf("Sum = %d\n", add(a, b));
    return 0;
}
Enter two integers: 7 5
Sum = 12
        

Bitwise addition repeatedly computes the carry and partial sum. The carry is calculated using bitwise AND, and the partial sum is obtained using XOR. The process continues until there is no carry left, resulting in the final sum.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...