Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Add n binary strings?
In C programming, adding n binary strings involves performing binary addition on multiple binary numbers represented as strings. We need to add all binary strings together to produce a single binary result.
The approach uses binary addition logic with carry propagation, adding all strings one by one to get the final result.
Syntax
char* addBinaryStrings(char* binary1, char* binary2); char* addNBinaryStrings(char** binaryArray, int n);
Example: Adding Multiple Binary Strings
This example demonstrates adding three binary strings using a helper function that adds two binary strings at a time −
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* addBinary(char* b1, char* b2) {
int len1 = strlen(b1);
int len2 = strlen(b2);
int maxLen = (len1 > len2 ? len1 : len2) + 1;
char* result = (char*)malloc((maxLen + 1) * sizeof(char));
result[maxLen] = '\0';
int carry = 0;
int i = len1 - 1, j = len2 - 1, k = maxLen - 1;
while (i >= 0 || j >= 0 || carry) {
int sum = carry;
if (i >= 0) {
sum += b1[i] - '0';
i--;
}
if (j >= 0) {
sum += b2[j] - '0';
j--;
}
result[k] = (sum % 2) + '0';
carry = sum / 2;
k--;
}
// Remove leading zeros
int start = 0;
while (start < maxLen && result[start] == '0') {
start++;
}
if (start == maxLen) {
strcpy(result, "0");
return result;
}
memmove(result, result + start, maxLen - start + 1);
return result;
}
char* addNBinary(char** arr, int n) {
char* result = (char*)malloc(2 * sizeof(char));
strcpy(result, "0");
for (int i = 0; i < n; i++) {
char* temp = addBinary(result, arr[i]);
free(result);
result = temp;
}
return result;
}
int main() {
char* binaryStrings[] = {"1011", "10", "1001"};
int n = 3;
printf("Input binary strings:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", binaryStrings[i]);
}
char* result = addNBinary(binaryStrings, n);
printf("\nSum: %s\n", result);
free(result);
return 0;
}
Input binary strings: 1011 10 1001 Sum: 10110
How It Works
- The addBinary() function adds two binary strings using carry propagation
- Starting from the rightmost digits, it adds corresponding bits along with any carry
- The addNBinary() function iteratively adds all strings using the helper function
- Leading zeros are removed from the final result
Key Points
- Binary addition follows the rules: 0+0=0, 0+1=1, 1+0=1, 1+1=10 (with carry)
- Memory is dynamically allocated to handle varying string lengths
- The algorithm processes digits from right to left, maintaining proper carry propagation
Conclusion
Adding multiple binary strings in C requires careful carry handling and memory management. This approach efficiently combines n binary numbers by repeatedly using a two-string addition function.
Advertisements
