Introduction to Computer Science:
Assignment 11:  While Loops
    Sewickley Academy, 2000-2001

See Course Home Page.
 
Date Assigned: Tue Oct-10
Date Due: Wed Oct-11 by end of day

This assignment is the last small step before we return to more traditional assignments -- thus, the main point of this assignment is to verify one last time that you can in fact write a simple C++ program as a homework assignment.  After this, the size and complexity of the programs will increase somewhat.

In class today, we wrote a program which empirically proved that the sum of the first N numbers is N * (N+1) / 2.  For tonight's assignment, you should write a very similar program which empirically proves that the sum of the squares of the first N numbers is (N * (N+1) * (2N+1)) / 6.

So, for example:  12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30 = 4 * 5 * 9 / 6.  Indeed!

To do this, ask the user to enter a number (numbers 0 or less should make your program immediately quit).  Your program should add the squares of numbers up to that number, then verify that this sum equals (N * (N+1) * (2N+1)) / 6.

Two changes from today in class:  first, your program should continue looping until the user does enter a non-positive integer.  Second, it should print out both the sum of the first N squares, and the result of (N * (N+1) * (2N+1)) / 6.  So, here is what your program's execution should look like (user input is underlined):

Enter a positive integer (0 or negative to quit): 4

The sum of the squares of the first 4 positive integers is:  30

(4 * (4+1) * (2*4+1)) / 6 = 30.

They match -- the function works!

Enter a positive integer (0 or negative to quit):  3

The sum of the squares of the first 3 positive integers is:  14

(3 * (3+1) * (2*3+1)) / 6 = 14.

They match -- the function works!

Enter a positive integer (0 or negative to quit): -1

Goodbye.

Hint:  In order to loop repeatedly like it does here, you may wish to enclose your entire program within a loop of the following form:
    while (true)
    {
        // This code will be run repeatedly forever...
        // So you must "return" to exit from here
    }

Best of luck!



See Course Home Page.