algorithms and their methods of representation ( loops) (1)

Post on 05-Apr-2015

171 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Section 3 : Problem Section 3 : Problem SolutionSolution

Algorithms and their Algorithms and their methods of representation methods of representation

( Loops)( Loops)

Prepared by : Samra TaufiqPrepared by : Samra Taufiq

Saint Michael’s Convent School

Computer StudiesComputer Studies

Loops ?Loops ?

All of the problems that we have solved so far used an algorithm with the set of instructions in a set order that we refer to as stepping.

What if you have to repeat an instruction or a set of instructions a number of times to find your solution?

In this case you can use loops.

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightWright]]

Loops ( Contd)Loops ( Contd)

Many Problems involve a process that needs to be repeated a specific number of times.

Therefore it is useful to have a technique that performs these loops.

There are number of techniques available.

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightWright]]

Types of Loops

The FOR…… NEXT LoopThe FOR…… NEXT Loop

The WHILE…….DO LoopThe WHILE…….DO Loop

The REPEAT …. UNTIL LoopThe REPEAT …. UNTIL Loop

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

FOR…… NEXT LoopFOR…… NEXT Loop

This is used when the loop is to be repeated a This is used when the loop is to be repeated a know fixed number of times. know fixed number of times.

A FOR loop keeps on carrying out a A FOR loop keeps on carrying out a command or commands, FOR a given number command or commands, FOR a given number of times.of times.

The counter is automatically increased each The counter is automatically increased each time the loop is performed. time the loop is performed.

The commands to be repeated are The commands to be repeated are sandwiched between the FOR and NEXT and sandwiched between the FOR and NEXT and than END FOR commands than END FOR commands

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

Example FOR…… NEXT LoopExample FOR…… NEXT Loop

Problem : Add 10 numbers togetherProblem : Add 10 numbers together Algorithm : Algorithm : For COUNT = 1 to 10 For COUNT = 1 to 10 Input NUMBER Input NUMBER ( inner loop)( inner loop) TOTAL = TOTAL + NUMBERTOTAL = TOTAL + NUMBER Next COUNTNext COUNT

FOR Loop is also know as FOR Loop is also know as Iterative Iterative LoopLoop

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

Example FOR…… NEXT Loop (Explanation)

The first time , the loop COUNT is = 1

The first number is read and its value is added to the TOTAL , to give a new TOTAL.

Next COUNT adds one to COUNT , which is now 2.

And we go back to FOR instruction , where the value of COUNT is checked to see if its less than or equal to 10.

If less than 10, the loop is repeated . This process is repeated until the value of

COUNT = 10

Example FOR…… NEXT LoopExample FOR…… NEXT Loop

PROBLEM: To print the numbers from 10 to 20

ALGORITHM: FOR number = 10 to 20 Print number END FOR

Example FOR…… NEXT LoopExample FOR…… NEXT Loop

PROBLEM: To print the 13 times table from 1 x 13 to 10 x 13

ALGORITHM: FOR NUMBER = 1 to 10 Print 13 x NUMBER NEXT NUMBER

A

B

D

C

TRUE

FALSE

For (A;B;D;C)

For Loop Diagram

WHILE…… DO LoopWHILE…… DO Loop

The WHILE….DO Loop are used in preference to the For….Next Loop.

It can also be used when we don’t know how many times the loop is to be performed.

The loop is ended when a certain condition is true.

This condition is checked before starting the loop

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

Example WHILE…… DO Example WHILE…… DO LoopLoop

PROBLEM: To ask for a number more than 10, then stop when such a number is given

ALGORITHM:

WHILE number given is less than 10 ask for a number more than 10 END WHILE

Example WHILE…… DO Example WHILE…… DO LoopLoop

Problem : Add 10 numbers togetherProblem : Add 10 numbers together Algorithm :Algorithm :

While COUNT <10 DO Input NUMBER TOTAL = TOTAL + NUMBER COUNT = COUNT + 1 Endwhile Output TOTAL

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

Example WHILE… DO Loop (Explanation)

It is possible for a WHILE…DO loop never to It is possible for a WHILE…DO loop never to be performed, If COUNT is given the value be performed, If COUNT is given the value 10 before WHILE… DO Loop is begun.10 before WHILE… DO Loop is begun.

When the loop checks the value of count , it When the loop checks the value of count , it finds it is not less than 10, it is equal to 10.finds it is not less than 10, it is equal to 10.

So the condition is false and loop is not So the condition is false and loop is not startedstarted

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

REPEAT…… UNTIL LoopREPEAT…… UNTIL Loop

The REPEAT … UNTIL Loop is used in preference to the FOR…. NEXT Loop.

It can also be used when we don’t know how many times the loop is to be performed.

The Loop is ended when certain condition is true

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

REPEAT…… UNTIL LoopREPEAT…… UNTIL Loop

The “TRUE” Condition is checked at The “TRUE” Condition is checked at the end of the loop .the end of the loop .

Therefore REPEAT LOOP has to be Therefore REPEAT LOOP has to be performed at least once performed at least once

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

Example REPEAT…… UNTIL Example REPEAT…… UNTIL LoopLoop

Problem : Add 10 numbers togetherProblem : Add 10 numbers together Algorithm :Algorithm :

RepeatRepeat Input NUMBER TOTAL = TOTAL + NUMBER COUNT = COUNT + 1 Until COUNT = 10 Output TOTAL

Source [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain WrightSource [Computer Studies & Information Technology by Chris Leadbetter & Stewart Wain Wright ]]

Selection or Conditional Selection or Conditional StatementsStatements

IF- THENIF- THEN

This is often used when there is a This is often used when there is a simple test available.simple test available.

E.g. To test if a number is positive or E.g. To test if a number is positive or negativenegative

