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
Add two numbers represented by two arrays in C Program
A number represented by an array is stored in such a form that each digit of the number is represented by an element of the array. For example −
Number 234 in array is {2,3,4}
To add two such numbers we will first add digits from the least significant position and if the sum is greater than 9, we propagate the carry. We continue this process for consecutive digits until all digits are processed.
Syntax
void addArrays(int arr1[], int arr2[], int size1, int size2, int result[]);
Algorithm
To find the sum of numbers stored as arrays −
- Start from the rightmost digits (least significant)
- Add corresponding digits along with any carry from previous addition
- Store the result digit (sum % 10) and calculate new carry (sum / 10)
- Continue until all digits are processed
- Handle remaining digits of the longer array
Example
Let's add two numbers represented as arrays −
#include <stdio.h>
void addArrays(int arr1[], int arr2[], int size1, int size2) {
int maxSize = (size1 > size2) ? size1 : size2;
int result[maxSize + 1];
int carry = 0;
int i = size1 - 1;
int j = size2 - 1;
int k = maxSize;
/* Initialize result array */
for(int x = 0; x <= maxSize; x++) {
result[x] = 0;
}
/* Add digits from right to left */
while(i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if(i >= 0) {
sum += arr1[i];
i--;
}
if(j >= 0) {
sum += arr2[j];
j--;
}
result[k] = sum % 10;
carry = sum / 10;
k--;
}
/* Print result */
printf("Sum: ");
int started = 0;
for(int x = 0; x <= maxSize; x++) {
if(result[x] != 0 || started) {
printf("%d", result[x]);
started = 1;
}
}
if(!started) {
printf("0");
}
printf("<br>");
}
int main() {
int arr1[] = {2, 9, 6};
int arr2[] = {6, 3, 8};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
printf("Array 1: ");
for(int i = 0; i < size1; i++) {
printf("%d", arr1[i]);
}
printf("<br>");
printf("Array 2: ");
for(int i = 0; i < size2; i++) {
printf("%d", arr2[i]);
}
printf("<br>");
addArrays(arr1, arr2, size1, size2);
return 0;
}
Array 1: 296 Array 2: 638 Sum: 934
How It Works
For arrays {2,9,6} and {6,3,8} −
- Step 1: Add rightmost digits: 6 + 8 = 14 ? digit = 4, carry = 1
- Step 2: Add next digits with carry: 9 + 3 + 1 = 13 ? digit = 3, carry = 1
- Step 3: Add leftmost digits with carry: 2 + 6 + 1 = 9 ? digit = 9, carry = 0
- Result: {9,3,4} which represents 934
Conclusion
Adding numbers represented as arrays involves digit-by-digit addition from right to left with proper carry handling. This approach works for numbers of any length and handles cases where arrays have different sizes.
