Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write a function called add_to_array. The function is passed 3 parameters: an

ID: 3814404 • Letter: 1

Question

1. Write a function called add_to_array. The function is passed 3 parameters: an array of integers x, the length of the array len, and an incrementing value i. The function modifies the array by adding i to each element in x. Here is the prototype for this function:

// in C, an array does not know how long it is. So its length

// must be passed as a second parameter.

void add_to_array(int[], int, int);

And here is an example of how the function should work:

int main() { int numbers[ ] = {3, 6, 2, 6, 1, 0, 6};

add_to_array(numbers, 7, 2);

int i;

for (i=0; i<6; i++) printf("%d ", numbers[i]); printf(" "); }

In this case, the correct output is 5 8 4 8 3 2 8.

Fill in the function as specified in the write-up. I have included a main function in this file. While my main function tests a few cases, I suggest that you write your own main function to test your code more thoroughly. YOU SHOULD REMOVE THE main FUNCTION FROM THIS FILE

*/

#include <stdio.h>

// 1. Write a function called add_to_array.
// The function is passed 3 parameters: an array of
// integers x, the length of the array len, and an
// incrementing value i. The function modifies the
// array by adding i to each element in x. See the
// homework write-up for details.

Here is the prototype for this function:
// in C, an array does not know how long it is. So its length
// must be passed as a second parameter.
void add_to_array(int[], int, int);

And here is an example of how the function should work:

void add_to_array(int x[], int len, int i) {
// replace the line below with your code.
// it is only here so that the initial version
// of hw1.c will compile.
return 0;
}

Explanation / Answer

#include <stdio.h>
void add_to_array(int x[], int len, int i);
int main()
{
int numbers[ ] = {3, 6, 2, 6, 1, 0, 6};
add_to_array(numbers, 7, 2);
int i;
for (i=0; i<7; i++)
printf("%d ", numbers[i]); printf(" ");

return 0;
}

void add_to_array(int x[], int len, int i) {
int j=0;
for(j=0; j<len; j++){
x[j] = x[j]+i;
}
}

Output:

sh-4.2$ gcc -o main *.c                                                                                                                                                                                                                                                

sh-4.2$ main                                                                                                                                                                                                                                                           

5 8 4 8 3 2 8