
157 views
How to Add two Array in C
To add two arrays in C, you need to create a third array to store the result of the addition. You’ll then iterate through both arrays element by element, add the corresponding elements together, and store the result in the third array. Here’s a C program to add two arrays:
C
#include <stdio.h>
int main() {
int size;
// Input the size of the arrays
printf("Enter the size of the arrays: ");
scanf("%d", &size);
// Initialize the arrays
int array1[size];
int array2[size];
int result[size];
// Input elements of the first array
printf("Enter elements of the first array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &array1[i]);
}
// Input elements of the second array
printf("Enter elements of the second array:\n");
for (int i = 0; i < size; i++) {
scanf("%d", &array2[i]);
}
// Perform array addition
for (int i = 0; i < size; i++) {
result[i] = array1[i] + array2[i];
}
// Display the result array
printf("Result of array addition:\n");
for (int i = 0; i < size; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
This program first takes the size of the arrays as input. Then, it initializes the arrays and reads the elements for both arrays. After that, it performs the addition element by element and stores the result in the result
array. Finally, it displays the result array.
Make sure to enter the elements of both arrays carefully, ensuring that they have the same size for addition to be valid.