Back 

Programming constructs questions and answers

Questions

Q1. State the three programming constructs.
Q2. Give an example of the sequence construct.
Q3. Give an example of the selection construct.
Q4. Give an example of the iterative construct.
Q5. What is meant by a nested construct?
Q6. Give an example of a nested IF construct.
Q7. Give an example of a nested FOR construct.
Q8. What is the difference between how a FOR, WHILE and REPEAT construct works?
Q9. What is meant by an infinite loop?
Q10. How do you avoid an infinite loop in a WHILE construct? 

Answers

Q1. The three programming constructs are sequence, selection and iteration (repetition).
Q2. An example of sequence is:

INITIALISE Variables
WRITE ‘Please enter the name of student’
INPUT Name
WRITE ‘Please enter the exam mark of student’
INPUT ExamMark
PRINT Name, ExamMark

Q3. An example of selection is:

INPUT letter using keyboard
IF (Letter entered = P) THEN
     Do the code in here - call it block A
ELSE
     Do the code in here - call it block B
ENDIF

Q4. An example of iteration is:

TOTAL=0
REPEAT
BEGIN
     READ VALUE
     TOTAL=TOTAL+VALUE
END
UNTIL (TOTAL > 1000)

Q5. A nested construct is where you have one construction inside another one. For example, you might have a FOR loop inside another FOR loop, or an IF construction inside another IF construction.

Q6. This example uses nested IF statements.

INPUT ExamMark
IF (ExamMark < 50) THEN
     PRINT "You have failed."
ELSE
     IF (ExamMark < 60) THEN
          PRINT "You have passed."
     ELSE
PRINT "You have passed with a merit."
     ENDIF
ENDIF

Q7. This example uses nested FOR statements. It prints out a table of @ signs with 10 rows and 5 columns.

FOR row = 1 TO 10 DO
     FOR column = 1 TO 5 DO
          Print (‘@’)
     ENDFOR
ENDFOR

Q8. FOR loops are done a fixed number of times. REPEAT and WHILE loops are repeated a variable number of times, depending upon the result of a conditional test. REPEAT loops are always carried out at least once because the test is at the end of the construction. WHILE loops may never happen at all because the test is at the beginning of the loop.
Q9. An infinite loop is one where you enter a loop of code but cannot leave it.
Q10. An infinite loop is caused by the variable that is tested in the conditional test of the loop never being altered in the body of the loop. For example,

TOTAL = 0
TEMP = 0
WHILE (TEMP < 1000)
BEGIN
     READ VALUE
     TOTAL=TOTAL+VALUE
END

Back