Array Exercises

For this assignment you will write two programs, both of which begin by asking the user for an array size, then asking the user to enter that many integers, and then placing the values the user enters into an array.

Filling the Array

Since the user is choosing the size of the array, you will have to wait to declare the array until you know what the size is going to be. So both programs should start out with the following steps:

See the example file arrays.c that I created for the video for an example of using scanf() to fill up an array in a loop.

array_abs.c

In the file array_abs.c, write a program that prints out the absolute values of the integers that the user entered. To get the absolute value of an int you can either use the abs() function (which requires including stdlib.h) or you can multiply the value by -1 if it is negative.

Here is what an example run should look like:

Enter the size of the array: 4
Enter the integers to put in the array: -3 5 -10 2
Here are the absolute values of the integers you entered:
3 5 10 2

To pass the tests, the last line of your output must contain each absolute value separated by a single space.

array_sum_avg.c

In the file array_sum_avg.c, write a program that computes the sum and average of the integers in an array of values filled with user input. The average will be the sum divided by the array size, but remember that you need to cast either the sum or the size to a double in the division otherwise the result will be an integer. To cast the variable sum to a double you would write (double)sum.

Use two loops in this program: one to fill up the array and another to calculate the sum. Note that you could write this program with a single loop and avoid using an array altogether. However, the point of this exercise is for you to practice declaring an array and using loops to access the elements of the array, so you will not get full credit if you do not use an array and two loops.

Here is what an example run should look like:

Enter the size of the array: 4
Enter the values to put in the array: 1 4 5 7
Sum: 17
Average: 4.250000

The text of your prompts can be different, but the last two lines must follow this format exactly for the tests to pass.

Grading

Your grade will be based on the following: