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

(620)

8.6K documents

1 / 57

Toggle sidebar

Related documents


Partial preview of the text

Download Construct and Algorithms using Problems Solving Tools and more Lecture notes Design Patterns in PDF only on Docsity! Page 1 of 57 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 Page 2 of 57 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, num2 COMPUTE sum=num1+num2 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. Page 5 of 57 SOLUTION PROGRAM quizAverage READ quiz1, quiz2, quiz3, quiz4, quiz5 COMPUTE average = (quiz1+quiz2+quiz3+quiz4+quiz5)/5 PRINT average END Ex-8 Sequence. [H] Write pseudocode for a program to compute the standard deviation of the following set of eight numbers: x1, x2, x3, x4, x5, x6, x7, and x8, and then displays the result. The standard deviation ฯƒ formula is: ๐ˆ = โˆš ๐Ÿ ๐‘ต โˆ‘(๐’™๐’Š โˆ’ ๐)๐Ÿ ๐‘ต ๐’Š=๐Ÿ where xi 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, x8 mu = (x1+x2+x3+x4+x5+x6+x7+x8)/8 SD=sqrt(1/N*((x1-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, x8 COMPUTE: mu = (x1+x2+x3+x4+x5+x6+x7+x8)/8 SD=sqrt(1/N*((x1-mu)^2+(x2-mu)^2+(x3-mu)^2+(x4-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. Page 6 of 57 Ex-10. Sequence [E]. Create pseudocode to compute the volume of a sphere. Use the formula: V= (4/3)* ฯ€ r3 where ฯ€ is equal to 3.1416 approximately, where r is the radius. Display the result. PROGRAM SphereVolume READ radius COMPUTE volume = (4/3) * pi* radius ^3 PRINT volume END Ex-11 Sequence. [E] Write an algorithm in pseudocode that converts Celsius degrees into its equivalent Fahrenheit degrees. Use the formula: F= (9/5) * C+32. Ex-12 Sequence [H]. Area under the curve. Shown is the formula to compute the total composed area of trapezoidal-1 plus trapezoidal-2: ๐‘‡๐‘œ๐‘ก๐‘Ž๐‘™ ๐ด๐‘Ÿ๐‘’๐‘Ž = โ„Ž 2 (๐‘“1 + 2๐‘“2 + ๐‘“3) Design an algorithm with flowchart (submit flowchart and output) and pseudocode to compute the composed area under the curve given h, f1, f2, and f3, where h is a constant given by โ„Ž = (๐‘โˆ’๐‘Ž) ๐‘ ๐‘’๐‘๐‘ก๐‘œ๐‘Ÿ๐‘  ; b (right end point); a (left end point); and sectors=2. Test your program with f1=2, f2=3, f3=2.5; x1=1, x2=3, x3=5. Ex-13 Sequence [E] Write an algorithm in pseudocode to compute the distance of the nine major planets in km. Background: The second illustration below depicts the true relative distances from the Sun of each planet as well as asteroids in the Asteroid belt, measured in astronomical units or (AU) which is equal to the length of the semi-major axis of the Earth's elliptical orbit or 149,597,870.69 km. Notice that the Earth is positioned at 1 AU and the farthest major planet Neptune is positioned at 30 AU. Also notice that Pluto's distance from the Sun varies between 30 and 50 AU, with its orbit sometimes crossing that of Neptune ( http://people.bu.edu/sscruggs/majorplanetshome.html) Page 7 of 57 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): Page 10 of 57 Input Processing Output a [side] ๐‘ƒ = 5 ๐‘Ž ๐ด = ( 1 4 ) โˆš5 ( 5 + 2โˆš5) ๐‘Ž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 (x1,y1), (x2,y2); 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. Page 11 of 57 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 <name>/ 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. Page 12 of 57 Ex-5. Write an algorithm in pseudocode to print the smallest of three numbers SOLUTION-1 READ A,B,C IF A < B Smallest=A IF C < Smallest Smallest = C ENDIF ELSE Smallest = B IF C < smallest Smallest = C ENDIF ENDIF PRINT Smallest READ A, B, C Smallest=A IF B < Smallest Smallest = B ENDIF IF C < Smallest Smallest = C ENDIF PRINT Smallest SOLUTION-3 READ A, B, C IF A < B AND A < C Smallest = A ENDIF IF B< A AND B < C Smallest = B ENDIF IF C < A AND C < B Smallest = C ENDIF PRINT Smallest Notice in the above solutions how the pseudocodes avoid many PRINT statements in the program, one at the end is enough SOLUTION-4 (Is it right?) Test the solution with several combinations of A, B, and C READ A, B, C % Find the bugs with this solution IF A < B AND B < C Smallest = A ENDIF IF B< A AND A < C Smallest = B ENDIF IF C < A AND A < B Smallest = C ENDIF PRINT Smallest The BEST solution is #2 SOLUTION-2 small3Guy.rap Page 15 of 57 IF time >2 PRINT โ€˜ Titi, please make dinner for me โ€™ ENDIF Ex-9. Selection. Write pseudocode to print the largest of three given numbers. Once you find the largest half the largest and find again the largest. SOLUTION In the following algorithm, itโ€™s assumed that the first number is the largest, then the second number is compared to this largest. If the second happens to be larger than the assumed largest, the second is stored as the new largest, otherwise the first number is still the largest. Algorithm does the same with the third number. READ X1, X2, X3 SET Largest =X1 POS = 1 IF X2 > Largest SET Largest = X2 SET POS = 2 ENDIF IF X3 > Largest SET Largest = X3 SET POS = 3 ENDIF PRINT โ€˜In the original list the largest is โ€˜, Largest % To repeat the process with a new value = Largest/2, we need to erase the largest and replaced it by % this new value (in the same position) so it does not participate of the new search (otherwise the % largest would be the same number) % NEXT is the algorithm to eliminate the largest from the list and replacing it by the new value equal to % half the Largest IF POS == 1 X1 = Largest/2 ENDIF IF POS == 2 X2 = Largest/2 ENDIF IF POS == 3 X3 = Largest/2 ENDIF % Repeat the first BLOCK of statements to find new largest: SET Largest =X1 Page 16 of 57 POS = 1 IF X2 > Largest SET Largest = X2 SET POS = 2 ENDIF IF X3 > Largest SET Largest = X3 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=3 ELSE bonus=0 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 Page 17 of 57 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 $10 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 = โ€“log10[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 = -log10(Hplus) % log10 is a predefined function PRINT pH Page 20 of 57 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). Page 21 of 57 Ex-23. Selection. Write pseudocode. Try a simple game: If you press 'L', turn left, if you press 'R', turn right, if there's a monster (e.g., โ€˜Mโ€™), you die. Ex-24. Selection TAXI RATES. To put it simply, taxi meters measure distance and time. They then convert those measurements into a fare. All taxi meters measure the distance a cab covers, plus any time spent waiting. That way, the driver gets compensated for time, so they don't lose out on money just because they're stuck in traffic. It's also why a cab ride from point A to point B may cost you more when there's traffic than when there's not, even if the distance covered is the same. Each trip is made up of three components: 1. Initial flag (Starting rate, which shows on the meter when switched to hire) is the minimum the customer is going to pay. This buys them a fixed distance or waiting time or a combination of both. 2. Ongoing Drops is the rate that is going to be charged after the initial flag distance. This is made up of the fare increments depending on the distance covered. This is called a progressive tariff, which after the initial flag distance and charge say, goes $1.50 per mile for two miles and then changes to $1.30 per mile to the end of the journey. 3. Waiting Time. During this ongoing drop period, waiting time is normally implemented. This normally uses the same drop value, a set waiting time rate would be used if the vehicle was stationery. This also uses a progressive tariff, in the first 2 hours, the rate is $0.20 per minute and then the tariff decreases to $0.15 per minute to the end of the trip. When the vehicle starts to move, the customer pays for waiting time PLUS distance charges PLUS initial flag. ๐‘ป๐’“๐’Š๐’‘ ๐‘น๐’‚๐’•๐’† = ๐’Š๐’๐’Š๐’•๐’Š๐’‚๐’ ๐’‡๐’๐’‚๐’ˆ + ๐’๐’๐’ˆ๐’๐’Š๐’๐’ˆ ๐’…๐’“๐’๐’‘๐’” + ๐’˜๐’‚๐’Š๐’•๐’Š๐’๐’ˆ ๐’•๐’Š๐’Ž๐’† Write a RAPTORโ€™S flowchart (submit flowchartโ€™s program and output) and PSEUDOCODE for a program that computes the total trip rate. Consider 0.5 mile as the initial flag. REAL LIFE: Taxi fares are set by the area the taxi cab operates in -- in other words, it might cost more to travel the same distance or time in one city than it does in another. Fares may also change based on how many people are in the taxi, if the driver has to help you with your bags and if the taxi has to cross state or municipal lines to get you where you're going. Level 0-Algorithm (1) Input: initial flag, trip distance, trip time (2) Compute trip rate a. Get or compute initial flag b. Compute Ongoing drops c. Waiting time (3) Output Total Trip Rate Page 22 of 57 Level 1-Algorithm (1) Input: initial flag, trip distance, trip time (2) Compute trip rate a. Compute Ongoing drops i. Compute trip interval-1 between 0.5 and 2 miles of the trip, then interv-1*$1.50 ii. Compute trip interval-2 beyond 2 miles, then interv-2*$1.30 iii. Compute ongoing-drops subtotal b. Waiting time i. Compute cost of trip time1<=120 minutes (2 hours), then time1*$0.20 ii. Compute cost of trip time2>120 minutes, then time2*$0.15 iii. Compute waiting-time subtotal c. Compute: ๐‘ป๐’“๐’Š๐’‘ ๐‘น๐’‚๐’•๐’† = ๐’Š๐’๐’Š๐’•๐’Š๐’‚๐’ ๐’‡๐’๐’‚๐’ˆ + ๐’๐’๐’ˆ๐’๐’Š๐’๐’ˆ ๐’…๐’“๐’๐’‘๐’” + ๐’˜๐’‚๐’Š๐’•๐’Š๐’๐’ˆ ๐’•๐’Š๐’Ž๐’† (3) Output Total Trip Rate. Ex 25. Selection Movie Theater. Write a program that tells the user what type of movie they can attend based on their age, if they are with their parents, if they are students, and their amount of money Under 13 G Under 13 w/parent: G, PG 13 and Over and Under 16: G, PG Under 16 w/parent G, PG, R 16 and Over G, PG, R Student $4.00 Matinee $4.50 Evening $6.50 Page 25 of 57 Ex 26. Selection. Bank Account. Write a program that will take as input the userโ€™s bank account balance and the type and level of account they have. Based on this information and the below rate table, determine the interest rate they are receiving. Type of Account Level Minimum Balance Interest Rate Student Standard $25 1.3 % Personal Standard $0 1.2 % Personal Gold $1000 1.9 % Personal Gold $5000 2.3 % Business Standard $1500 1.7 % Business Platinum $10000 2.5% Page 26 of 57 Cursory Sketch using โ€œANDโ€ and/or โ€œORโ€ Combining conditions simplified our sketch dramatically! Now let us translate this new sketch into a flowchart with pseudocode. Page 27 of 57 pseudocode: INPUT user account type, account level, and balance. IF account type is โ€œpersonalโ€ and account level is โ€œstandardโ€ and balance >= 0 PRINT โ€œInterest Rate is 1.2%โ€ ELSEIF account type is โ€œpersonalโ€ and account level is โ€œgoldโ€ and balance >= 5000 Page 30 of 57 % C=cost of the meal R=restaurant type: โ€˜dinerโ€™, โ€˜goodโ€™, โ€˜excellentโ€™; S=how was the type of service: โ€™poorโ€™,โ€™goodโ€™,โ€™excellentโ€™; N = number of parties % INPUT C INPUT R,S,N IF R==โ€œdinerโ€ T=0.12 ELSE IF R==โ€œgoodโ€ T=0.15 ELSE IF R==โ€˜excellentโ€™ T=0.20 ELSE PRINT โ€˜error in type of restaurantโ€™ Page 31 of 57 ENDIF ENDIF ENDIF IF S==โ€˜poorโ€™ T=T-0.2 ELSEIF S==โ€˜goodโ€™ T=T ELSEIF S==โ€˜excellentโ€™ T=T+0.20 ELSE PRINT โ€˜error in type of serviceโ€™ ENDIF A=C*T; PRINT โ€˜Amount of Tipโ€™, A IF N>=1 AND N<=5 % No need T=T ENDIF IF N>=6 AND N<=10 T=T+0.03 ENDIF IF N>10 T=T+0.05 ENDIF IF N<1 PRINT โ€˜error in number of partiesโ€™ ENDIF LOOPS Design algorithms to solve the following problems. Use designing tools, such as, problem iteration decomposition, trace tables, flowcharts and pseudocodes. Page 32 of 57 Ex-1. Loops. Construct a program to print a message (e.g., Hello There World) of your choice N times. READ N % N, desired number of % messages, e.g. five (5) SET counter=1 WHILE counter <= N % Loops is true PRINT โ€˜ HELLO THERE WORLDโ€™ ADD counter=counter + 1 ENDWHILE RAPTOR ADAPTED: WRITE โ€œEnter number of Greetingsโ€ GET N % E.g., N=5 SET Count = 1 LOOP Count > N % Loops if false PUT Count + โ€œ Hello there Worldโ€ SET Count = Count +1 ENDLOOP File: greetsWorld.rap Ex-2. Loops. Write pseudocode for the following game. Ask for the radius of a circle, then keep asking guesses for the area of the circle until the correct area is given. INPUT radius COMPUTE area = pi * r^2 PRINT โ€˜Can you guess the area of the circle with radius equal to โ€™, radius INPUT guess WHILE area <> guess DO % symbol <> means not equal IF guess > area PRINT โ€˜Too highโ€™ PRINT โ€˜Tray againโ€™ PRINT โ€˜Can you guess the area of the circle with radius equal to โ€™, radius INPUT guess Page 35 of 57 ENDWHILE PRINT โ€˜You got it! The password is โ€™, password Ex-8. Loops. Write pseudocode to keep asking for a number less than 100 and stop when the number is multiple of 3, 5, and 7. (If you were trying to develop a code, you should read about โ€˜remโ€™ and โ€˜modโ€™ matlab functions; similar functions exist in most languages). PRINT โ€˜Enter a number less than 100โ€™ INPUT number SET multiple357 = false WHILE number <= 100 IF number%3~=0 AND number%5~=0 AND number%7~=0 PRINT โ€˜Enter another number less than 100โ€™ INPUT number ELSE SET multiple357 = true ENDIF END WHILE IF multiple357 == true PRINT number is multiple of 3, 5, and 7 ELSE PRINT number is NOT multiple of 3, 5, and 7 END Ex-8. Loops. [M] Starting with one (1), write and algorithm to test for numbers less than 1000 and count how many of them are multiple of 3, 5, or 7. Also count how many are multiples of 3, 5, and 7 (If you were trying to develop a flowchart, you should read about โ€˜moduloโ€™ flowgorithm operator, either mod or %; similar function or operator exist in most languages). Ex-9. Loops. Starting with [H+] concentration in a substance, write pseudocode to compute pH of several liquids as shown below and produce a table with โ€œpHโ€, โ€œ[H+] concentrationโ€, โ€œtype of substanceโ€ columns. Program requests from user the substance type and the [H+] concentration until user types a sentinel (e.g., -1). To calculate the pH of Page 36 of 57 an aqueous solution you need to know the concentration of the hydronium ion [H+] in moles per liter (molarity). Type of Substance [H+] Concentration moles/liter. pH battery acid 1 0 gastric acid 1.0E-01 1 lemon juice, vinegar 1.0E-02 2 orange juice, soda 1.0E-03 3 tomato juice, acid rain 1.0E-04 4 black coffee, bananas 1.0E-05 5 urine, milk 1.0E-06 6 pure water 1.0E-07 7 sea water, eggs 1.0E-08 8 baking soda 1.0E-09 9 Great Salt Lake, milk of magnesia 1.0E-10 10 ammonia solution 1.0E-11 11 soapy water 1.0E-12 12 bleach, oven cleaner 1.0E-13 13 liquid drain cleaner 1.0E-14 14 SOLUTION INPUT substance INPUT H WHILE H ~=-1 DO pH = -log10(H) PRINT substance, H, pH PRINT โ€˜Do you want to continue? write -1 to stopโ€™ INPUT H INPUT substance ENDWHILE Page 37 of 57 Ex-10. Loops. Print the first 100 odd numbers. SET x=1 WHILE x<=200 DO IF x%2==0 % if x is even the reminder of x/2 is zero PRINT x ENDIF ENDWHILE Ex-11. Loops. Determine the factors of a positive number entered by the user INPUT N SET i=1 WHILE i<=N DO IF mod(N,i)==0 % mod is a function that returns the integer reminder of N/i PRINT i ENDIF ADD i=i+1 ENDWHILE Page 40 of 57 Ex-15. Loops. Write pseudocode to design a program which will repeatedly print the value of the positive variable X, decreasing it by 0.5 each time, as long as the X remains positive. Advice the user to enter initially a positive number. PRINT โ€˜Enter a positive numberโ€™ INPUT X WHILE X>0 DO PRINT X ADD X=X-0.5 ENDWHILE Ex-16. Loops. Write pseudocode to print the square roots of the first 25 odd positive integers. Use the mod function SET NUMBER=1 SET COUNT =0 WHILE COUNT<=25 IF mod(NUMBER,2) ~=0 PRINT NUMBER, NUMBER^(1/2) COUNT=COUNT+1 Page 41 of 57 END ENDWHILE Ex-17. Loops. Write pseudocode to repeat a block of code as long as the user indicates they want it to. This is an example of a sentinel (or flag) controlled loop. SET X=1 WHILE X ~= -1 % sentinel is -1 PRINT 'YOU are the greatest men/women on earth!!โ€™ PRINT โ€˜Enter another value of X, -1 to stopโ€™ INPUT X END Ex-18. Loops. Write pseudocode for a program which drives the user crazy by insisting they re-enter a particular input no matter what they enter. Be creative... You the programmer decides to stop the program after N times (once he/she is fully crazy). SET X=33 % Value set by the programmer, unknown by user SET COUNT=0 PRINT โ€˜Enter a two-digit value of Xโ€™ INPUT X WHILE X ~= 33 AND COUNT<=90 % sentinel is 33 COUNT=COUNT+1 PRINT โ€˜SORRY, you failed. Enter another two-digit value of Xโ€™ INPUT X END PRINT โ€˜EUREKA, you got it. The number isโ€™, X Page 42 of 57 Ex-19. Loops (H) Textito: We want to read a text represented as a sequence of characters. We want to calculate the number of occurrences of the letter a (or any character). We can assume that the text always has at least one character. Example, the entered text for the solution to the right was: โ€œAlbertito Einstenitoโ€, a string with 20 characters which was entered (input) char-by- char. Then, program counted the number of โ€œtees.โ€ Flowgorithm cannโ€™t I/O the whole string in a single statement, thus you have to develop loops for input and output of strings char-by- char. Ex-20. Loops. (H) If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Hint: Be careful not to add two times a number which is multiple of both 3 and 5. Submit RAPTORโ€™s flowchart (flowchart + output) and pseudocode. A solution In C language is offered below: #include <stdio.h> int main(void) { int zx, nn3 = 0, nn5 = 0, nn15 = 0; for (zx = 0; zx < 1000; zx++) { if (zx % 3 == 0) { nn3 += zx; } if (zx % 5 == 0) { nn5 += zx; } if (zx % 15 == 0) { nn15 += zx; } } printf("%d\n", nn3 + nn5 - nn15); Page 45 of 57 if(NUMBER%ki==0) jj=ki; if(ki>=(sqrt(NUMBER))) goto END; } } } END: printf("%d", jj); return 0; } Ex-23 Loops. Integer Division (also called Long Division) is the process of division of two integers which produces a quotient and a reminder both integers. Example Algorithm quotient remainder 123 % n=[numerator] 20 ๏ƒง1 % d=[denominator] 103 % reminder r becomes new n 20 ๏ƒง2 83 20 ๏ƒง3 63 20 ๏ƒง4 43 20 ๏ƒง5 23 quotient is the number of times 20 ๏ƒง6 you subtract the denominator until n<=d 3 ๏ƒง reminder Page 46 of 57 PSEUDOCODE: INPUT n % n = integer numerator INPUT d % d =integer denominator SET nn=n % stores initial n COMPUTE: q=0 % q=quotient [a counter] WHILE n>=d n=n-d q=q+1 END PRINT โ€œquotient isโ€, q COMPUTE r=nn-d*q PRINT โ€œreminder is โ€œ, r For the second algorithm Let a be an integer and b be a positive integer. Then there exist unique integers q and r such that a = bq + r and 0 <= r < b. q [quotient]; r [reminder] Algorithm: 1. Begin with values of a and b; 2. Set q equal to the integer part of a/b; (**) 3. Set r = a โ€“ bq. (**) no easy, how? Likely you have to use a floor, round, or ceil functions Page 47 of 57 Another approach: 1. Begin with values of n [numerator] and d [denominator]; 2. Set r=n 3. Set q=0 4. Do a. q=q+1 b. Compute r=n-d*q 5. While (r>d) 6. Print q, r Ex-24 Loops. (H) GCD-Euclidean Algorithm. The Euclidean algorithm is one of the oldest numerical algorithms still to be in common use. It solves the problem of computing the greatest common divisor (gcd) of two positive integers (see problem description and example in document โ€œEuclides Algorithm.pdfโ€) Ex-25 Loops. Sequences. For the sequence 7, 10, 8, 11, 9, 12โ€ฆcompute the first 10 numbers in this sequence. SOLUTION The pattern is increasing by 3, then decreasing by 2, so the next number in the series after 12 should be 10. LOOPS & ARRAYS Ex-25. Input/OUTPUT the array X=[10,9,8,7,6,5,4,3,2,1] Ex-26. Compute the average of the following set of values A=[3,4,2,6,4,3,7,8,5,4,5,6,7]; Ex-27. Flip left to right (fliplr) the 1D array ZAP=[1,2,3,โ€ฆ, 10]; and store the results in the new array PAZ whose elements would be PAZ=[10,9,7,โ€ฆ,1]. Alternative-1: Page 50 of 57 6 12 7 10 8 13 9 11 10 14 Ex-26. Loops. [M]. Sorting. Input three randomly selected integer values and print them in ascending order. E.g., test your code with A=3, B=2, C=1 and A=2, B=3, C=1. File: SortThree FUNCTIONS Ex-1-Functions. Write a program to print a table showing the area of circles with radii from 10-cm to 20- cm, steps of 1-cm. The area must be calculated using a user-defined function circleArea. Ex-2. Compute the average of the following set of values A=[02, 12, 22, 32, 42] The main program should I/O . Processing the average is performed by calling the function average. Solution file: arrayFunction.fprg Page 51 of 57 HARDER PROBLEMS Ex-30. Sin(x) and Do/WHILE structure. Write pseudocode to compute the series iSin(x) for a given x value until error is less than 1x10-6 ๐‘–๐‘†๐‘–๐‘›(๐‘ฅ) = โˆ‘ (โˆ’1)๐‘–๐‘ฅ(2๐‘–+1) (2๐‘– + 1)! = ๐‘ฅ1 1! โˆž ๐‘–=0 โˆ’ ๐‘ฅ3 3! + ๐‘ฅ5 5! โˆ’ ๐‘ฅ7 7! + โ‹ฏ. Error is defined as ๐‘’๐‘Ÿ๐‘Ÿ๐‘œ๐‘Ÿ = |๐‘ก๐‘Ÿ๐‘ข๐‘’ ๐‘ฃ๐‘Ž๐‘™๐‘ข๐‘’ โˆ’ ๐‘๐‘Ž๐‘™๐‘๐‘ข๐‘™๐‘Ž๐‘ก๐‘’๐‘‘ ๐‘ฃ๐‘Ž๐‘™๐‘ข๐‘’| where calculated values is the value of the series as computed with the above equation and the true value is the value given by an efficient dwarf consulting the sin(x) tables for you living within any computer system, calculator, smart phone and providing you 24/7 with the precise result by free, i.e., the sin(x) library function. The value 1x10-6 represents the allowed tolerance of the error. The partial sum should be presented as a table with values of the angle x in radians. Later we will extend the program objective to calculate sin(x) with values of the angle x in radians in the range of [0,2pi] in steps of pi/4. RECALL: Page 52 of 57 A new loop structure is introduced which verifies the condition at the end. If the condition is true the loop continues. This structure called do/while executes the loop at least once. do statements while condition Alternatively we can write the above structure as: while condition statements ... ... โ€ฆ end Forcing the condition to be true initially by assuming smart values for the variable in the condition. The algorithm in Simple Words for the first objetive: 1.- SET tolerance 2.- Print table title โ€˜xโ€™ vs โ€˜iSin(x)โ€™ 3.- 3.1. Compute each term of the series 3.2 Accumulate the sum of terms 3.3 Compute the error 3.4 Compare the error with the error tolerance 3.5.- Store or Print results of iSin(X) for each value of X. Print results as Table 3.6.- Compute next x Page 55 of 57 2.5 COMPUTE letter grade [LG] 2.6 ADD student=student +1 % student is a counter 3. END WHILE 4. PRINT score, LG FINAL PSEUDOCODE INPUT N % N is the number of students SET student=1 % the first student is 1 WHILE student<=N % For the current student INPUT scores: cp, ex1, ex2, ex3, final, qzs INPUT number of absences, abs IF abs==0 THEN att=3 ENDIF IF abs==1 THEN att =2; ENDIF IF abs>=2 THEN att =0 ENDIF Compute score = cp*0.10+ex1*0.15+ex2*0.20+ex3*0.25+(fal+qzs+att)*0.30 IF score >=90 THEN LG=โ€™Aโ€™ % LG is letter grade ENDIF IF score <90 & score >=80 THEN LG=โ€™Bโ€™ ENDIF IF score <80 & score >=70 THEN LG=โ€™Cโ€™ ENDIF IF score <70 & score >=60 THEN LG=โ€™Dโ€™ ENDIF Page 56 of 57 IF score <60 THEN LG=โ€™Fโ€™ ENDIF student=student + 1 PRINT student, score, LG % to print a TABLE student#, score, Letter Grade ENDWHILE ALGORITHM FOR INTEGER DIVISION http://tex.stackexchange.com/questions/111116/what-is-the-best-looking-pseudo-code-package APPENDIX (Sequence. Exercise 12) APPENDIX Page 57 of 57 Plin VBA Worksheet Function One of the most powerful features of programming with VBA in Excel is the ability to use functions that are built into Excel. For example, say you're writing a macro that calculates the area of a circle from the radius or diameter (the formula is of course Area = 2 * pi * 42). Instead of typing out the constant pi to a certain number of decimal places, you can use the Pi() function built into Excel. Normally if you were computing this formula in an Excel cell, you would just use Pi(); you can call the same function in VBA using the following line of code: Application.WorksheetFunction.Pi If you have a macro that uses this function, it would look something like this (using variables dblArea for the area of a circle, and sngRadius for the radius of the circle): dblArea = 2 * Application.WorksheetFunction.Pi * sngRadius * 2 While this may not seem very useful for Pi (we can easily approximate the constant to 3.14159), it becomes invaluable when using other Excel functions - for example you might use Excel's Linear Regression function to output the slope of a best fit line, or VLookup to get the value of a cell in a range. In all cases, you call up the function using Application.WorksheetFunction. Function - Excel helpfully suggests all possible functions when you type the period between WorksheetFunction and Function, so you can then just choose the function you need from the list of suggestions. You could just assign the value to a constant directly... Const P| = 3.14159265358979 Or you can let VB calculate it far you. PI= 4* ATN(1)
Docsity logo



Copyright ยฉ 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved