320 likes | 345 Vues
Learn about repeat statements, looping, counting, and iterations in algorithm design. Understand how to repeat sections of code using FOR and WHILE constructs, and how to use counting to control repetitions. See examples of counting, cumulative totals, and loops.
E N D
Repeat statements/looping/counting/iterations It is often necessary to repeat certain parts of a program a number of times. One way of doing this would be to write that part of the program as many times as needed. This is impractical, however, as it would make the program lengthy. In addition, in some cases the number of times the section of code needs to be repeated is not known beforehand.
Repeat statements/looping/counting/iterations Two of the methods used to repeat sections of instructions/codes are the FOR construct and the WHILE construct. You need to keep track of how many times the instructions are repeated. Counting or iteration involves increasing the value of a counter variable by a fixed number (this can be any value such as 1, 2, 5, etc.) every time the instructions are repeated. This counter can be part of a condition for stopping the instructions from repeating when the value of the counter becomes equal to a certain value.
Counting Syntax: <Counter variable> = <Counter variable> + 1 The counter variable must be initialised before any instructions are carried out. It is usually set to 0; this is often, but not always, the case. The choice of the name for the counter variable can reflect what is being counted: in the following example, NumofCars for the number of cars.
Examples Example 1: A car rental firm leases its cars; read a car registration number and count the car. Print the number of cars. Solution 1: NumofCars = 0 PRINT “Enter registration number” READ regno NumofCars = NumofCars + 1 PRINT NumofCars
Examples Example 2: A car rental firm leases its cars; read the car registration number and count the car. If the car is a station wagon, also count the number of station wagons. Print the number of cars and the number of station wagons.
Cumulative Totals It often becomes necessary to keep adding values to a current total to get a new total. It is important to initialise the Cumulative Total variable to 0 before the values are added. Syntax: <Cumulative Total> = <Cumulative Total> + <Variable>
Examples Solution 2: NumofCars = 0 NumStationWagons = 0 PRINT “Enter a car registration number and car type” READ regno, cartype IF cartype = “Station Wagon” THEN NumStationWagons = NumStationWagons + 1 ENDIF NumofCars = NumofCars + 1 PRINT “Number of Cars: ”, NumofCars PRINT “Number of Station Wagons: ”, NumStationWagons
Cumulative Totals Example 3: A car rental firm leases its cars; read the number of cars leased in one day and add it to the total number of cars leased. Print the total number of car leased. Solution 3: TotalCars = 0 PRINT “ Enter the number of cars leased in one day” READ carsleased TotalCars = TotalCars + carsleased PRINT “Total Number of Cars Leased: ”, TotalCars
Loops • When a group of statements/instructions are repeated it is called a loop. There are two types of loops: • Finite loop – the number of times a repetition is to be made is known. • Indefinite loop - the number of times repetition is to be made is not known.
The FOR construct – Finite loop In this construct the loop is controlled by a counter which increases each time a set of instructions is executed. This construct is used when the number of times a set of instructions has to be repeated is known. Syntax 1: FOR <Variable> = <Start value> TO <End value> DO <Action to be repeated> ENDFOR
The FOR construct – Finite loop Syntax 2: FOR <Variable> = <Start value> TO <End value> STEP <incremental value> DO <Action to be repeated> ENDFOR The STEP clause allows you to increase the variable by the increment value every time the instructions are repeated, until it becomes equal or exceeds the end value. It is often used when we want to print tables.
Examples Example 4: A car rental firm leases 4 cars in one day. Read the number days for lease for each car and calculate the total rent paid to the firm if a car is leased for $250.00. Print the total rent paid to the rental firm.
Examples Solution 4: TotalRent = 0 FOR Cars = 1 TO 4 DO PRINT “ Enter number of days for lease” READ noofdays rent = nofodays * 250 TotalRent = rent + TotalRent ENDFOR PRINT “Total rent paid to firm: ” TotalRent
Examples Example 5: Print a table to find the square and cube of numbers 1 t0 10. Solution 5: PRINT “Number”, “Square”, “Cube” FOR Number = 1 TO 10 DO Square = Number * Number Cube = Number * Number * Number Print Number, Square, Cube ENDFOR
Examples Example 6: Print a table to find the square and cube of all even numbers between 2 and 20 inclusive. Solution 6: PRINT “Number”, “Square”, “Cube” FOR Number = 2 TO 20 STEP 2 DO Square = Number * Number Cube = Number * Number * Number Print Number, Square, Cube ENDFOR
Examples Example 7: Calculate the sum of all the odd numbers between 1 and 20. Print the total. Solution 7: Sum = 0 FOR Oddnumber = 1 TO 20 STEP 2 DO Sum = Sum + Oddnumber ENDFOR PRINT Sum
Examples Example 8: A company gives out bonuses based on the amount of income generated by their sales representatives per month. Once the income is greater than or equal to $10,000.00, a bonus of 20% is given. If the income generated is greater than or equal to $8000.00 but less than $10,000.00, a bonus of 15% is given. If the income generated is greater than or equal to $5000.00 but less than $8,000.00, a bonus of 10% is given. If the income generated is less than $5000.00, a bonus of 3% is given.
Examples Example 8 (cont’d): Write an algorithm to read 10 employees’ numbers, their income generated, and determine the bonuses of 10 employees. Print the employee number, income generated and the bonus earned by each employee.
Examples Solution 8: PRINT “Employee Number”, “Income generated”, “Bonus” FOR Numemployees = 1 TO 10 DO PRINT “ Enter employee number, income generated” READ emp _num, inc_gen IF (inc_gen >= $10,000.00) THEN bonus = inc_gen * 20% ELSE IF (inc_gen >= $8,000.00) AND (inc_gen < $10,000.00) THEN bonus = inc_gen * 15%
Solution 8 (cont’d): ELSE IF (inc_gen >= $5,000.00) AND (inc_gen < $8,000.00) THEN bonus = inc_gen * 10% ELSE bonus = inc_gen * 3% ENDIF ENDIF ENDIF PRINT emp_num, inc_gen, bonus ENDFOR
Examples Example 9: Write an algorithm to read 25 numbers and print the lowest. Solution 9: Lowest = 99999 FOR count = 1 TO 25 DO PRINT “Enter a number” READ number IF number < lowest THEN Lowest = number ENDIF ENDFOR PRINT “The lowest number entered is: ”, Lowest
The WHILE construct - Indefinite loop In the WHILE construct the computer executes a set of statements/instructions repeatedly for as long as a given condition is true. When you do not know beforehand how many times a set of instructions has to be repeated, use the WHILE construct.
The WHILE construct - Indefinite loop In the WHILE construct the condition is tested; if it is true the instructions within the WHILE ENDWHILE are executed until the condition becomes false and the loop is executed. The trigger that causes the loop to stop is a value that is entered as input data. This value is called a sentinel value, dummy value or terminatingvalue.
The WHILE construct - Indefinite loop Syntax: WHILE <Condition> DO <Action to be taken if condition is true> ENDWHILE
Examples Example 10: Write an algorithm to enter the age and count the number of students in a class. Calculate the average age of the group of students if the data is terminated by 999. Print the number of students in the class and the average age of the students.
Examples Solution 10: total = 0 count = 0 PRINT “Enter student’s age” READ age WHILE age < > 999 DO total = total + age count = count + 1 PRINT ““Enter student’s age” READ age ENDWHILE average = total/count PRINT count, average
Examples Example 11: Write an algorithm to read a set of numbers terminated by 0; print the number of positive and negative numbers entered.
Examples Solution 11: negative = 0 positive = 0 PRINT “Enter a number” READ number WHILE number < > 0 DO IF number > 0 THEN positive = positive + 1 ELSE negative = negative + 1 ENDIF PRINT “Enter a number” READ number
Solution 11 (cont’d): ENDWHILE PRINT negative, positive
Examples Example 12: Write an algorithm to read a set of numbers terminated by 0 and print the highest number.
Examples Solution 12: highest = 0 PRINT “Enter a number” READ number WHILE number < > 0 DO IF number > highest THEN highest = number ENDIF PRINT “Enter a number” READ number ENDWHILE PRINT highest