Write a C program to add two arrays.
#include <stdio.h>
#define MAXLIMIT 256
int main() {
int i, n1, n2, n3;
int arr1[MAXLIMIT], arr2[MAXLIMIT], sum[MAXLIMIT];
/* get the number of elements for first array */
printf("Number of elements in first array:");
scanf("%d", &n1);
/* get the number of elements for second array */
printf("Number of elements in second array:");
scanf("%d", &n2);
/* get the inputs for the first array */
printf("Enter your inputs for Array 1:\n");
for (i = 0; i < n1; i++) {
printf("Array[%d]: ", i);
scanf("%d", &arr1[i]);
}
/* get the inputs for the second array */
printf("\nEnter your inputs for Array 2:\n");
for (i = 0; i < n2; i++) {
printf("Array[%d]: ", i);
scanf("%d", &arr2[i]);
}
/* getting the max of n1 and n2 */
n3 = n1 > n2 ? n1 : n2;
/* adding two arrays */
for (i = 0; i < n3; i++) {
if (i < n1 && i < n2) {
sum[i] = arr1[i] + arr2[i];
} else if (i < n1) {
#define MAXLIMIT 256
int main() {
int i, n1, n2, n3;
int arr1[MAXLIMIT], arr2[MAXLIMIT], sum[MAXLIMIT];
/* get the number of elements for first array */
printf("Number of elements in first array:");
scanf("%d", &n1);
/* get the number of elements for second array */
printf("Number of elements in second array:");
scanf("%d", &n2);
/* get the inputs for the first array */
printf("Enter your inputs for Array 1:\n");
for (i = 0; i < n1; i++) {
printf("Array[%d]: ", i);
scanf("%d", &arr1[i]);
}
/* get the inputs for the second array */
printf("\nEnter your inputs for Array 2:\n");
for (i = 0; i < n2; i++) {
printf("Array[%d]: ", i);
scanf("%d", &arr2[i]);
}
/* getting the max of n1 and n2 */
n3 = n1 > n2 ? n1 : n2;
/* adding two arrays */
for (i = 0; i < n3; i++) {
if (i < n1 && i < n2) {
sum[i] = arr1[i] + arr2[i];
} else if (i < n1) {
sum[i] = arr1[i];
} else if (i < n2) {
sum[i] = arr2[i];
}
}
/* printing contents of array 1 */
printf("\nArray 1:\n{");
for (i = 0; i < n1; i++) {
printf("%d, ", arr1[i]);
}
printf("\b\b}\n");
/* printing the contents of array 2 */
printf("\nArray 2:\n{");
for (i = 0; i < n2; i++) {
printf("%d, ", arr2[i]);
}
printf("\b\b}\n");
/* printing the sum of 1st and 2nd array */
printf("Result:\n{");
for (i = 0; i < n1; i++) {
printf("%d, ", sum[i]);
}
printf("\b\b}\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Number of elements in first array:4
Number of elements in second array:2
Enter your inputs for Array 1:
Array[0]: 10
Array[1]: 20
Array[2]: 30
Array[3]: 40
Enter your inputs for Array 2:
Array[0]: 50
Array[1]: 60
Array 1:
{10, 20, 30, 40}
Array 2:
{50, 60}
Result:
{60, 80, 30, 40}
Number of elements in first array:4
Number of elements in second array:2
Enter your inputs for Array 1:
Array[0]: 10
Array[1]: 20
Array[2]: 30
Array[3]: 40
Enter your inputs for Array 2:
Array[0]: 50
Array[1]: 60
Array 1:
{10, 20, 30, 40}
Array 2:
{50, 60}
Result:
{60, 80, 30, 40}
No comments:
Post a Comment