created 08/04/99

Chapter 16 Programming Exercises


Exercise 1 --- Adding up Integers

Write a program that adds up integers that the user enters. First the programs asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.

How many integers will be added:
5
Enter an integer:
3
Enter an integer:
4
Enter an integer:
-4
Enter an integer:
-3
Enter an integer:
7

The sum is 7
Be careful not to add the number of integers (in the example, 5) into the sum.

Click here to go back to the main menu.

Exercise 2

Write a program that computes the following sum:

sum = 1.0/1 + 1.0/2 + 1.0/3 + 1.0/4 + 1.0/5 + .... + 1.0/N
N will be an integer limit that the user enters.
Enter N
4

Sum is: 2.08333333333

Click here to go back to the main menu.

Exercise 3

Write a program that computes the standard deviation of a set of floating point numbers that the user enters. First the user will say how many numbers N are to follow. Then the program will ask for and read in each floating point number. Finally it will write out the standard deviation. The standard deviation of a set of numbers Xi is:

SD = Math.sqrt( avgSquare - avg2 )
Here, avg is the average of the N numbers, and avg2 is its square.

avgSquare is the average of Xi * Xi. In other words, this is the average of the squared value of each floating point number.

For example, if N = 4, say the numbers were:

     Xi Xi * Xi
      2.0 4.0
      3.0 9.0
      1.0 1.0
      2.0 4.0
     ----- ------
  sum   8.0 18.0
then
avg = 8.0/4 = 2.0
avg2 = 4.0

avgSquare = 18.0/4 = 4.5

SD = Math.sqrt( 4.5 - 4.0 ) = Math.sqrt( .5 ) = 0.7071067812
To do this you will need to do several things inside the loop body for each floating point value as it comes in: add it to a sum, square it and add it to a sum of squares. Then after the loop is finished apply the formula.

Click here to go back to the main menu.

End of exercises.