CSE110 Summer Session I
Homework #2: Loops
Due Friday, June 1 2001
NOTE: Please remember to provide relevant comments on all
programs
Also, name your files hw2p1.c, hw2p2.c, hw2p3.c, hw2p4.c
/html/courses/cse110/hw2p1 /html/courses/cse110/hw2p2 /html/courses/cse110/hw2p3 /html/courses/cse110/hw2p4
1. [20 points] Write a program that reads in a list of integers from the user until the user enters the value 0 as a sentinel. You can assume that all the integers will be positive. When the sentinel appears, you should display the largest value in the list.
Note: Problems 1 and 2 are most naturally done by using a while loop, sonmething we haven't covered in class yet, as of this writing (5/24). A brief, and sufficient, introduciton to while loops is on page 71 in the textbook. The example code in Figure 3.3, page 72 in the book (addlist.c) is an example of how to write a program to input numbers until the user enters 0.
% a.out Enter an integer: 3 Enter an integer: 5 Enter an integer: 7 Enter an integer: 4 Enter an integer: 0 The largest integer was: 7
2. [20 points] Rewrite the program to print out the smallest value. You can still assume that all integers are positive and that 0 is taken as the sentinel value.
% a.out Enter an integer: 3 Enter an integer: 5 Enter an integer: 7 Enter an integer: 4 Enter an integer: 0 The smallest integer was: 3
3. [30 points] Write a program that will take an integer n and print out n factorial. The value n factorial for n >= 1 is defined as 1 * 2 * ... * (n - 1) * n.   0 factorial is defined to be 1. Factorial is undefined for any integer less than 0. Make sure your program works for all integer values. For an input that is less than 0, just print "Error, factorial undefined for n".
% a.out Enter an integer n: 5 5 factorial = 120 % a.out Enter an integer n: 0 0 factorial = 1 % a.out Enter an integer n: -3 Error, factorial undefined for -3
4. [30 points] Write a program that will take an integer n >= 1 and print out a table with the integers 1 through n in the left column and the average of the sum of the first i numbers in the right column. Format your output so that exactly 2 decimal places are displayed in the right column.
(Addition to original statement of problem: Check that the integer that the user enters is >0. If it is not, notify the user and ask him/her to enter it again.Enter an integer n: 0 n must be positive, try again: -1 n must be positive, try again: 10 i avg ----------------------------- 1 1.00 2 1.50 3 2.00 4 2.50 5 3.00 6 3.50 7 4.00 8 4.50 9 5.00 10 5.50