Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Construct and Algorithms using Problems Solving Tools, Lecture notes of Design Patterns

Write a flowchart of a program that will display the numbers from 10 backwards to 1. Page 3. Page 3 of 57. Ex-5 Sequence. [E] Construct an algorithm ...

Typology: Lecture notes

2021/2022

Uploaded on 08/01/2022

hal_s95
hal_s95 🇵🇭

4.4

(652)

10K documents

1 / 57

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39

Partial preview of the text

Download Construct and Algorithms using Problems Solving Tools and more Lecture notes Design Patterns in PDF only on Docsity!

Program Design:

Construct and Algorithms using Problems Solving Tools--

Sample Exercises

Here you will find some solutions to problems used in the course. Just recall:

SEQUENCE

Ex1. Sequence [E]. Construct pseudocode or flowchart for a program that prints ‘Hello There World’ (or

‘Hola Mundo’) on the screen.

PROGRAM HolaMundo

PRINT ‘Hello There World’

END

i.e., the whole program is just an output

statement greeting the world !!

FLOWCHART CONSTRUCTED WITH RAPTOR

Ex-2. Sequence [E]. Construct pseudocode for a program that asks the user for someone’s name and

greets him/her with his/her name. Hint: names can be stored as strings.

INPUT PROCESSING OUTPUT

name “greeting” + name

NOTE: E.g., “greeting” + name = Hi Marco

PROGRAM whatsUpPana

PRINT “What is your name?”

GET name

PRINT “Hi”+ name + “!!”

END

note: GET is the same as READ, INPUT, etc

This is a program with just I/O, not additional processing.

Ex- 3. Sequence [E]. Write an algorithm in pseudocode that calculates the sum of two numbers and

display the result.

PROGRAM sum2Values

READ num1, num

COMPUTE sum=num1+num

PRINT sum

END

Ex- 4. Sequence[E] Write an algorithm in pseudocode that calculates the sum of powers of two numbers

A and B as shown by the formula below and display the result.

𝐵

𝐴

PROGRAM sum2Powers

READ A, B

COMPUTE R = A^B + B^A

PRINT R

END

Ex- 4. Sequence. Write a flowchart of a program that will display the numbers from 10 backwards to 1.

PROGRAM cylinderSurfAreaVol

READ r, h

COMPUTE A = 2* pi * rh + 2 pi * radius ^

COMPUTE V = pihr^

PRINT A, V

END

Ex- 7 Sequence [E]. Write an algorithm in pseudocode that computes the average of five quizzes, and

then display the result.

SOLUTION

PROGRAM quizAverage

READ quiz1, quiz2, quiz3, quiz4, quiz

COMPUTE average = (quiz1+quiz2+quiz3+quiz4+quiz5)/

PRINT average

END

Ex- 8 Sequence. [H] Write pseudocode for a program to compute the standard deviation of the following

set of eight numbers: x 1

, x 2

, x 3

, x 4

, x 5

, x 6

, x 7

, and x 8

, and then displays the result. The standard deviation

σ formula is:

𝒊

𝟐

𝑵

𝒊=𝟏

where x i

is each individual value, μ is the set average and N is the number of data values.

INPUT PROCESSING OUTPUT

x1, x2, x3, x4,

x5, x6, x7, x

mu = (x1+x2+x3+x4+x5+x6+x7+x8)/

SD=sqrt(1/N*((x 1 - mu)^2+(x2-mu)^2+(x3-mu)^2+(x4-mu)^2+(x5-

mu)^2+(x6-mu)^2+(x7-mu)^2+(x8-mu)^2))

SD

PROGRAM standardDeviation

INPUT x1, x2, x3, x4, x5, x6, x7, x

COMPUTE:

mu = (x1+x2+x3+x4+x5+x6+x7+x8)/

SD=sqrt(1/N*((x1-mu)^2+(x2-mu)^2+(x3-mu)^2+(x 4 - mu)^2+(x5-mu)^2+(x6-mu)^2+(x7-mu)^2+(x8-mu)^2))

PRINT SD

END

