• Unit 8:CONTROL STRUCTURES AND ONE DIMENSION ARRAY

    Key Unit Competency
    By the end of the unit, you should be able to:
    • Derive logic in algorithm which include control statements.
    • Handle one dimensional array in algorithm.

    Unit Outline
    • Conditional logic.
    • Control structures.
    • One-dimensional array.

    Introduction
    Control structures are statements or symbols used in algorithms to represent the logical flow or order in which program statements are to be executed. In this unit we will begin by describing conditional logic that is fundamental to control structures. Later, we demonstrate how three control structures namely sequence, decision and iteration are used in algorithms. Before closing the unit, we discuss one of the elementary data structures known as one-dimensional array.

    8.1 Conditional logic
    In everyday life we use statements like If I had the time and the money I would go buy a tablet and learn how to use it. Such a statement is a conditional logic implying that certain conditions must be satisfied for an action to be taken. Therefore, a conditional logic is a proposition formed by combining two or more facts using the words like if, case and then. The conditions in the if statement are combined using logical links like: and, or and not.

    8.1.1 Simple conditional logic
    Simple conditional logical requires only one fact for an action to be taken, hence
    statements do not require use of logical links like and, or and not. For example, the
    following statement is a simple conditional logic because it only requires participation
    in class for the teacher to take action:

    8.1.2 Compound conditional logic
    Compound conditional logic make use of logical links to combine several facts for an action to be taken. For example, the following statement requires two conditions to be fulfilled for the teacher to take action:
    • The teach promises that if “you are always punctual”” and “participates in class” then “you will get five extra points” This statement implies that the teacher can only award five extra points (true) if a student is always punctual (true) and participates in class (true). In Mathematics, facts and actions can be represented using symbols in a table as shown in Table 8.1.

    Conditions linked with AND logic requires an action to be taken only when all conditions
    are true. For example, the third column in Table 8.1 above shows that the two conditions
    must be true (T) for the teacher to award a student five extra points. The table also
    shows four other possible outcomes depending on the true/false value of p and q.

    Conditions linked with an OR logic lead to an action when either one or both are true.
    For example, the teacher may decide to awarded five points if a student is punctual or
    participates in class. This statement can be represented using OR logic in a table as
    shown in Table 8.2.

    In algorithm design, there are many occasions conditional logic is required when
    alternative actions are to be considered. In the next sections on control structures, we
    demonstrate how to express conditional logic using relational and logical operators.

    For example the flowchart extract of Fig. 8.1 and equivalent pseudocode demonstrates
    use of conditional logic to check if a person is an adult.

    8.2 Control Structures
    Control structures (statements) refer to a conditional logic that determines the flow
    of an algorithm or execution of a program. The three types of control structures
    discussed in this unit are sequence, selection and looping.

    8.2.1 Sequence Control Structure
    Sequence control structure refers to logical flow of statement one after another in the
    order in which they are written. This means that algorithms designed using sequence
    control do not depend on evaluation of a conditional logic. The pseudocode shown in
    Fig. 8.2 illustrates sequence control in which two numbers are first entered before sum
    and product are calculated and displayed on the screen.

    Activity 8.1: Sequential control structure
    1. Formulate an algorithm that would prompt a user to enter the length and width of a rectangle. The program then calculates and displays the area and perimeter.

    2. Study the flowchart of Fig. 8.3 below and explain why the algorithm represents
    a sequence control structure.

    8.2.2 Selection Control Structure
    Selection control structure also known as decision control statement is a conditional
    logic used when there is one or more alternatives to choose from. If a selection
    statement provides several alternatives to choose from, we refer to such as a statement
    as case selection. The four types of selection control structure are if ...then, if...else,
    nested if and switch/case.

    8.2.2.1 If …then selection
    The if…then is a conditional logic used to test whether the condition is true before an action is taken. If the condition is true, the statement in the body of if statement is executed; otherwise nothing happens if false. The general syntax of if..then is expressed as follows:
                     If condition is true then
                         Do Task-A

    For example, in the following statement, if...then condition tests whether mark is 80 and above. If the condition is true, the statement distinction is displayed on but this case, if the condition is false, nothing happens:
                           If mark >= 80 then
                           PRINT “distinction”

    One important application of if…then selection is to validate user input. For example, the Fig. 8.4 shows a flowchart with if … then selection used to test whether a number entered is less than zero. If the number is negative, the algorithm displays invalid mark.

    Explanation
    1. Once the user enters a mark, the algorithms checks whether the input is less than
    zero.
    2. If true then statement ‘invalid mark’ is displayed, otherwise nothing happens.

    8.2.2.2 If ... else selection
    If … else selection is suitable when there are two available options. In general the
    format of if... else statement can be represented as:

    Explanation
    The Boolean expression within If....then statement is first evaluated. If true, statement 1 is evaluated otherwise statement 2 is evaluated if the condition returns false. For example, Fig. 8.5 (a) and (b) shows the flowchart and pseudocode for checking voters eligibility depending on age. If a person is 18 years and above, the expression returns true and displays “Vote” else if a person is below the set age limit, the program displays “Do”.

    Activity 8.2: If ... else selection
    1. Draw a flowchart for a program that reads two numbers and displays the larger
    of the two numbers. The algorithm should use IF...ELSE selection to compare
    the two numbers.
    2. Study the flowchart shown in Figure 8.6 below and state the value of Z if the
    following values of x and y are entered by the user:
    (a) X = 20, Y = 10
    (b) X = 19, Y = 20

    8.2.2.3 Nested IF
    Nested IF selection is used where several options have to be considered to make a
    selection. The general format of the Nested IF is:

    Explanation
    1. The statement first evaluates if the condition is true. If true, the statement is executed.
    2. If the first condition is false, the else if statement is evaluated. This continues until the else statement is encountered.
    Note that in nested if selection, the last statement must be within else that executes the statement if the boolean expression returns false. When drawing a flowchart, if there are n options to select from, the number of diamonds representing IF should be n-1. For example, Fig. 8.7 shows an algorithm for a program that takes current date (Todate) and date of birth. Depending on the current date, the algorithm computes age used to classify the people into categories shown in table on top-right side.

    Explanation
    1. The user first enters a person’s date of birth (DoB) and the current date (ToDate) that are used to calculate age.
    2. Based on age, the algorithm uses nested if to assign the person to one of the categories (cat) defined in the table on the right. For example, if age <1 as indicated in the first decision symbol, cat is assigned to kid using the statement: cat = kid;
    3. The algorithm displays category of the person in the output symbol. For example, if cat is assigned to kid, the output symbol displays Grown up.

    Activity 8.3: Nested If selection
    Fig. 8.8 shows an algorithm for a program that would be used to accept three numbers A, B and C, compare them and display the largest of the three. Co n v e r t the flowchart to a pseudocode.

    8.2.2.4 Switch/Case selection
    An alternative to nested if selection is use of switch/case selection control. The following algorithm represents the general syntax of a switch statement.

    For example, the pseudocode of Fig. 8.9 shows a sample selection of menu items in
    a hotel implemented using switch selection.

    Explanation
    1. The procedure accepts a number as input.
    2. The switch statement checks if the input is number 1, 2 or 3. For example, if
    number is 3, it displays “My choice is coffee”.
    3. If the number entered does not fall within the three numbers, the DEFAULT
    statement is executed.
    To demonstrate further use of switch/case selection, Fig. 8.10 shows a flowchart used
    to determine discounted price of products depending on the item code. For example,
    if the product code is B123, its prefix B means that it belongs to category B. Note
    that each category is used to determine the rate used to discount the cost of an item.

    Activity 8.4: Switch/case selection
    A school intends to develop a computer program that automates processing of computer science exam grades as follows:
    • 70 – 100                 A
    • 60 – 69                   B
    • 50 – 59                   C
    • 40 – 49                   D
    • Below 40                E
    Design a flowchart that expresses selection logic for a program that assigns grades
    as per grading system above.

    8.2.3 Looping control Structure
    The looping control structure, also referred to as iteration or repetition, causes the program to repeatedly execute statements within the loop until the condition is false. For example, consider repetitive task that occurs during shopping represented by the following natural language algorithm:

    This algorithm describes a common practice of buying items in a retail outlet. The statements under the WHILE keyword indicate that a buyer continues picking items until the shopping list is exhausted. The keyword END WHILE shows that it is after picking all the items from the shopping list the buyer stops and proceeds to make payment at checkout counter.”

    8.2.3.1 FOR Loop
    For loop is a looping statement used to evaluate a condition before executing statement in the body of the loop. The for loop can be represented using the following general syntax:
           FOR variable = lowerlimit TO upperlimit DO
                           statements;
           END FOR

    For example, the pseudocode of Fig. 8.11 shows how to use the FOR loop to design a program that displays the first 20 positive integers and their sum. Note that, as long as the lower limit is less than the upper limit, the number is added to sum and the count incremented by 1 until the lower limit is equal to or greater than the upper limit.

    Explanation
    1. The algorithm set initializes sum with zero.
    2. The for loop sets the initial count to zero and maximum to 19 i.e number < 20.
    3. In every loop the premium sum is updated by adding a number.
    4. The for loop is existed once the maximum count is reached.

    Activity 8.5: For loop
    A class of ten students took a quiz in computer science. Using the FOR loop, formulate an algorithm that would be used to compute cumulative total and mean score of the class.

    8.2.3.2 WHILE Loop
    Like the FOR loop, WHILE loop first evaluates the condition before executing the body of the loop. Therefore, While loop executes statements zero or more times. The general syntax of a while loop can be expressed using the following pseudocode on the left or flowchart of Fig. 8.12 on the right.

    For example, in a commercial bank, a customer may be allowed to withdraw money
    through the ATM if the minimum balance is over RWF500 otherwise a message
    “Insufficient funds” is displayed. Assuming for each transaction the minimum
    withdrawable amount is 100, the control logic shown in Fig. 8.13 would be used to
    enforce the business rule.

    Explanation
    1. The algorithm shows that the user first enters withdrawal amount. For example, if the user enters 2000, the conditional logic “if amount % 100 = 0” checks whether dividing the amount by 100 returns 0 as the remainder is 0. If the expression returns false, the algorithm displays a message “Try again” before prompting the user to re-enter amount. If true, the algorithm proceeds to check whether the current balance (bal) is above 500.
    2. If the condition bal>500 returns false, the algorithm prints a message “Insufficient funds” before exit.
    3. If the current balance is above 500, the algorithm proceed to the next step of debiting the account using the statement: bal = bal - amount
    4. Finally, the algorithm displays withdrawal receipt on the screen.

    Activity 8.6: While loop
    In groups, formulate an algorithm for automatically counting the number of times an electric fence alarm beeps. Once the number of beeps reaches 20, the system triggers a remote siren that alerts the security firm to send emergency response team. The looping control logic for counting beeps should represented designed with a while loop.

    To further demonstrate application of while loop, let’s look a problem of determining whether a calendar year such as 2016 is a leap year. Fig. 8.14 shows a flowchart for a program that would be used to receive a valid year, verify whether it is a leap year, and then print the result such as year 2016 is a leap year. Note that a leap year has 366 days and it is divisible by 4 except for years that are exactly divisible by 100. Years such as 2000 that are divisible by 100 and 400 are leap years.

    Explanation
    1. The user enters a valid year or 9999 to quit the algorithm. For example, if the user enters 2016, “if Year%100 = 0” checks whether the remainder is 0 after dividing the by 100.
    2. If the expression returns true, year% 400 is evaluated otherwise if false, year%4 is evaluated. In both cases, Rem (remark) is assigned to Leap using the statement:
    Rem = Leap;
    3. If after dividing by 100 returns a non-zero value, Rem is assigned to NotLeap using the statement:
    Rem = NotLeap;
    4. The algorithm displays Leap or NotLeap remark in the output symbol depending
    on the result of the assignment statement.

    8.2.3.3 Repeat ...Until Loop
    Repeat … Until control is similar to the while loop except that the statement is executed at least once. For example, Fig. 8.15 shows a pseudocode used to convert an integer number in base 10 to binary numbers represented by zeros and ones.

    Explanation
    1. The pseudocode starts with declaration of three variables that are initialised to zero.

    2. Once the user enters a number like 25, the algorithm uses reat ... until loop to repeatedly divide the number by 2 for example, 25 DIV2 returns 12.
    3. The statement Number Mode 2 returns the remainder of integer division. For example, 25 Mod2 returns 1.

    Activity 8.7: Repeat until loop
    1. Revisit the algorithm in Activity 8.6 and represent it using REPEAT.. UNTIL loop.
    2. The flowchart of Fig 8.16 represents a program that would be used to compute sum of 50 integers. Study the algorithm and express loop construct using pseudocode.

    8.2.4 Finite and Infinite Loops
    A finite loop repeatedly executes a set of instructions until a specific condition is met. On the other hand, an infinite loop (endless loop) continue looping indefinitely due to a condition that is never met. To force such a loop to terminate, you may have to forcefully shut down the computer or close a program by pressing a combination of keys such as Ctrl+C. For example, Fig. 8.17 shows an infinite loop in which the value of x is reset to 1 hence the condition x<5 holds forever.

    Explanation
    1. This section of an algorithm starts by initialising x to 0.
    2. Once the algorithm enters the while loop the value of x is replaced with 1 then x + 1. This means what the value of x before printing is 2.
    3. The algorithm prints X and then checks the condition to compare x (i.e. 2) with
    5. Because 2<5, the algorithm enters the loop again. The value of x is reset to 1 then incremented to 2 and the looping continues.

    Activity 8.8: Finite and infinite loop
    A college offers a course that prepares students for a motor vehicle driving test. In the previous month, twenty of the students who completed this course took both theory and practical tests. To keep record of test results, you have been asked to develop an algorithm using the following specifications:
    • Prompt the user to enter driving test results for each student with a comment pass or fail.
    • The algorithm displays a summary of the test results indicating the number of students who passed and the number who failed.
    • If more than 85% of the students passed the test, the program displays a message “give commission to instructors!”
    1. Carefully read the problem statement and identify the input, processing and output requirements.
    2. Using top-down, stepwise refinement, state the conditional logic of the problem and represent the solution as a pseudocode or flowchart.

    8.2.5 Break and Continue Statements
    Although a loop performs a set of repetitive task until a condition is met, sometimes it is desirable to skip some statement inside a loop or prematurely terminate the loop. In such cases, break and continue statements are used.

    8.2.5.1 Break statement
    A break statement is used to force immediate exit from a loop or selection statements.
    The statement is normally used with if statement such as the one shown in Fig. 8.18.
    Once the condition is encountered the program flow is transferred to the next statement following loop or selection statements.

    Explanation
    1. The for loop initializes count to 1 and then sets the upper limit to 10.
    2. Once the loop encounters 5, the break statement causes the algorithm to exit the
    loop and print numbers 0, 1, 2, 3, 4 and 5. The numbers after 5 are ignored.

    8.2.5.2 Continue statement
    The continue statement is used in looping to skip the remaining statements in the body of the loop and perform the next iteration. Like the break statement, continue statement is also used with if statements to specify the condition as shown in Fig. 8.19.

    Explanation
    1. The for loop initializes count 1 and then sets the upper limit to 10.
    2. Once the loop encounters 5, the continue statement causes 5 to be ignored.
    3. The algorithm prints the values 1, 2, 3, 4, 6, 7, 8, 9, 10 before exiting the loop.

    Activity 8.9: Break and continue
    1. To test if a number n is a prime number, we could loop through 2 to n - 1 and test whether each number divides exactly into n giving a remainder of zero. Formulate an algorithm for a program that tests if the given number is prime number. The logic should use a loop and break statements to test the use input.
    2. Develop a pseudocode for a program that accepts positive integers starting from zero. If the number is less than zero, program should print an error message and stop reading numbers. If the number is greater than 100, the program ignores the number and transfers control to the next iteration.

    8.2.6 Goto Statements
    Goto is a jump statement that alters the flow of execution to a section of an algorithm or program identified by a goto label. Let’s take an example of an algorithm that would continue to prompt the user for a password until he or she enters secret as the password (Fig. 8.20). To repeat the prompt, a label named “again:” is placed at the start of the pseudocode shown below. If “secret” is not entered the algorithm uses the goto statement to go to again label to repeat the prompt.

    Note that although a goto statement is an easy method of controlling flow of execution, it is considered as bad program design practice because it can cause logic errors that may be difficult to detect especially in complex programs.

    8.2.7 The Exit Statement
    The exit statement may be used in algorithm design to indicate a point at which a program may terminate prematurely during processing. For example, the flowchart shown in Fig. 8.21 shows that once the user enters a number, the exit statement is evaluated. If exit is true, the program terminates without adding the number to sum.

    Assessment Exercise 8.1
    1. Differentiate between selection and iteration control structures.
    2. Explain the importance of the following selection statements:
    (a) IF..THEN
    (b) Nested IF
    (c) SWITCH
    3. Explain three types of looping control structures. Support your answers with
    illustration.
    4. Design an algorithm for a program that would be used to compare three numbers
    x, y and z, and then display the least among the three.
    5. State four types of selection control structures supported by most structured
    programming languages.
    6. Study the income taxation brackets used by Rwanda’s revenue authority and
    draw a flowchart for a program that would be used to compute tax payable by an
    employee depending on marital status and monthly income.

    8.3 One-Dimensional Array
    A one dimensional array is a group of contiguous memory locations identified by the same name for storing data the same type. An array can be one dimension such as a list of items, two dimension such as a table or matrix. To make the concept of array clear, let us consider an entertainment hall that has capacity of 100 seats, 10 in each row. Suppose you and your friends would like to seat together along one row. The reserving one row of seats in an entertainment hall is equivalent to one-dimensional array. To access a particular element in an array, we specify the name of the array and the position number (index or subscript) of the element. A subscript is a position number that must be an integer or an integer expression. It is important to note that reserving too much memory location that are not likely to be occupied leads
    to memory wastage. Table 8.3 shows an integer array called Scores containing 10 elements identified by indexes 0 to 9.

    Note that each of the score elements may be accessed by giving the name of the array
    i.e. Scores followed by the index of the element for example, Scores [5] returns the sixth element that holds 45 because counting starts from 0.

    8.3.1 Declaration of Arrays
    An array occupy space in memory. Therefore, declaring an array is the same as declaring other variables only that a computer reserves contiguous memory locations enough to store the number of elements. The general syntax of declaring an array is:
    • Arrayname: Array [elements] of datatype e.g.
    • Scores: Array[10] of integer;

    Once the Scores array is declared, the computer sets aside ten memory locations for
    storing integers such as 65, 50, 19,30,20,45,60,89,55, and 72 shown earlier in Table 8.3.
    Regardless of language used to implement arrays, the following are factors that need to be considered.
    • Array name: Decide on a suitable array name that indicates several elements
    are to be stored e.g. scores.
    • Data type of elements: An array can only hold elements of the same data type.
    Size of array: The size of an array determines the maximum number of values that an array will hold.
    • Dimension: An array can be one-dimensional list or multidimensional such as a table (matrix).

    Activity 8.10: One dimensional array
    Study Table 8.4 that shows graphical representation of two arrays:

    1. Determine each array name, data type and number of elements stored in each array.
    2. Using section of a pseudocode, write a sample declaration for each array.

    8.3.2 Array initialization
    Initialization refers to assigning an array initial values during declaration. For
    example, elements of an array can be initialized during declaration by assigning them
    to comma separated list as follows:
    Scores: Array[10] = {34, 20, 45, 87, 92, 21, 43, 56, 12, 15}
    The statement first declares an array of 10 elements and then initializes each element
    with values enclosed in (curly) braces.

    8.3.3 Accessing Array Elements
    In arrays, an element can be accessed by specifying the array name and the location (index) of the element. For example, to access the first element (index 0) in an arraynamed scores, use scores [0]. Once you access the element, you can then read or write a value into it.

    8.3.3.1 Reading array elements
    To store (read) a value into an array, you need to know the name of the array and the index of the element. Then a READ function may be applied to the element. For example READ Scores [4] stores a value in the fifth location of the score array. Multiple values may be read into several elements using a FOR loop as shown in Fig. 8.22.

    Explanation
    1. The scores array is set to store 10 elements of integer type.
    2. The for loop uses index as a counter to continously store ten elements 0 to 9.

    3. The for loop is eliminated once the ten elements have been read into the array.

    8.3.3.2 Writing Array Elements
    To write (display) elements from an array, use a write function together with the arrayname and location (index) of the element. To display a single value of an array you must provide the array name and index to the write operation. For example, the value in Scores [1] may be displayed by using PRINT Scores[1] . To display multiple values such as the 10 elements in the Scores array, use the FOR loop by setting the initial value to 0 and the upper limit to 9 as shown in Fig. 8.23 below:

    Explanation
    This for loop is used to display 10 elements from the scores array. The index is incremented by 1 until the ten elements are displayed.

    Activity 8.11: Array of integers
    Thirty students were asked to rate quality of the food in the student cafeteria on a scale
    of 1 to 5 (1=poor, 2=fair, 3=neutral, 4 =good, and 5=excellent). Write a pseudocode for a program that places the 30 responses in an array of integers and summarizes the results of the poll in terms of counts and percentages.

    Assessment Exercise 8.2
    1. Declare a one-dimensional array that represents a fleet of 25 buses numbered from 100 to 125.
    2. The following is a list of numbers representing customers waiting to be served in a banks: 64, 25,69, 67, 80 and 85.
    (a) Define an array named Customers and initialize it with the waiting list numbers.
    (b) Develop an pseudocode for reading and writing the elements into customer array.
    3. Formulate an algorithm that converts numbers from base 10 to binary and store the binary digits in an array and correctly displays the binary number.
    4. Study Fig. 8.24 representing a pseudocode fragment for printing elements from and array. Identify possible errors and explain what happens if the error(s) are not corrected.

    Unit Test 8
    1. Differentiate between nested IF and switch/case selection.
    2. Explain the importance of the following looping control statements:
    (a) WHILE
    (b) FOR
    (c) REPEAT...UNTIL
    3. Explain at least two reasons that would make a program to infinitely repeat execution of a loop. How can such undesirable behaviour be resolved?
    4. Using illustrations, differentiate between a one-dimensional array and a matrix.
    5. State four factors that need to be considered when declaring a one-dimensional array.
    6. The Fig 8.25 below shows the faces of six-sided die with each side marked with dots representing faces 1 to 6. To generate random numbers, a player rolls a single die 6000 times and the frequency of each face that appears is stored in an array. Formulate an algorithm that would be used to count frequency of each face in an array.

    Unit 7:INTRODUCTION TO COMPUTER ALGORITHMUnit 9:INTRODUCTION TO COMPUTER PROGRAMMING