Chapter 6 Exercises: Loops and Iteration

Part A: Conceptual Questions

A1. Explain the difference between a pre-test loop and a post-test loop. Which Pascal loop construct is post-test? Why does this distinction matter in practice?

A2. What does the word UNTIL mean in a REPEAT..UNTIL loop — does the loop continue while the condition is true, or stop when it becomes true? How does this contrast with WHILE..DO?

A3. Why does the Pascal standard say that the loop variable in a FOR loop is undefined after the loop finishes? What design principle does this rule serve?

A4. A classmate claims: "You only need WHILE loops — you can always rewrite REPEAT and FOR loops as WHILE loops, so why bother learning three?" Write a paragraph arguing against this position.

A5. What is a sentinel value? Give an example of a sentinel loop and explain why the "priming read" is necessary.

A6. Explain why the following code produces an infinite loop:

i := 1;
while i <> 10 do
begin
  WriteLn(i);
  i := i + 3;
end;

What value should the condition test instead?

A7. How many times does the body of a FOR i := 5 to 3 do loop execute? Why?

A8. What is an off-by-one error? Give an example involving a loop, and explain how to fix it.


Part B: Trace and Predict

For each program fragment, predict the exact output without running the code. Then verify by running it in Free Pascal.

B1.

x := 10;
repeat
  Write(x, ' ');
  x := x - 3;
until x < 0;
WriteLn;

B2.

n := 1;
while n < 50 do
begin
  n := n * 2;
  Write(n, ' ');
end;
WriteLn;

B3.

for i := 1 to 5 do
begin
  for j := 1 to i do
    Write(i);
  WriteLn;
end;

B4.

total := 0;
for k := 1 to 4 do
  total := total + k * k;
WriteLn(total);

B5.

ch := 'E';
while ch >= 'A' do
begin
  Write(ch);
  ch := Pred(ch);
end;
WriteLn;

B6.

a := 1;
b := 1;
Write(a, ' ', b, ' ');
for i := 3 to 8 do
begin
  c := a + b;
  Write(c, ' ');
  a := b;
  b := c;
end;
WriteLn;

Part C: Programming Exercises

C1. Countdown Timer Write a program that asks the user for a starting number and counts down to 1, printing each number. Use a FOR..DOWNTO loop. After the countdown, print "Liftoff!"

C2. Sum of N Numbers Write a program that asks the user for a positive integer n, then reads n numbers from the keyboard (using a FOR loop), and prints their sum and average.

C3. Input Validation Write a program that asks the user for a test score between 0 and 100. Use a REPEAT..UNTIL loop to keep asking until a valid score is entered. Then display the letter grade (A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60).

C4. Powers of Two Write a program that prints all powers of 2 from 2^0 to 2^20 using a FOR loop. Format the output as a two-column table: the exponent and the value.

C5. Factorial Calculator Write a program that reads a non-negative integer n (validated with a REPEAT..UNTIL loop) and computes n! (n factorial) using a FOR loop. Remember: 0! = 1.

C6. Multiplication Table Write a program that prints a multiplication table from 1x1 to 12x12, neatly formatted with column headers and row labels. Use nested FOR loops.

C7. Vowel Counter Write a program that reads a string from the user and counts the number of vowels (a, e, i, o, u — both upper and lower case) using a FOR loop that iterates through each character.

C8. Number Pyramid Write a program that prints a number pyramid of n rows (user-specified). For example, with n = 4:

   1
  2 2
 3 3 3
4 4 4 4

Use nested loops for spacing and number printing.

C9. Digit Sum Write a program that reads a positive integer and computes the sum of its digits. Use a WHILE loop with integer division (div) and modulus (mod). For example, the digit sum of 1234 is 1+2+3+4 = 10.

C10. Prime Number Checker Write a program that reads a positive integer and determines whether it is prime. Use a WHILE loop that tests potential divisors from 2 up to the square root of the number. If any divisor divides evenly, the number is not prime.

C11. Password Guesser Write a program that stores a secret password as a constant string. The user gets up to 3 attempts to guess it. Use a REPEAT..UNTIL loop that terminates when the user guesses correctly OR runs out of attempts. Display an appropriate message for each outcome.

C12. FizzBuzz Write a program that prints the numbers from 1 to 100. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For multiples of both 3 and 5, print "FizzBuzz". Use a FOR loop.

C13. Temperature Converter Table Write a program that prints a conversion table from Celsius to Fahrenheit, from 0 to 100 degrees in steps of 5. Use a FOR loop (hint: loop over step numbers, not temperatures directly, since FOR only increments by 1).

