Sample Midterm #1 A22.0002

1. (30 points.) Write a program that reads a goup of contiguous numbers from
the keyboard. For instance 45231 such that the first digit indicates how many
digits follow. Thus the "4" indicates that four digits will
follow. The program should sum the remaining digits. Thus if the inputted digits
are 523167, the result would be the sum of 2, 3, 1, 6, and 7. The program should
be written in general.

Hint. Use `J`, as the loop control variable, where ` VAR J:integer`

Here are some questions to help you do the problem:

If `First` is the variable that the first digit is read into, is it read
before or after the `FOR-DO loop`?

What does the FOR statement look like in terms of `First`?

PROGRAM Midterm; VAR inpChar, First : char; sum, J : integer; BEGIN sum := 0; writeln; writeln; writeln; writeln('Enter n consecutive digits, the first indicates how many'); read(First); FOR J := 1 TO (ord(First) - ord('0')) DO BEGIN read(inpChar); sum := sum + ord(inpChar) - ord('0'); END; writeln('Sum = ', sum); END.

**N.B.**: you can find a better version here.

2. (10 points.) What does the following produce?

PROGRAM Test1 VAR J:integer; BEGIN FOR J:=1 TO 5 DO writeln(J:J, J:J) END.

Hint when J is 1, what is the value of ` J:J, J:J`, what does the ` :J` part
indicate?

11 2 2 3 3 4 4 5 5

3. (15 points) In the following, state the type and value of each of the following expressions.
If the expression contains an error, write * invalid* as the type and omit the value.

EXPRESSION TYPE VALUE 200.0 div 4.0 invalid_ ________ { "div" only for ints } 3 mod 4 * 3 div 2 - 5 mod 2 integer_ 3_______ (5 + 4) mod (1 + 2) + 5 / 5 real____ 1.0_____

4. In the parts (a) and (b), assume that all the variables are ` INTEGER`.
Given the following input:

13 24 4 6 8 6 3 5 7

(a) (5 points) What will be assigned to A, B, C, D, and E in:

Readln(A, B, C, D); read(E);

A = 13 B = 24 C = 4 D = 6 E = 6

(b) (5 points) What will be assigned to A, B, C, D, and E in

Read(A, B, C, D); read(E)

A = 13 B = 24 C = 4 D = 6 E = 8

(c) (5 points) What will be assigned to A, B, C, D and E in

readln (A, B, C, D, E)

if all these variables are declared as ` Char`?

A = '1' B = '3' C = ' ' D = '2' E = '4'

5. (5 points) Given:

var silly : integer ;

Which of the following causes the number stored in ` silly` to be printed.
(circle one)

a) writeln ( silly ) ; b) readln ( silly ) ; c) writeln ( 'silly ' ) ; d) readln ( 'silly' ) ;

a)

6. (5 points) Given:

var answer1, answer2 : ___________ ; begin writeln( 'Enter both answers, one per line' ) ; readln( answer1 ) ; readln( answer2 ) ; end.

Fill in the blanks so that no errors occur if the user types:

3 4.0

real

7. (20 points) How many times would the FOR-DO loops beginning with
the following statements be executed?

0____ a. FOR J:= 4 DOWNTO 5 DO 5____ b. FOR J:= 3 DOWNTO -1 DO 0____ c. FOR CH:= 'D' TO 'A' DO 8____ d. FOR J:= -4 TO 3 DO 3____ e. FOR CH:= '3' TO '5' DO