CS 171 Sample Test 2

  1. (8 pts) Describe the output produced by the following code:
    Count := 1;
    WHILE Count < 10 DO
       WRITELN (Count)

  2. (8 pts) What is the output produced by the following code?
    Exp := 0;
    Base := 3;
    Power := 1;
    WHILE Exp < 5 DO
       BEGIN
          Power := Power * Base;
          Exp := Exp + 1;
          WRITELN (Power)
       END

  3. (12 pts) Write a Pascal program (omit comments) that asks for the user to input their name, and then greets them, as in
    What is your name? Jack
    Hello, Jack!
    What is your name?
    As the example shows, the program continues to ask for names and greet users. However, when your name is typed in, the program responds with
    What is thy bidding, O my Master?
    and then ends.

  4. (8 pts) What is the output produced by the following code?
    Count := 1;
    Total := 0;
    REPEAT
       Count := Count + 1;
       Total := Total + Count;
       WRITE (Total)
    UNTIL Count = 10;
    WRITELN (Total)

  5. (8 pts) Rewrite the following program using the style rules:
    program power ; var base , exponent, count : integer ; results : real;
    begin write ('Enter base for power: ') ; readln (base) ;
    write ('Enter exponent for power: ') ; readln (exponent) ; Results := 1;
    Count:=0;
    repeat results := results * base ; count := count + 1 until
    count >= exponent ; write ('Power is: '); writeln (results : 1 : 1) end.

  6. (8 pts) Write a REPEAT-UNTIL loop that asks the user to input a number, repeatedly, until a positive number is entered.

  7. (8 pts) What is wrong with the following?
    FOR Count := 1 TO Finish DO
       IF Finish > 4
          THEN Count := Finish
          ELSE WRITE (Count)

  8. (8 pts) What is the output produced by the following code?
    FOR Outer := 1 TO 6 DO
       FOR Inner := 5 DOWNTO 1 DO
          IF Inner <> Outer
             THEN WRITE (Inner)

  9. (8 pts) The value 5 factorial (written 5! in mathematics) is the product 5*4*3*2*1. Similarly, to calculate N factorial, we would multiply N*(N-1)*...*2*1, as in the following:
    Fact := 1;
    FOR I := N DOWNTO 1 DO
       Fact := Fact * I
    Write a procedure Factorial(N,Result) that would calculate N factorial and return the answer in Result.

  10. (8 pts)Write a function Factorial(N) that calculates N factorial.

  11. (8 pts)Discuss which approach, procedure or function, is the most appropriate for calculating factorials.

  12. (8 pts)Discuss the difference between Value and Variable parameters. Explain when to use each.