This is intended to be a function to add the elements of two same-sized integer arrays and return pointer to a third array.
this is required /
int *addTwoArrays(int *a1, int *b1, int size);
The function should follow the following rules:
- If the sum for any element is negative, make it zero.
- If a1 and b1 point to the same array, it returns a NULL
- If any input array is NULL, it returns a NULL.
and I need to call this function with the following arrays and print the sums (print sum array elements in separate lines for cases i, ii below).
case i.
int a1[] = {1, -15, 2, 14, 3, -13, 0};
int b1[] = {0, 16, 2, -15, -3, 10, 0};
case ii.
int a2[] = {100, 101, 200, -3011};
int b2[] = {1000, 1010, -300, 10000};
i also cant use any external libraries (other than the default stdio.h)
#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");
addTwoArrays(a1, b1, size);
//for the execution of case2
int a2[] = {100, 101, 200, -3011};
int b2[] = {1000, 1010, -300, 10000};
size = 4;
printf("\n\ncase 2:\n");
addTwoArrays(a2, b2, size);
}
I'm sure there are better ways as this (more compact ways) but I'm new to c, and I need to compress this as best as I can.