Jamaica Gleaner

Control structures

- Natalee A. Johnson Urquhart CONTRIBUTO­R

GOOD DAY, students. This is lesson 26 in our series. In this week’s lesson, we will continue to look at control structures and flow charts.

THE WHILE LOOP

The ‘while’ loop structure is shown below:

‘While’ variable not equal to Control_VariableDo Block Statement(s) Endwhile The ‘while’ loop is an example of an indefinite loop (unbounded loop); it facilitate­s the repetition of a block of instructio­ns until a certain condition is met. No one knows exactly how many times the block statements (instructio­ns) will be carried out. Using the same example of having a bowl of ice cream with jello, no one can tell how many scoops you would take that will fill your stomach. It depends on the size of your stomach and the size of the spoon. The algorithm would look something like this:

EXAMPLE 1

The ‘while’ loop structure can have a pretest and post-test to help with the execution of the loop, while in some instances, the ‘while’ loop will continue to execute until the condition is met (considered to be bounded). Please note: you use the WHILE LOOP when you do not know exactly how many times a block of statements will be carried out. In this case, there will be some terminatin­g condition.

EXAMPLE 2

Write a pseudocode algorithm to read a set of integer numbers terminated by 999. The pseudocode should find the sum and average of the numbers. The algorithm should also output the sum and average of the numbers. PSEUDOCODE VERSION Algorithm Sum_and _Average This program will read a set of integer numbers and calculate the sum and average of the numbers, and output the sum and average of the numbers.

AN EXAMPLE OF A BOUNDED ‘WHILE’ LOOP

This ‘while’ loop will continue to execute as long as sum is less than a 1,000. In this case, no pretest or post-test is necessary.

FLOW CHART VERSION FOR FIRST EXAMPLE FLOW CHART VERSION FOR EXAMPLE 2 THE ‘REPEAT-UNTIL’ LOOP

The ‘repeat-until’ loop is similar to the ‘while’ loop, except the condition is tested at the end of the loop (post-test). Thus, the block of statement (s) will continue to execute as long as the specified condition in the UNTIL statement is true. Using the same example of having a bowl of ice cream and jello, you would continue to have your ice cream and jello as long as you have ice cream in your bowl. The ‘Repeat-Until’ loop structure is shown below:

REPEAT

Block Statement (s) UNTIL

EXAMPLE 1 EXAMPLE 2 PSEUDOCODE AND FLOW CHART VERSIONS

We have come to the end of this lesson. Remember, if you fail to prepare, you prepare to fail. Natalee A. Johnson Urquhart teaches at Ardenne High School. Send comments to kerry-ann.hepburn@gleanerjm.com.

 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??

Newspapers in English

Newspapers from Jamaica