In: Computer Science
Write a C function to add the elements of two same-sized integer arrays and return ptr to a third array.
int *addTwoArrays(int *a1, int *b1, int size);
The function should follow the following rules:
Please call this function with the following arrays and print the sums (print sum array elements in separate lines for cases i, ii below).
i. int a1[] = {1, -15, 2, 14, 3, -13, 0};
int b1[] = {0, 16, 2, -15, -3, 10, 0};
ii. int a2[] = {100, 101, 200, -3011};
int b2[] = {1000, 1010, -300, 10000};
Hint: For the array with sum, you may have to declare a global var
#include<stdio.h>
int sum[];
int *addTwoArrays(int *a1, int *b1, int size)
{
if(a1==b1)
{
return NULL;
}
if((a1==NULL)||(b1==NULL))
{
return NULL;
}
for(int i=0;i<size;i++)
{
sum[i] = 0;
}
for(int i=0;i<size;i++)
{
sum[i] = a1[i] + b1[i];
}
printf("Sum is: ");
for(int i=0;i<size;i++)
{
if(sum[i]<0)
{
sum[i]=0;
}
printf("\t%d\t",sum[i]);
}
}
int main()
{
int i;
//for the execution of case1
int a1[]={1,-15,2,14,3,-13,0};
int b1[]={0,16,2,-15,-3,10,0};
int size=7;
printf("\ncase 1:\n");
printf("\ta1[]=\t");
for(i=0;i<size;i++)
printf("%d\t\t",a1[i]);
printf("\n\tb1[]=\t");
for(i=0;i<size;i++)
printf("%d\t\t",b1[i]);
printf("\n");
addTwoArrays(a1,b1,size);
//for the execution of case2
int a[]={100,101,200,-3011};
int b[]={1000,1010,-300,10000};
size=4;
printf("\n\ncase 2:\n");
printf("\ta1[]=\t");
for(i=0;i<size;i++)
printf("%d\t\t",a[i]);
printf("\t");
printf("\n\tb1[]=\t");
for(i=0;i<size;i++)
printf("%d\t\t",b[i]);
printf("\n");
addTwoArrays(a,b,size);
return 0;
}
OUTPUT GENERATED:
case 1:
a1[]= 1
-15 2
14 3
-13 0
b1[]= 0
16 2
-15 -3
10 0
Sum is: 1 1
4 0
0 0
0
case 2:
a1[]= 100
101 200
-3011
b1[]= 1000
1010 -300
10000
Sum is: 1100
1111 0
6989