Homework 9: Due Thursday, October 12th

Read Chapter 5, section 5.4. Complete the following problems:

What is printed by each of the following? Assume that i and j are int
variables.

1.  for (i=1 ; i<10 ; i=i+1)     3.  for (i = 10 ; i < 10 ; i++)
       cout << "again";                cout << "more";

2.  i = 5;                       4.   for (i = 5 ; i > 0 ; i = i - 1)
    for (j = 1 ; j < 7 ; j++)            cout << "yes";
       i = i - 2;
    cout << "i = " << i << " and j = ";
    cout << j << endl;


5.  Rewrite the following statements using a for loop instead of a
while loop.

    total = 4;
    i = 2;
    while (i < 5)
    {
       total = total * i;
       i = i + 1;
    }
    cout << "The total is " << total << endl;

6.  Use a for loop to write a program segment that:
          1.   reads a number input by the user and stores the number in a
               variable called limit.
          2.   adds up all the odd numbers between 1 and limit

7.  Consider the following program to add up a list of numbers. The value
999 is used as a sentinel to stop the loop:

    num = 0;
    sum = 0;
    cout << "Enter a number: ";
    cin >> num;
    while (num != 999)
    {
       sum += num;
       cout << "Enter a number: ";
       cin >> num;
    }
    cout << "The total is : " << sum << endl;

    A.  What should the program calculate for the sum if the user wants
    to add up the numbers 10, 20, and 30?

    B.  What data should the user input to get the program to add up
    the numbers 10, 20, and 30?

    C.  What is the output from the program if the user inputs:
            10 20 30 999

8.  Consider the following program to add up a list of numbers. The
value 999 is used as a sentinel to stop the loop:

    num = 0;
    sum = 0;
    while (num != 999)
    {
       cout << "Enter a number: ";
       cin >> num;
       sum += num;
    }
    cout << "The total is : " << sum << endl;

    A.  What should the program calculate for the sum if the user wants
    to add up the numbers 10, 20, and 30?

    B.  What data should the user input to get the program to add up
    the numbers 10, 20, and 30?

    C.  What is the output from the program if the user inputs:
            10 20 30 999

    D.  Is this program correct? If not, why not.

Remember to type your answers and to make two copies of each homework assignment. One copy is submitted to me and the other you keep to use in the group discussions.


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2004