CS 12 Homework Assignment 2
CS 12 Homepage
This assignment is due on Monday, August 4, 2003, at the start of the lecture. Please hand in printed solutions.
1. Suppose I gave you N numbers, { a1, a2, a3, ..., aN }. Define what their average is, that is, write a formula that computes their average.
2.a. Suppose I gave you a sequence of integer numbers, all at once (as opposed to one at a time). In English, not pseudo-code or C++, explain how you could determine their average. Be as explicit and precise in your argument as possible.
2.b. Now do the same thing, but assuming that I give you the numbers one at a time.
3.a. Now write a function double avg(int a[], unsigned int length), taking as arguments an array of integers and its corresponding length, that determines and returns the average of the numbers in the array.
3.b. Write a program to test your solution to 3.a. More specifically, write your main function so that it asks the user for the number of integers (N) and then for each of those integers. Finally, main() should use 3.a. to compute the average of those numbers and then display the result.
4. Explain what the function below is supposed to do and why it does not work as intended. Then, fix it.
int f(int a, int b)
{
return (a + b) / 2;
}
5.a. This one is a little tricky. Suppose you already know the average of N numbers previously given to you (call it avg_N) and suppose also that I now give you one more number (call it a). How can you compute the average of all (N+1) numbers (call it avg_Np1), if you haven't recorded the first N numbers? In other words, all that you have is avg_N, a, and N, and I want you to compute avg_Np1. (Note: the Np1 part in avg_Np1 is just to indicate that I mean (N+1). It's just a notation. Don't get hung up on it.)
5.b. Can you think of a reason why it would be useful to be able to do what 5.a. asks? There are at least two such reasons.
© 2003 UC Riverside Department of Computer Science & Engineering. All rights reserved.