PSEUDOCODE - Colombo Británicotech.colombobritanico.edu.co/cswebsite/pdfs/4-2/Pseudocode.pdfan...
Transcript of PSEUDOCODE - Colombo Británicotech.colombobritanico.edu.co/cswebsite/pdfs/4-2/Pseudocode.pdfan...
PSEUDOCODE
It is a conventional code to represent an algorithm
PSEUDOCODE
It is a conventional code to represent an algorithm
PSEUDOCODE NOTATION
Refers the syntax used to write an algorithm in pseudocode
PSEUDOCODE NOTATION
Start an algorithm Algortihm NameOfTheAlgorithm {Finish an algorithm }
Data Types
Primitives DataInteger number intReal number (Floating point) doubleCharacter (single alphanumeric symbol) charBoolean data (FALSE/TRUE) boolean
Objects DataString (collection of chars) String
Data Types
Default valuesint 0double 0.0char ‘ ‘boolean FALSEString null
Char values should be shown between ‘ ‘String values should be shown between “ “
Variable
Is an abstract field which represent a storage location with a particular name.
Abstract Field
Physical storage location
Is a reference of
Variable
Different types of data could be stored in variables. Those data could change their value depending of different operations done with them
45 Data stored * 2 90
Naming a variable
• Is convenient to label the storage location with a name:• Variable names are letters (A..Z, a..z) combined with decimal digits (0..9) and the
underline symbol (_)• No length limits• No allowable special symbols (#$%&/()[]{}.,;!|…)• Variable names are case sensitive • “Variable names are all capitals, for example, CITY”• Self-documented names
Assigning values
To store a value in a variable, the assignment operation should be done:
“Values will be assigned using = “, for example:AGE=35FIRSTNAME_OF_CLIENT=“Fernando”STATUS=TRUEGENDER=‘F’AREAOFCIRCLE=56.2345
Assigning values
Naming a variable
AGE
Assigning a value 45
AGE
AGE = 45
Creating a variable
To create the abstract field and the storage location of a variable, a “declaration”sentence has to be executed. This operation should be done previously to startusing the variable
Declaration syntax:
Data type variable_name = value ;Type of the data
to be storedName of the
variable
Assignment operation
Value to be stored
Sentence separator
Output information
Operation that indicates data is output in an output device: printer, screen, …Output syntax:• output (“Prompt”); The label is shown in an output device• output (variable); The content of the variable is shown an output device• output (“Prompt” + variable); The label and the content of the variable is
shown in an output device output (“Label” + variable);+ in this context is called “concatenation” operator, and it
means link the label and the variable value
Example
Problem: Given the value of a temperature in Celsius degrees, calculate the equivalentFahrenheit degrees value
Algorithm TemperaturesConvertion {double CELSIUS=0.0;double FAHRENHEIT=0.0;CELSIUS=37;FAHENHEIT=(9/5)*CELSIUS+32;output (CELSIUS+” °C are equivalent to “+FAHRENHEIT+” °F”);}
Input Data
Operation that permits to capture data from an input device and stores it in a variable.There are different instructions to input data for every data type.Input syntax:• inputString(String prompt); to get a String value • inputInt(String prompt); to get an integer value• inputDouble(String prompt); to get a double value• inputChar(String prompt); to get a char value• inputBoolean(String prompt); to get a boolean value
Example
Problem: Given the value of a temperature in Celsius degrees, calculate the equivalentFahrenheit degrees value
Algorithm TemperaturesConvertion {double CELSIUS=0.0;double FAHRENHEIT=0.0;CELSIUS=inputDouble(“Type the temperature in Celsius degrees”);FAHENHEIT=(9/5)*CELSIUS+32;output (CELSIUS+” °C are equivalent to “+FAHRENHEIT+” °F”);}
Operators
Arithmetic Operators:Relational Operators: Logic operators:
+ - * / %> >= < <= == !=&& || !
Are symbols to establish an arithmetic, logic or relational operations between data
Arithmetic Operators
Operator Computes Syntax Category
+ the sum of its two operands a + b Additive
- subtracts the second operand from the first
a - b Additive
* the product of its operands a * b Multiplicative
/ divides its first operand by its second operand
a / b Multiplicative
% the remainder after dividing its first operand by its second a % b Multiplicative
Relational Operators
Operator Computes Syntax Category
> Greater than a > b Relational
>= Greater than or equals to a >= b Relational
< Less than a < b Relational
<= Less than or equals to a <= b Relational
== Equals to a == b Relational
!= Is not equal to a != b Relational
Logical Operators
Operator Computes Syntax Category
&& Are both values TRUE? P1 && P2 Logic
|| Is, at least, one value TRUE? P1 || P2 Logic
! Is the opposite logical value !P1 Logic
Operators Precedence Category Operator Asociativity
Postfix ( ) Left to Right
Unary ! Right to Left
Multiplicative * / % Left to Right
Additive + - Left to Right
Relational < <= > >= Left to Right
Equality == != Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Assignment = Right to Left
Functions
Are pre-designed formulas to execute particular and complex calculations• sqrt(value) calculates the square root of a value• pow(base,power) calculates the result of an exponential expression 𝑥𝑥𝑦𝑦• abs(value) calculates the absolute value of a quantity • :• :
Exercise
In an University, the final grade of a subject is calculated by the weighted average ofthree grades. The weights of the grades are given as percentages respectively: 20% tothe first grade, 25% to the second grade and 55% to the third one, respectively. Developan algorithm, in pseudocode, which takes the personal information of any student andcalculate the final grade of a subject.
Exercise
La instalación de criaderos de peces, en una zona rural del Valle del Cauca, exige lacompilación de ciertos datos relacionados con los pescados que allí van a sembrarse: laespecie, la talla (el largo del pez) y el peso, serán características que en cada criaderose determinarán mediante sensores especiales de tecnología de control. Implementar unalgoritmo registre y calcule los datos necesarios para dar una información eficaz decualquier pez.
El factor de densidad lineal es un valor que permite generalizar y calcular el peso, dadosolamente el tamaño y que en este caso será 1.75.
CONTROL FLOW STATEMENTS
“Break up the flow of execution by employing decision making, looping, andbranching, enabling your program to conditionally execute particular blocks ofcode”
CONDITION
Is an expression which involves relational and/or logic operators. A boolean value is the result of a condition evaluation
Examples:AGE >=35AREA<23.7 AND SHAPE=“CIRCLE”
Tip: relational operators: > < >= <= ≠ ==Logic operators: AND OR NOT
if then STATEMENT
“It tells your algorithm to execute a certain section of code only if a particular test, of a condition, evaluates to true”
Syntaxif (condition) then
sentences for TRUE value;endif
if then STATEMENT
Example:A web site has implemented a routine that gives the access to its content only if the user type an appropriate password. Implement an algorithm to solve this situation
Algorithm AccessGranted{String PASSW=“AZ123b”, PASSUSER=null;PASSUSER=inputString(“Type the password”);if (PASSUSER=PASSW) thenoutput(“Welcome to the web site”);endif}
if then else STATEMENT
“The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false”
Syntaxif (condition) then
sentences for TRUE value;else
sentences for FALSE value;endif
if then STATEMENTExample:A web site has implemented a routine that gives the access to its content only if the user type anappropriate password; in other case a pop up window will notices the wrong password. Implement analgorithm to solve this situation
Algorithm AccessGranted{String PASSW=“AZ123b”, PASSUSER=null;PASSUSER=inputString(“Type the password”);if (PASSUSER=PASSW) thenoutput(“Welcome to the web site”);elseoutput(“Access hasn’t be granted !!!”);endif}
EXERCISESProblem 1:“Write an algorithm that recommends the number of calories a person should eat each day. Calories areunits of energy found in all foods. Base your recommendation on the person's weight and whether theperson has an active or sedentary (inactive) lifestyle. If the person is sedentary, that person's activityfactor is 13. If the person is active, that person's activity factor is 15. Multiply the activity factor by theperson's weight to get the recommended number of calories”
Problem 2:A code program to detect and advertise when a driver exceeds speed limits is required to be burned ina ROM memory and to be installed in a special device which will be used by the highway police.Develop a pseudocode of the algorithm to sketch the real program.
Problem 3:Given a natural number, determine if it is an odd or even number
Problem 4:Given two natural numbers A and B, determine if B is divisor of A
NESTED CONTROL FLOW STATEMENTSConsist of the combination or the link of two or more control flow statements to increase the functionalpower of an algorithm
NESTING IF THEN ELSE STATEMENTSSyntaxif (condition1) thensentences for TRUE value of condition 1;else if (condition2) thensentences for TRUE value of condition 2;else if (condition3) thensentences for TRUE value of condition 3;else if …..elsesentences for FALSE value all conditions;endif
if then STATEMENTExample:Classify a triangle given the three sides length
Algorithm Triangles {double SIDEA=0.0, SIDEB=0.0, SIDEC=0.0;SIDEA=inputDouble(“Length of side A”);SIDEB=inputDouble(“Length of side B”);SIDEC=inputDouble(“Length of side C”);if (SIDEA==SIDEB AND SIDEB==SIDEC) thenoutput (“Equilateral triangle”);else if (SIDEA==SIDEB OR SIDEA==SIDEC OR SIDEB==SIDEC) thenoutput (“Isosceles triangle”);else output (“Scalene triangle”);}
EXERCISES
Problem 1:Write a program to determine the cost of an automobile insurance premium, based on driver's age andthe number of accidents that the driver has had. The basic insurance charge is $500. There is asurcharge of $100 if the driver is under 25 and an additional surcharge for accidents:
# of accidents Accident Surcharge1 502 1253 2254 or more No insurance
EXERCISES
Problem 2:Windows performs a date format in two ways: a short format which shows the date as mm / dd / yyyy;and a long format mmmm-dd-yyyy
September-11-2013 (long format), 9/11/2013 (short format)
Implement an algorithm, in pseudocode, that permits to convert a format date from short to long format
EXERCISES
Problem 3:El personal que acude a un gimnasio deportivo se puede clasificar en “socios” o en“invitados”. El gimnasio cobra una tarifa fija por hora (no se cobran fracciones de la hora),pero para los socios hay un descuento del 20 % del valor a pagar . Además, para fomentar elejercicio físico en adultos mayores, el gimnasio ofrece un descuento adicional del 10% delvalor a pagar, a todas las personas con edad de 40 o más años. Desarrollar el algoritmo enpseudocódigo que permita calcular el valor a pagar por la utilización del gimnasio, de unapersona cualquiera
EXERCISES
Problem 4:• Given the Cartesian coordinates of a point P (x , y), calculate Polar coordinates of P (r , θ)• Given the polar coordinates of a point P (r , θ), calculate Cartesian coordinates of P (x , y)
Use the following information
FLOW CHART
It’s a graphic data representation of an algorithm.
Symbols:
Perform a Task
Manual Input
Start
EndDecision
Documentt
Display
Example Problem: Given the value of atemperature in Celsius degrees, calculatethe equivalent Fahrenheit degrees value
Algorithm TemperaturesConvertion {double CELSIUS=0.0;double FAHRENHEIT=0.0;CELSIUS=inputDouble(“Type the temperature in Celsius degrees”);FAHENHEIT=(9/5)*CELSIUS+32;output (CELSIUS+” °C are equivalent to “+FAHRENHEIT+” °C”);}
Start
CELSIUS=0.0
FAHRENHEIT=0.0
CELSIUS=inputDouble(“Type the temperature in Celsius degrees”)
FAHENHEIT=(9/5)*CELSIUS+32
output (CELSIUS+” °C are equivalent to “+FAHRENHEIT+” °C”);
End
while loop STATEMENT
“The while statement continually executes a block of statements while a particular condition is true”
Syntaxloop while conditionstatements;end loop
Condition StatementsYES
NO
while loop STATEMENT
Example: Print the first 5 even numbers out
Algorithm Serie1 {int COUNTER=1;loop while COUNTER < 5output(COUNTER*2+”\n”);COUNTER=COUNTER+1;end loop}
while loop STATEMENT
Example: Print the first 5 even numbers out
Algorithm Serie1 {int COUNTER=1;loop while COUNTER < 5output(COUNTER*2+”\n”);COUNTER=COUNTER+1;end loop}
A loop counter is a variable that increments or decrements its value
with a fixed quantity
COUNTER variable is a “loop counter”
while loop STATEMENT
Example: Print the following series numbers: 300, 250, 200, 150, 100, 50, 0
Algorithm Serie2 {int COUNTER=300;loop while COUNTER > -1output(COUNTER+”\n”);COUNTER=COUNTER-50;end loop}
while loop STATEMENT
Example: Determine the final printing of the following algorithm
Algorithm Serie1 {int COUNTER=0, NUMBER=0, ACUM=0;loop while COUNTER < 4NUMBER=inputInt(“Type a natural number”);ACUM=ACUM+NUMBER;COUNTER=COUNTER+1;end loopoutput(“The result is “+ACUM);}
while loop STATEMENT
Example: Determine the final printing of the following algorithm
Algorithm Serie1 {int COUNTER=0, NUMBER=0, ACUM=0;loop while COUNTER < 4NUMBER=inputInt(“Type a natural number”);ACUM=ACUM+NUMBER;COUNTER=COUNTER+1;end loopoutput(“The result is “+ACUM);}
A loop accumulator is a variable that increments or decrements its
value with a variable quantity
ACUM variable is a “loop accumulator”
while loop STATEMENT
Loop counter and loop accumulator operators:
N++ is equivalent to N=N+1N-- is equivalent to N=N-1
N+=c is equivalent to N=N+cN-=c is equivalent to N=N-cN*=c is equivalent to N=N*cN/=c is equivalent to N=N/c
Loop counter
If c is a constant value N is a loop counter
If c is a variable value N is a loop
accumulator
while loop STATEMENT
TRACE TABLE is a table used to test an algorithm by tracing the values of its variables during the algorithm flow
Variable 1 Variable 2 Variable 3 output
value value value value
value value value value
value value value value
while loop STATEMENT
Example: Determine the final printing of the following algorithm
Algorithm Serie1 {int COUNTER=0, NUMBER=0, ACUM=0;loop while COUNTER < 4NUMBER=inputInt(“Type a natural number”);ACUM=ACUM+NUMBER;COUNTER=COUNTER+1;end loopoutput(“The result is “+ACUM);}
Trace TableCOUNTER NUMBER ACUM OUTPUT
0 0 0
1 5 5 Type a natural number 5
2 2 7 Type a natural number 2
3 6 13 Type a natural number 6
4 3 16 Type a natural number 3
The result is 16
while loop STATEMENT
Exercises: 1. Print a sequence of asterisk characters depending of a given value2. Read and print values entered by a user until a particular sentinel value is
encountered. Do not print the sentinel value. Assume the sentinel value is stored in a constant called SENTINEL.
3. Print the numbers between LOW and HIGH that are evenly divisible by four but not by five.
4. Given a natural number, determine if it is a “perfect number”5. Generate the “Fibonacci numbers”
from/to loop STATEMENT
Syntaxloop counter from counter initial value to counter final value statements;end loop
Condition (involving
the counter)
NO
YES
counter declaration
statements
counter increasing/decreasing
from/to loop STATEMENT
Example: Write and algorithm in pseudocode to calculate the average of the students ages in a certain classroom
Algorithm TheAverage {int QUANTITY=0, COUNTER=0, ACUM=0, AGE=0;QUANTITY=inputInt(“Type the quantity of students”);loop COUNTER from 1 to QUANTITYAGE=inputInt(“Type the age”);ACUM += AGE;end loopoutput (“The average is “+(ACUM/QUANTITY));}
from/to loop STATEMENT
Example: Given a quantity of natural numbers, compute the sum of the odd numbers between 1 and the final number
Algorithm SumOdd{int QUANTITY=20, COUNTER=0; acum=0;QUANTITY=inputInt(“Type the amount of numbers”);loop COUNTER from 1 to QUANTITYif(counter mod 2 ≠ 0) thenACUM += NUMBER;end ifend loopoutput (“The sum is “+ACUM);}
from/to loop STATEMENT
Exercises: 1. Given a positive integer number, calculate its factorial2. “Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below,
where n=50. “
3. “Write a program called ComputePI to compute the value of π, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing π?”
loop STATEMENTS
4. Write an algorithm in pseudocode to find out if a number is prime5. Develop the trace table to the following algorithm:
Algorithm Special {int N=0,M=0;N=inputInt (“Type a positive integer number”);loop while N>0N/=10;M++;end loopoutput (“Value “+M);
}
Approved notation for developing pseudocodehttp://occ.ibo.org/ibis/documents/dp/gr5/computer_science/d_4_comsc_sup_1201_1b_e.pdf
International Baccalaureate Organization 2012 IB Java Examination Tool Subset (JETS)http://occ.ibo.org/ibis/documents/dp/gr5/computer_science/d_4_comsc_sup_1201_1a_e.pdf
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.htmlhttp://visualbasic-dotnet-hindi.blogspot.com/2013/01/control-flow-statements.html