REPETITION STRUCTURES
Repetition or Loop or Iteration structures allow statements to be repeated a fixed number of times or until some condition evaluates to false.
There are three repetition constructs:
- FOR Loop - counted loop
- REPEAT Loop - conditional loop
- WHILE Loop - conditional loop
‘FOR’ LOOP CONSTRUCT
The FOR loop construct syntax:
FOR <counter> = <start value> TO <end value> DO
{Statements}
ENDFOR
e.g. FOR X = 1 to 10 DO
{Statements to be executed}
ENDFOR
NOTE: The FOR loop is used when the required number of iterations (loops) is known beforehand.
Some other simple examples include:
FOR x = 1 to 100 DO
Print (‘I must not sleep in class’)
ENDFOR
|
FOR weekday = 1 to 5 DO
Print(‘Go to school’)
ENDFOR
|
FOR age= 13 to 19 DO
Print(‘You are a teenager’)
ENDFOR
|
FOR x = 1 to 12 DO
y = x * 2
Print(x,’ times 2 = ‘,y)
ENDFOR
|
FOR num = 1 to 20 DO
Print(‘The number is: ‘,num)
ENDFOR
|
Saturday = 2
Sunday = 3
FOR day = Saturday to Sunday DO
Print(‘It is the weekend’)
ENDFOR
|
Eg.) A man works 40 hours per week and he is paid an hourlyrate of $50.00 per hour. Construct pseudocode algorithm and flowchart to read the names and hours worked for 10 employees.
Determine and print their weekly wages along with their names.
Answer
Start
FOR x = 1 to 10 DO
Print (‘Please enter a name and hours worked’)
Input Name, Hours
Set Wage to Hours * 50
Print (Name,’ $’,Wage)
ENDFOR
Stop
Eg 2.) Write a pseudocode algorithm to print a conversion tableto convert miles to kilometres. The table ranges from 5 to 100 miles in steps of 5 [1 mile = 1.161km].
Answer
Start
FOR x = 1 to 100 DO STEP 5
km = x * 1.161
Print(x,’ miles = ‘,km)
ENDFOR
Stop
Comments (0)
You don't have permission to comment on this page.