C14. Average Until Sentinel Write a program that reads real numbers from the user until they enter 0 (the sentinel). Use a WHILE loop. After the sentinel is entered, display the count of numbers entered, their sum, and their average. Handle the case where no numbers are entered before the sentinel.

C15. Reverse a Number Write a program that reads a positive integer and prints it reversed. For example, 12345 becomes 54321. Use a WHILE loop with mod and div. Do not convert to a string.

C16. Star Rectangle Write a program that asks for the width and height (both positive integers), then prints a hollow rectangle of asterisks with those dimensions using nested loops. For example, width=5, height=3:

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

C17. Collatz Conjecture Write a program that reads a positive integer and applies the Collatz rules: if the number is even, divide by 2; if odd, multiply by 3 and add 1. Repeat until the number reaches 1. Print each value in the sequence and count the total steps. Use a WHILE loop.

C18. Simple Interest Calculator Write a program that calculates how many years it takes for an investment to double at simple interest. Read the principal and annual interest rate from the user. Use a WHILE loop to simulate year-by-year growth until the amount reaches or exceeds twice the principal. Display a year-by-year table.


Part D: Debugging Exercises

D1. The following program should print the numbers 1 to 10 but has a bug. Find and fix it.

program BuggyLoop1;
var
  i: Integer;
begin
  i := 1;
  while i <= 10 do
    WriteLn(i);
    i := i + 1;
end.

D2. This program should compute the sum 1 + 2 + ... + n but produces the wrong answer. Find and fix the bug.

program BuggyLoop2;
var
  n, i, sum: Integer;
begin
  Write('Enter n: ');
  ReadLn(n);
  sum := 0;
  for i := 0 to n do
    sum := sum + i;
  WriteLn('Sum from 1 to ', n, ' is ', sum);
end.

D3. This program should keep asking for input until the user enters 'q' but runs forever. Why?

program BuggyLoop3;
var
  input: Char;
begin
  repeat
    Write('Enter a character (q to quit): ');
    ReadLn(input);
    WriteLn('You entered: ', input);
  until input = 'Q';
end.

D4. This program should print a 5x5 grid of asterisks but prints only one row. Find and fix the bug.

program BuggyLoop4;
var
  row, col: Integer;
begin
  for row := 1 to 5 do
    for col := 1 to 5 do
      Write('* ');
    WriteLn;
end.

Part E: Challenge Exercises

E1. Diamond Pattern Write a program that reads an odd positive integer n and prints a diamond pattern. For n = 5:

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

Use nested loops. The upper half (including the middle) and lower half can be handled with two separate sets of nested loops.

E2. GCD by Euclid's Algorithm Write a program that reads two positive integers and computes their Greatest Common Divisor using Euclid's algorithm: repeatedly replace the larger number with the remainder of dividing the larger by the smaller, until one of them becomes 0. The other is the GCD. Use a WHILE loop.

E3. Menu-Driven Statistics Write a program with a menu loop that lets the user: 1. Enter a data value (store up to 50 values) 2. Display count, sum, average, minimum, and maximum of all entered values 3. Clear all data 4. Quit

Use REPEAT..UNTIL for the menu, FOR loops for computing statistics, and proper input validation.

E4. Pascal's Triangle Write a program that prints the first n rows of Pascal's Triangle. Each entry is the sum of the two entries above it. Use nested FOR loops. For n = 6:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1
1 5 10 10 5 1

E5. Digital Root Write a program that computes the digital root of a number. The digital root is found by summing the digits, then summing the digits of the result, repeating until a single digit remains. For example: 9875 -> 9+8+7+5 = 29 -> 2+9 = 11 -> 1+1 = 2. Use nested WHILE loops (an outer loop for the repeated summing, an inner loop for extracting digits).


Part M: Metacognitive Reflection

M1. Which of the three loop constructs feels most natural to you right now? Which one feels least intuitive? What specifically about it is confusing?

M2. When you wrote your first WHILE loop for these exercises, did you encounter the "forgetting begin..end" bug? If so, how long did it take you to diagnose? What strategy will you use to avoid it in the future?

M3. Off-by-one errors are sometimes called the "most common bug in programming." Did you encounter any while working on these exercises? Describe the situation and how you identified and corrected the error.

M4. Rate your confidence (1-5) on each learning objective: - [ ] Writing REPEAT..UNTIL loops - [ ] Writing WHILE..DO loops - [ ] Writing FOR loops (both TO and DOWNTO) - [ ] Choosing the right loop for a situation - [ ] Identifying and fixing infinite loops and off-by-one errors

For any rating below 4, identify one specific exercise you will redo to improve your understanding.