3.11. Practice Problems

while Loops

1. Write a program that prompts the user to enter a sequence of scores (integers) and prints the highest score, as illustrated at the right.
  1. All scores are non-negative (i.e., 0 or > 0)
  2. The user enters a -1 to end data input
  3. After the user enters a -1, print the largest score and end the program
  4. Use only while loops and if statements
Enter a score (-1 to end): 25
Enter a score (-1 to end): 15
Enter a score (-1 to end): 35
Enter a score (-1 to end): 5
Enter a score (-1 to end): 100
Enter a score (-1 to end): 90
Enter a score (-1 to end): -1
The maximum score is 100
Hints
Solution
2. Write a program that prompts the user to enter a sequence of scores (integers) and prints the average of all scores as illustrated at the right.
  1. All scores are non-negative (i.e., 0 or > 0)
  2. The user enters a -1 to end data input
  3. After the user enters a -1, print the average and end the program
  4. Use only while loops
Enter a score (-1 to end): 25
Enter a score (-1 to end): 15
Enter a score (-1 to end): 35
Enter a score (-1 to end): 5
Enter a score (-1 to end): 100
Enter a score (-1 to end): 90
Enter a score (-1 to end): -1
The average is 45
Hints
Solution
3. Repeat problem 1, but use an infinite while loop and a break statement.   Solution
4. Repeat problem 2, but use an infinite while loop and a break statement.   Solution

for Loops

5. The two for-loops at the right are very similar. Describe the "picture" that each loop draws.
for (int i = 0; i < 5; i++)
	cout << '*' << endl;
Solution
for (int i = 0; i < 5; i++)
	cout << '*';
cout << endl;
6. Write the for loop(s) necessary to draw the picture at the right.
*****
*****
*****
*****
*****
Hints
Solution
7. Write the for loop(s) necessary to produce the output at the right.
1
22
333
4444
55555
666666
7777777
Hints
Solution
8. Modify the loops above to produce the output at the right.
      1
     22
    333
   4444
  55555
 666666
7777777
Hints
Solution