1.1 Fundamental Control Structures All algorithms, no matter how complex, can be reduced to combinations of three fundamental control structures which are independent of the programming language. 1. SEQUENCE structure One operation, or a group of operations, is performed one after another 2. SELECTION structure A condition is tested to determine which steps are to be performed next. Different operations are performed depending on whether the condition tested was found to be true or false. 3. REPETITION A series of steps is repeats. In a conditional loop, the steps are repeated as longs as a certain condition is true. In a counting loop the steps are repeated for a predetermined number of times. 1. Sequential Blocks 2. Branch (or selection) block 3. Repetition( or Loop) block Why are the three basic control structures special and what other control structures are useful? If we could select our own control structures, the following criteria would apply: 1.1.1 Criteria for choosing a control structure are: 1. Minimality The idea of minimality is that we choose the minimal amount of the simplest structures that we need. 2. Standardisation It is desirable to have program structures that have the same external interface. Programs can then be constructed by assembling these components. The three constructs have only one entry point at the top and one exit point at the bottom so they can be “plugged” easily together 3. Clarity and expressive power When choosing control constructs we need a large enough range to allow us to express clearly what we want the program to do. For this reason C and Java provide us with do-while and for statements as well as while statements for repetitions and the switch statement which can be used as an alternative to an if-else ladder selection. A balance is needed between minimality and the need for expressive power 4. Abstraction This is one of the most important ideas in structured programming. To allow us to understand a complex system, it is necessary to be able to express components of the system as a hierarchy of interconnected black boxes whose implementation details is hidden at each level. 1.1.2 Sequence structure The sequential structure consists of steps that are performed sequentially. The figure below represents the flowchart and pseudocode of a sequence structure with three tasks. Flowchart Task 1 Task 2 Task 3 Pseudocode BEGIN Task 1 Task 2 Task 3 END In the pseudocode the keywords BEGIN and END mark the beginning and end points of the structure. The operations performed in the sequence structure are usually input, output and computations. Assignment Statements In pseudocode assignment is indicated by a left arrow (), for example: Algorthim: Assign the product of PI, radius and height to the variable area” In pseudocode this would be written as follows: area PI * radius * height The flowchart would be area = PI * radius * height Input Statements In pseudocode Input Statements are specified by the word READ, for example: READ radius, height The flowchart would be READ radius, height Ouput Statements In pseudocode Output Statements are specified by the word PRINT, for example: PRINT “Area = “, area This pseudocode prints a message followed by the value of the variable area. The flowchart would be PRINT “Area = “ area 1.1.3 Selection structure The selection structure tests a condition to determine which steps are to be performed next. The two forms of selection structure are . Open Branch - Basic IF Structure IF is followed by directly by statement or set of statements which is only executed if the condition tested is true Flowchart Pseudocode true false condition IF condition True alternative task ENDIF true alternative task Closed Branch - IF-ELSE Structure In a closed branch, the flow of the program always goes forward to new information and the program will do one of two options. If the condition tested is true one set of operations will be performed. If the condition tested is false, the other set of operations is executed. Flowchart false false alternative task Pseudocode true condition true alternative task IF condition True alternative task ELSE False alternative task ENDIF Example of Open Branch Step 3of the following Algorithm to calculate the absolute value of a number. Read in the number Check the sign of the number If the number is negative, then multiply it by -1 Print the absolute value of the number The flowchart and Pseudocode are as follows: Flowchart false number < 0? Pseudocode IF number < 0 true number number = (-1) * number (-1) * number ENDIF Example of Closed Branch Step 3of the following Algorithm to calculate the absolute value of a number. 1. Read in the number 2. Check the sign of the number 3. If the number is greater than or equal to zero proceed to step 4, otherwise, print a message and stop; 4. Compute the square root of the number. 5. Print the number and the square root on the monitor The flowchart and Pseudocode are as follows: Flowchart false Pseudocode true x >= 0 ? PRINT “Number is negative” y = sqrt(x) IF number >= 0 y sqrt (x) ELSE PRINT “Number is negative” ENDIF IF-ELSEIF Structure and the CASE SELECT Structure Structures used for multiple choice decisions: Flowchart for IF ELSEIF Structure condition 1 true Pseudocode for IF-ELSEIF fasle condition 2 false task1 true false condition 3 task 2 true IF condition 1 Task1 ELSEIF condition 2 Task 2 ELSEIF condition 3 Task 3 ELSE Default task ENDIF Invalid Selection task 3 Flowchart for CASE SELECT Structure Pseudocode for CASE SELECT SELECTION CHOICE1’ YES NO CHOICE2 NO ACTION 1 YES NO CHOICE3 ACTION 2 YES ACTION 3 Invalid Selection SWITCH selection CASE choice 1 Task1 CASE choice 2 Task2 CASE choice 3 Task3 DEFAULT Default task ENDCASE 1.1.4 Repetition structure 3 types of loops: 1. The while Loop 2. The do while Loop 3. The for Loop WHILE Loop Flowchart condition Pseudocode false WHILE condition Tasks ENDWHILE true Tasks DOWHILE Loop Flowchart Pseudocode Tasks DO Tasks WHILE condition condition true false FOR Loop Flowchart Pseudocode Initial Task false condition End task initial task FOR condition DO Tasks ENDFOR end task true Tasks FOR control variable {FROM start} TO finish {INSTEPS OF value} D Tasks ENDFOR Flowchart initialise index condition increment index false true Tasks ADVANTAGES OF USING FLOWCHARTS The benefits of flowcharts are as follows: 1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned. 2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way. 3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes. 4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase. 5. Proper Debugging: The flowchart helps in debugging process. 6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part LIMITATIONS OF USING FLOWCHARTS 1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy. 2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely. 3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem. 4. The essentials of what is done can easily be lost in the technical details of how it is done. 2. Exercises Exercise 1: Draw the flowchart and give pseudocode for the following algorithm: Algorithm: 1. Read in the number 2. Check the sign of the number 3. If the number is negative, then print a message and stop; otherwise, proceed to step 4; 4. Compute the square root of the number. 5. Print the number and the square root on the monitor Exercise 2: Draw the flowchart for the following algorithm: Algorithm: 1. Input the radius into variable Radius. 2. Input the angle into variable Theta. 3. Compute the arc length from and save the result in the variable ArcLength. 3.1 Assign the product of PI, Radius and Theta divided by the value 180 to the variable ArcLength 4. Compute the sector area and save the result in the variable SectorArea 4.1 Assign the product of ArcLength and Radius divided by the value 2 to the variable SectorArea 5. Print the values ArcLength and SectorArea on the monitor 5.1 Print the value of the variable ArcLength on the monitor 5.2 Print the value of the variable SectorArea on the monitor 3. Examples Example 1: Draw the flowchart for the following algorithm for a program to compute the gross salary for an employee given the number of hours worked and the hourly rate. If the number of hours worked is greater than 40, the hourly rate shall be 1.5 times the normal hourly rate for all overtime hours. The program should print the number of overtime hours, the regular salary, the overtime salary, and the gross salary for the employee : PROGRAM ANALYSIS: The main functional requirements are as follows: Read in the number of hours worked and the hourly rate Determine if the number of hours worked is greater than 40 Calculate the gross salary if hours worked are less than or equal to 40 Calculate the gross salary if hours worked are greater than 40 Print out the number of overtime hours, the regular salary, the overtime salary, and the gross salary for the employee Input Data: number of hours worked (float) hourly rate (float) Output Data: number of overtime hours (float) regular salary (float) overtime salary (float) gross salary (float) Relationship Input-Output Data: If hours Number of hours worked <=40 -> gross salary = hourly rate * number of hours worked regular salary = hourly rate * number of hours worked number of overtime hours=0 overtime salary = 0 If hours Number of hours worked >40 -> regular salary= 40* hourly rate number of overtime hours= number of hours worked - 40 overtime salary = 1.5*hourly rate * number of overtime hours gross salary = 40* hourly rate + 1.5*hourly rate * number of overtime hours ALGORITHM: 1. Read in the number of hours worked and hourly rate 2. Calculate the number of overtime hours, regular salary and overtime salary as follows: If number of hours worked is less than or equal to 40 2.1 Set overtime hours equal to 0 2.2 Calculate regular salary equal to hourly rate * number of hours worked 2.3 Set overtime salary equal to 0 else do the following 2.4 Calculate overtime hours equal to number of hours worked minus 40 2.5 Calculate regular salary equal to 40* hourly rate 2.6 Set overtime salary equal to 1.5*hourly rate * number of overtime hours 3. Calculate gross salary equal to regular salary + overtime salary 4. Print number of hours worked 5. Print the regular salary, the overtime salary, and the gross salary for the employee c PSEUDOCODE BEGIN READ hours, rate IF hours <= 40 regular_pay hours * rate Overtime 0 Overtime_pay 0 ELSE regular_pay 40 rate Overtime hours - 40 Overtime_pay overtime * 1.5 * rate ENDIF Gross_pay regular_pay + overtime_pay PRINT hours PRINT overtime, reguler_pay, overtime_pay, gross_pay END FLOWCHART START READ hours,rate Hours <=40 regular_pay = hours*rate overtime = 0 overtime_pay=0 regular_pay = 40*rate overtime = hours - 40 overtime_pay=1.5*overtime*rate gross_pay = regular_pay +overtime_pay PRINT hours PRINT overtime, reguler_pay, PRINT overtime_pay, gross_pay STOP PSEUDOCODE BEGIN sum_max 0 sum_min 0 count 1 READ n WHILE count <= n READ max_temp, min_temp sum_min sum_min + min_temp sum_max sum_max + max_temp count count + 1 ENDWHILE avg_min sum_min/n avg_max sum_max/n PRINT avg_max, avg_min END FLOWCHART START sum_min = 0 sum_max = 0 count = 1 READ n count <=n TRUE READ min_temp, max_temp sum_min = sum_min + min_temp sum_max = sum_max + max_temp count = count + 1 avg_min = sum_min/n avg_max = sum_max/n PRINT avg_min, avg_max STOP FALSE Example 3: Requirement Specification: A college is running a number of courses and wishes to find out the age of the oldest student on each course. 1. The main functional requirements are as follows: The program should take as input the age of each student on a particular course and output the age of the oldest student. 2. Constraints The program must be written in C The program must be run on a IBM compatible PC 3. Clarifications/Assumption/Guidelines Maximum number of students is a class is 50 Assume the inputs entered are correct and no input checking is required 4. Data Specification Input Data: number of student - (integer) age of students (integer array[0..49]) Output Data: age of oldest student (integer) Relationship Input-Output Data: age of oldest student > age of each other student Design: Algorithm: 1. Read in the number of students 2. Read in the ages of the students 3. Calculate the ages of the oldest student 4. Output the age of the oldest student Design: Refined Algorithm: 1. Read in the number of students 1.1 Print “enter number of students” 1.2 Read number of students, num 2. Read in the ages of the students For each student 2.1 Print “Enter age of student” 2.2 Read age of student 3. Calculate the ages of the oldest student 3.1 assign oldest to first student For each student 3.2 if age > oldest then assign oldest to this student 3.2 else do nothing 4. Output the age of the oldest student PSEUDOCODE BEGIN PRINT “enter number of students” READ num FOR temp = 1 TO num DO PRINT “enter age of student number”, temp READ age[temp-1] ENDFOR oldest age[0] FOR temp = 1 TO num-1 DO IF age[temp] > oldest Oldest age[temp] ENDIF ENDFOR START PRINT “oldest student is”, oldest END PRINT “ enter “ READ num temp = 1 temp num? FALSE temp = temp+1 TRUE PRINT “enter age of “ READ age[temp-1] oldest = age[0] temp = 1 temp num-1? FALSE temp = temp+1 TRUE age[temp]>oldest? TRUE oldest = age[temp] PRINT “ “ STOP FALSE