CSC 270 
Homework 2

C, C++, or Java version:


Write a program that reads in an int, then that many double numbers into an array, prints their sum and average (appropriately labelled), and prints out how many of them are positive. The task of finding the sum should be done by a function named sum to which the array is passed. The task of counting how many are positive should be done by a function named countPos to which the array is passed. Note that in C and C++, you'll need to pass in the size of the array, as well as the array itself; this isn't necessary in Java. The int at the beginning should be no smaller than 0, nor larger than 100; if it is, your program should print an appropriate error message rather than asking for the doubles and printing the results.

For example, if the input were
5 3.7 5.2 -4.7 -62 14.7
the output might be
Sum: -43.1
Average: -8.62
3 of your 5 numbers are positive.

Also turn in sample runs with well-chosen test cases.

Note: in C or C++, you can demonstrate the use of pointers and memory management by using a pointer rather than an array declaration, and allocating exactly as much memory as necessary. In Java, this is the only natural way to do it.

Scheme version:

Write three functions sum, average, and count-positive, each of which takes in a list of numbers and returns a number.

If you want to practice your Scheme I/O, you can then write a 0-parameter function named hw2 that asks the user for a number, prints an error message if it's less than 0, more than 100, or not an integer, and otherwise asks for that many numbers, forms them into a list, and prints the results as above.

If you want to learn about Scheme vectors, try doing the same thing using a vector rather than a list.

Prolog version:

As in the Scheme version, using Prolog lists.


Last modified: 
Stephen Bloch / sbloch@adelphi.edu