CS 1401, Quiz #6

Date: Monday, October 8, 2007
Name: ____________________________________________________________
Class section (9:30 am or 11:30 am): _______________________________

1. For each of the following topics, write "yes" or "no" depending on whether this topic is covered in Chapter 6, the chapter that you were supposed to read before the class:

for loops no

linked lists no

object oriented design yes

Graphical User Interface yes

2. Write a code that uses a for-loop to compute the factorial n! of a given number n, i.e., to multiply all the integers from 1 to n. Do not worry about reading this number or printing the results, assume that the number is there.


fact = 1;
for (int i = 1; i <= n; i++)
  {fact *= i;}

3. Write a similar code, but using the while loop.


fact = 1;
int i = 1;
while (i <= n){
  fact *= i;

4. For extra credit: Explain the difference between while- and for-loops. When is it better to use while loops and when for loops? Based on your explanation, what is better for computing the factorial of n?

Main difference: in a for loop, initialization and update (like i++)
are done automatically.

Recommendation: for loops are better when we know how many iterations
we need. For n!, we know how many iterations we need, so it is
better to use a for loop.