NOTE: Later we will learn there are others ways to solve this problem more efficiently, e.g., using x as

array variable and implementing loops

Ex- 9 Sequence [E]. This is twofold: Write an algorithm in pseudocode that converts Fahrenheit degrees

into its Celsius degree equivalent. Use the formula: C= (5/9)*F-32. Write another algorithm in

pseudocode that converts Celsius degrees into its equivalent Fahrenheit degrees. Use the formula: F=

(9/5) * C+32.

Ex- 14 Sequence [M] Write an algorithm in pseudocode that calculates the sum of powers of two

numbers A and B as shown by the formula below and display the result. The number B must be half of

three times A.

𝐵

𝐴

PSEUDOCODE:

Exercise 12. A biotechnologist is researching a newly-discovered species of bacteria. At time t = 0 hours,

he puts one hundred bacteria (P=100) into what he has determined to be a favorable growth medium.

He wants to compute how many more bacteria will be after six hours. Assuming exponential growth, the

growth constant k for the bacteria is 0.25/hr. The bacteria amount at time t can be computed with (See

Appendix):

PROGRAM sum2Powers

READ A

COMPUTE B= A*3/

COMPUTE R = A^B+B^A

PRINT R

END

Ex- 15 Sequence. [H] A biotechnologist is researching a newly-discovered species of bacteria. At time t

= 0 hours, he puts one hundred bacteria (𝐴 0

=100) into what he has determined to be a favorable growth

medium. He wants to compute how many more bacteria will be after six hours. Assuming exponential

growth, the growth constant k for the bacteria is 0.25/hr. The amount of bacteria A after an elapsed

