More Loops Worksheet

Show the output produced by the following segments of code. Assume that
all variables are declared as int.

1.  for (int k = 1; k <= 2; k++)
       for (int m = 1 ; m <= 3; m++)
          cout << k << ' ' << m << endl;


2.  for (int d = 6; d >= 4; d--)
       for (int e = 2; e <= 4; e++)
          cout << d << ' ' << e << endl;


3.  x = 1;
    while (x <= 5)
    {
        sum = 0;
        y = 1;
        while (y <= x)
        {
            sum += y;
            y++;
        }
        cout << sum << ' ';
        x++;
    }


4.  for (i = 1 ; i <= 5 ; i++)
    {
       cout << i << endl;
       for (j = i ; j >= 1 ; j -= 2)
          cout << j << endl;
    }


5.  for (i = 1 ; i <= 3 ; i++)
       for (j = 1 ; j <= 3 ; j++)
       {
          for (k = i ; k <= j ; k++)
             cout << i << j << k << endl;
          cout << endl;
       }


6.  for (i = 3 ; i > 0 ; i--)
       for (j = 1 ; j <= i ; j++)
          for (k = i ; k >= j ; k--)
             cout << i << j << k << endl;


7. Write statements that will read numbers and print out the sum of the
numbers. The program should stop when the user enters -999, or after
reading 5 numbers, whichever comes first.


8. Test your program from problem 7 with the following data:
         10 20 30 -999


9. Test your program from problem 7 with the following data:
         10 20 30 40 50 60 70


10. Write a program segment using nested loops to create the following
output:

*
**
***
****
*****
******
*******
********
*********


11. Write a program segment using nested loops to create the following
output:

    *
   ***
  *****
 *******
*********


12. Prompt the user to enter y or n. If the user enters an invalid
character, keep re-prompting until a value character is entered.
Use a while loop.


13. Redo problem 12 with a do-while loop.

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

© Copyright Emmi Schatz 2002