Read numberRead number

IF number > 0 THEN write (‘Positive’)IF number > 0 THEN write (‘Positive’)

Else write ( ‘negative’)Else write ( ‘negative’)

Selection or Conditional Selection or Conditional StatementsStatements

IF- THENIF- THEN

IF …. THEN selection involves the use of IF …. THEN selection involves the use of comparison such as comparison such as

= (equal)= (equal)

< (less than)< (less than)

<= (less than or equal )<= (less than or equal )

> ( greater than)> ( greater than)

>= (greater than or equal)>= (greater than or equal)

Using Pseudocode, or otherwise, write Using Pseudocode, or otherwise, write an algorithm tat will input the hourly an algorithm tat will input the hourly temperature for one day in temperature for one day in Centigrade and print out in Centigrade and print out in FahrenheitFahrenheit

The maximum temperatureThe maximum temperature The minimum temperatureThe minimum temperature The average temperatureThe average temperature For that day.For that day.

InitialiseInitialise LoopLoop Input temperature (*24)Input temperature (*24) Convert to FahrenheitConvert to Fahrenheit Find maximum and minimumFind maximum and minimum Calculate average (outside loop)Calculate average (outside loop) Output maximum, minimum, averageOutput maximum, minimum, average

Sum =0Sum =0 Min =100Min =100 Max =0Max =0 Count =1Count =1 WhileWhile count <=24 do count <=24 do Input Input temptemp F= (temp *1.8) +32F= (temp *1.8) +32 Sum = sum +FSum = sum +F IfIf F< min F< min thenthen min = F min = F IfIf F>max F>max thenthen max =F max =F Count =count +1Count =count +1 endwhileendwhile

Sum =0 Min =100 Max =0 Count =1 repeat Input temp F= (temp *1.8) +32 Sum = sum +F If F< min then min = F If F>max then max =F Count =count +1 Until count >24 average = sum/24 print average , min, max

A utility store uses a computer to store product quantity available in stock. There are 150 products available in stock and the maximum price of product is 100

Initialization ( must correctly set smallest (m1) and largest (m2) boundaries)

Method for looping round for 150 products Reading in price for all products Checking if price inside 0 to 100 boundary

and action taken Setting value of largest (m2) after

checking against input price Totaling all price together Calculating the average price Output of average , smallest price (m1) ,

largest price (m2)

M1 =100 M2 = 0 Sum =0 N =1 While n <151> do repeat read price until (price > =0 and ) price < 101 if price < m1 then m1 = price if price > m2 then m2 = price sum = sum + price n = n + 1 endwhile average = sum/150 output average, m1 , m2

Q The following algorithm contains an error

SET X =1 REPEAT X = X +2 Print X UNTIL X =10 Trace the algorithm and explain

what the error is

Solution

trace – 3, 5, 7,9,11 ………….

Reason – x is odd/loop does not terminate/goes on forever

Q (a) A formula for calculating the body mass index (BMI) is:

BMI = ____Weight in kilograms___

(height in meters) * (height in meters)

Calculate the BMI for a person whose weight is 80kg and height is 2 meters.

Ans : 20

(b) Using Pseudocode or otherwise , write an algorithm that will input the ID, weight (kg) and height (m) of 30 students, calculate their body mass index (BMI) and output their ID, BMI and a comment as follows:

A BMI greater than 25 will get the comment ‘Over Weight’, a BMI between 25 and 19 (inclusive) will get ‘NORMAL’ and a BMI less than 19 will get ‘UNDER WEIGHT’

Intialise Loop (30) Input ID, weight , height IF………….THEN………………ELSE (or CASE OF………………

OTHERWISE) Calculate BMI Output ID, BMI and comment

Count = 0 While count < 31 do Input id, weight, height Bmi = weight /height * height If bmi > 25 then print “overweight”, “id”, “bmi” If bmi < 19 then print “underweight”, “id”, “bmi” else print “normal”, “id”,

“bmi” count = count + 1 endwhile

Q A fuel economy for a car is found using the formula:

Fuel Economy = Distance travelled (km) Fuel Used (litres) What would be the fuel Economy of a car

travelling 40 kim on 10 litres of fuel?

Ans 40/10 = 4

b) The fuel economy for 1000 cars is to be calculated using the formula in Question 16(A)

Write an algorithm, using pseudocode or otherwise, which inputs the Distance travelled (km) and the fuel used (litres) for 1000 cars. The fuel economy for each car is then calculated and the following outputs produced:

- Fuel Economy for each car - Average (mean) Fuel Economy for all the cars input - The best fuel economy ( i.e. lowest value)

Total = 0, count =0, best =0 , worst =1000

Repeat Input litres, distance Economy = distance/litres Print economy If economy > best then best =

economy If economy < worst then worst =

economy Total = total + economy Count = count +1 Until count = 1000 Average = total/1000 Print average, best, worst

Q The manufacturing cost of producing an item depends on the complexity . A company manufactures three different types of item, with costs based on the following calculations.

Item type 1: item cost = part cost * 1.5Item type 2: item cost = part cost * 2.5Item type 3: item cost = part cost * 5.0The company makes 1000 items per dayWrite an algorithm, using pseudocode, flowchartor otherwise , which - Inputs the item type and parts cost of each item - Outputs the item cost for each item - Calculates and outputs the average (mean) item cost per day (based on 1000 items being made).

Total cost = 0For x = 1 to 1000 Input type , partcost If type = 1 then itemcost = partcost *

1.5 } If type = 2 then itemcost = partcost *

2.5 } If type = 3 then itemcost = partcost *

5.0 } else print error totalcost = totalcost+ itemcost print itemcostnext xaverage = totalcost / 1000print average

top related