time t (starting at t o

=0), is (See http://www.biology-pages.info/P/Populations.html).

0

𝑘𝑡

INPUT PROCESSING OUTPUT

SET t = 6

SET Ao = 100

SET k = 0.

A = Aoexp(kt)

A

The above is not the best solution, it lacks generality. The program works for only the given parameters

t=6, Ao=100, and k=0.25. What if we want to create a program that runs for an ample range of values of

these parameters?

Ask the user for the parameters, then you create a more general program, which would work for larger

range of values, then your IPO diagram is:

INPUT PROCESSING OUTPUT

t, Ao, k A = Aoexp(kt) A

Input Processing Output

a [side]

2

P [perimeter]

A [area]

Ex-18. Sequence. Construct a program (IPO diagram, pseudocode, flowchart) to compute the equation

of a line expressed as y = mx + b, given the coordinates of two points (x 1

,y 1

), (x 2

,y 2

); where m is the slope

and b the y intercept. SOLUTION: lineEquation

Ex-19. Sequence. Construct an algorithm to switch the value stored in A to B, and the value stored in B

to A. Code should work for any value of A and B. E.g., if A=1 and B=3, the new values after switching are

A=3 and B=1. Trace your code solution.

Ex-20. Sequence. Write an algorithm to transfer the value of A to C, the value of B to A and the value of

C to B.

SELECTION

Develop an algorithm for the following problems; use top down design, cursory sketches, flowcharts and

pseudocodes for each problem of the following.

In the following answers, we skip the { PROGRAM / END } requirement to make solutions

shorter.

Ex-1. Write pseudocode to decide whether or not to wash your hands.

INPUT HandsMode % Modes are ‘dirty’ OR ‘clean’

IF HandsMode == ‘dirty’ THEN

PRINT ‘ Wash your dirty Hands, Please ’

ELSE

PRINT ‘ Do not need to wash your hands, they are clean enough ’

ENDIF

Ex- 2. Write pseudocode to decide whether or not is time to make lunch. (Please see algorithm in

problem #7 and shorten it for this problem)

Ex-3. Write pseudocode to print the largest of two given numbers.

INPUT two numbers: A and B

IF A >= B % notice the symbol >=

PRINT ‘ A is largest’

ELSE

PRINT ‘ B is largest’

ENDIF

A better algorithm:

INPUT A,B

grandote=A

IF B >= grandote

grandote=B

ENDIF

PRINT ‘The largest is’, grandote

Ex-4. Write an algorithm in pseudocode which ask the user for a number, then decide if the number is

between 10 and 15, if it is, print the number.

Ex-2. Write Pseudocode to print the height of

the tallest boy in a three-guy basketball team.

Their height is stored as A, B, C.

SOLUTION

In the following algorithm, it’s assumed that the

first boy A is the tallest, then the second boy B is

compared to this tallest. If the second happens

to be taller than the assumed tallest, the second

is stored as the new tallest, otherwise the first

number is still the tallest. Algorithm does the

same with the third boy.

SOLUTION

READ A, B, C

SET Tallest = A

IF B > Tallest

SET Tallest = B

ENDIF

IF C > Tallest

SET Tallest = C

ENDIF

PRINT ‘The Tallest is ‘, Tallest

Ex-6. Selection. Write an algorithm in pseudocode to decide whether or not to take a shower. Then,

decide if you shampoo your hair. Shower are taken from 7:30-9:30 am and shampooing only Monday,

Wednesday, and Fridays.

INPUT time, day

IF time >= 7:30 AND time <=9:

IF day is Monday or Wed or Friday

PRINT ‘take a shower & shampoo your hair’

ELSE

PRINT ‘take a shower skip shampooing your hair’

END IF

ELSE

PRINT ‘can’t take a shower neither shampoo your hair’

ENDIF

NOTE: You can only shampoo your hair only if you take a shower and the day is Monday, Wednesday or

Friday.

Ex-7. Selection. Write an algorithm in pseudocode to decide whether or not to take a shower. Then,

decide if you shampoo your hair. Shower are taken from 7:30-9:30 am and shampooing only Monday,

Wednesday, and Fridays. The FOLLOWING ALGORITHM HAS LOGIC ERRORS , PLEASE FIND THEM:

INPUT time, day

IF time >= 7:30 AND time <=9:

PRINT ‘take a shower’

ELSE

PRINT ‘don’t take a shower’

END IF

IF day is Monday or Wed or Friday

PRINT ‘shampoo your hair’

ELSE

PRINT ‘don’t shampoo your hair’

END IF

Ex- 8. Selection. Write pseudocode to decide whether or not it is time to make lunch. If it is late make

dinner, if it is early prepare breakfast. Lunch is prepared between noon and 2 pm

INPUT time

IF time <

PRINT ‘ Mami, please prepare breakfast ‘

ENDIF

IF time >=12 AND time <= 2

PRINT ‘ Güela, please cook lunch ‘

ENDIF

POS = 1

IF X2 > Largest

SET Largest = X

SET POS = 2

ENDIF

IF X3 > Largest

SET Largest = X

SET POS = 3

ENDIF

PRINT ‘In the new list the largest is ‘, Largest

NOTE: You will see later on how to implement a loop into this problem, which will greatly simplify it.

Ex- 10. Selection. Write pseudocode to decide if a number is between 1 and 10, if it is, print the double

of the original number and check whether the result is still between 1 and 10.

INPUT number

IF number>=1 AND number <= 10

PRINT ‘Original ‘ + number + ‘is in the range of [1,10]’

COMPUTE newNumber = 2* number

IF newNumber >= 1 AND newNumber <= 10

PRINT newNumber is also in the range of [1,10]

ELSE

PRINT newNumber is NOT in the range of [1,10]

ENDIF

ELSE

PRINT ‘Original number’ + number + ‘is not in the range of [1,10]

ENDIF

Ex- 11. Selection. Write pseudocode to decide if a student got attendance bonus. If he has zero

absences he gets 3% bonus added to its final examination score, otherwise zero bonus.

INPUT absences, final % final = final score

IF absences = = 0 THEN

bonus=

ELSE

bonus=

ENDIF

finalPlusBonus = final + bonus

PRINT finalPlusBonus

Ex- 12 : Selection. Write an algorithm in pseudocode for sizing a Window Air Conditioner unit (size is in

BTU). Window air conditioners typically have cooling capacities ranging from 5,000 to 12,500 British

Thermal Units (BTUs). As a rule of thumb, an air conditioner needs 20 BTU for each square foot of living

space but there are other considerations such as the height of your ceiling and the size of your windows

and doorways. To measure your room, multiply the length of the room by the width. Energy Star

recommends that you make adjustments for the following circumstances:

  • If the room is heavily shaded, reduce capacity by 10 percent.
  • If the room is very sunny, increase capacity by 10 percent.
  • If more than two people regularly occupy the room, add 600 BTUs for each additional person.
  • If the unit is used in a kitchen, increase capacity by 4,000 BTUs.

Test your program for a very sunny 12 by 16 feet master room occupied by a couple.

Ex- 13. Selection. Print the height of the tallest boy in a three-people basketball team. Their height is

store as A, B, C.

SOLUTION

In the following algorithm, it’s assumed that the first boy A is the tallest, then the second boy B is

compared to this tallest. If the second happens to be taller than the assumed tallest, the second is

stored as the new tallest, otherwise the first number is still the tallest. Algorithm does the same with

the third boy.

READ A, B, C

SET Tallest = A

IF B > Tallest

SET Tallest = B

ENDIF

IF C > Tallest

SET Tallest = C

ENDIF

PRINT ‘The Tallest is ‘, Tallest

Ex 14. Selection. Suppose “ Banco del Pueblo ” offers 1 percent annual interest on balances of less than

$5000, 2 percent for balances of $5000 or more but less than $10 000, and 3 percent for balances of $

000 or more. Write down pseudocode to calculate a customer’s new balance after one year.

Ex 15. Selection. Chemists define the acidity or alkalinity of a substance according to the formula

pH = – log 10

[H+] where [H+] is the hydrogen ion concentration, measured in moles per liter. Solutions

with a pH value of less than 7 are acidic; solutions with a pH value of greater than 7 are basic; solutions

with a pH of 7 (such as pure water) are neutral. Suppose that you test apple juice and find that the

hydrogen ion concentration is [H+] = 0.0003. Find the pH value for the apple juice and determine

whether the juice is basic or acidic.

READ Hplus

COMPUTE pH = - log 10 (Hplus) % log 10 is a predefined function

PRINT pH

PSEUDOCODE:

INPUT Y % Y= year

IF mod(Y,4)==

IF mod(Y,100)==

IF mod(Y,400)==

PRINT ‘Y is leap year’

ELSE

PRINT ‘Y is NOT leap year’

END

ELSE

PRINT ‘Y is leap year’

END

ELSE

PRINT ‘Y is NOT leap year’

END

MATLAB CODE

% LeapYear Program

clc, clear

Y=input('Enter a year \n');

if mod(Y,4)==

if mod(Y,100)==

if mod(Y,400)==

fprintf('%d is leap year \n',Y);

else

fprintf('%d is NOT leap year \n',Y);

end

else

fprintf('%d is leap year \n',Y);

end

else

fprintf('%d is NOT leap year \n',Y);

end

Testing and running in RAPTOR:

Another version :

Ex-18. Selection. Write pseudocode to test if a number is a multiple of 3, 5 or 7.

Ex-19. Selection. Given an age, write pseudocode to figure out whether someone's a baby, toddler,

child, teenager, adult or old codger. Better use the following table:

Age Stage

0 - 1 approximately a baby

1 - 2 a toddler

2 - 12 approximately a child – this period is your childhood

13 - 17 approximately a teenager (14 = early teens)

18 + an adult

20 - 30 in your twenties (24-26 = mid twenties)

30 - 40 in your thirties (38 = late thirties)

40+ people are middle-aged; in middle age

60 or 65 retirement (= when people stop work; they are retired)

75+ old age (you can also use elderly)

Ex-20. Selection. Write pseudocode to calculate a grade based on the A through F letter grade system

and on the final percentage score.

Ex-21. Selection. Write pseudocode. Given a blackjack hand, check if it's okay or bust (this is good since

J/Q/K morph into 10).

Ex-22. Selection. Write pseudocode. Given a blackjack hand, figure out whether to draw another card (if

total is under 17 for example).