C Program to Add 2 Binary Strings - Source Code, Output & Execution Flow

C Program to Add 2 Binary Strings

This tutorial explains c program to add 2 binary strings with C source code, sample output, and step-by-step execution flow.

#include <stdio.h>
#include <string.h>
int main() {
    char a[] = "1011", b[] = "1101", result[20];
    int i = strlen(a) - 1, j = strlen(b) - 1, k = 0, carry = 0, sum;
    while (i >= 0 || j >= 0 || carry) {
        sum = carry + (i >= 0 ? a[i--] - '0' : 0) + (j >= 0 ? b[j--] - '0' : 0);
        result[k++] = (sum % 2) + '0';
        carry = sum / 2;
    }
    while (k--) printf("%c", result[k]);
    return 0;
}
11000

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.