1.27k likes | 3.58k Views
Pseudocode. Faking it. Pseudocode. Literally – “False code” Not a ‘real’ programming language only used to define algorithms same pseudocode can be implemented in many different computer languages Many conventions to be followed:
E N D
Pseudocode Faking it
Pseudocode • Literally – “False code” • Not a ‘real’ programming language • only used to define algorithms • same pseudocode can be implemented in many different computer languages • Many conventions to be followed: • all programs begin with PROGRAM statement and BEGIN, and end with END statement • modules are defined after the main program, and begin with MODULE statement along with inputs and outputs • ‘Reserved words’: PROGRAM, BEGIN, END, MODULE, IF, THEN, ELSE, FOR, TO, STEP, CASE, IS, WHILE, REPEAT, UNTIL, AND, OR, NOT, ADDRESS, CONTENTS. • Variables are not declared, and have no type • but they still should have sensible names
Pseudocode • Program structure: • every program begins and ends in the same way.. PROGRAM my_program BEGIN statement1 statement2 …. END
Pseudocode • Layout is very important! • indentation must be used for conditional statements, loops, etc.. • one statement per line • upper case for reserved words • main program first, modules in top-down order or grouped by function • Some good habits to get into: • leave space between lines to add more code • give variables meaningful names • think first, then write • module structure, algorithm, etc.. • try it in your head or on paper first
Pseudocode Variables • In general: • do not need to be declared • have no type, and no size • Arrays: • a set of values of the same type referred to using the same label • a list of 10 numbers • a sentence consisting of 100 characters • a collection of 45 students • set and accessed using the [ ] operator • first element is element 0, last is size - 1 • examples: Set num_array[0] = 50 sets first element to 50 Set num_array[10] = 0 sets 11th element to 0 write num_array[0] to screen Prints 50
Pseudocode • Statements: • can take many forms • simple – single action, defined in simple English statement Set x = 1 Read m, c from keyboard Set y = m * x + c • module call – sqrt ( IN: x OUT: y ) • conditional – IF or CASE statement • loop – WHILE, REPEAT, FOR
Simple Statements • Simple statements should: • be unambiguous get x BAD read x from keyboard GOOD • as brief as possible multiply x by 3 and store result in variable y BAD Set y = x * 3 GOOD • follow pseudocode conventions • “Set” should be used when assigning variables • normal mathematical symbols (*, /, +, -, ^, etc..) • be simple! calculate impedence of circuit BAD calculate Fourier Transform of image VERY BAD! • make sense
Module Calls • Syntax: module_name ( IN: input1, input2, … OUT: output1, output2, … ) • both IN: and OUT: should always be present, even if there are no inputs or outputs • number and type of inputs and outputs MUST exactly match the module definition • but the names of the variables don’t have to match.. • Examples: sqrt ( IN: x OUT: y ) fft ( IN: signal OUT: signal_fft ) • How to define modules? We’ll get to that in a little bit..
Conditional Statements • IF statements: • branch program execution depending on value of a boolean expression • should be a TRUE or FALSE answer! • syntax: IF ( expression ) THEN statements... • ELSE block can also be added, to be run when the expression is FALSE IF ( expression ) THEN statements… ELSE more statements… • note the indentation - it is the ONLY way to tell when the IF statement ends!!
Conditional Statements • IF statements can also be nested • ie, one inside the other IF ( a = 1 ) THEN do something ELSE IF ( a = 2 ) THEN do something else ELSE IF ( a = 3 ) THEN some else again ELSE default behavior • obviously quite difficult to read – better way is to combine ELSE and IF into one line IF ( a = 1 ) THEN do something ELSE IF ( a = 2 ) THEN do something else ELSE IF ( a = 3 ) THEN something else again ELSE default behavior
IF Statement Examples PROGRAM quadratic BEGIN read a, b, c from keyboard Set det = b^2 – 4*a*c IF ( det < 0 ) THEN write “No roots” to the screen ELSE IF ( det = 0 ) THEN Set r1 = -b / ( 2 * a ) write “One root: “, r1 to the screen ELSE Set r1 = ( -b + det^0.5 ) / ( 2 * a ) Set r2 = ( -b – det^0.5 ) / ( 2 * a ) write “Two roots: “, r1, r2 to the screen END
Logical Operators • The standard mathematical operators for comparisons are used in pseudocode: • <, <=, =, >=, >, != • Expressions may also be combined via logical operators to form compound expressions • AND, OR, NOT IF ( a = b AND c > d ) THEN … IF ( size = 0 OR size = max ) THEN …
Invalid Expressions • Expressions controlling IF statements (and loops, etc) must be easily calculated • simple comparisons ( = <= > != etc..) • logical combinations of the above (AND OR etc) • Complex expressions should not be used, eg: • IF ( the value 7 is in the array ) THEN… • IF ( the smallest value in the array is < 10 )… • IF ( the WHILE loop above ran more than 15 times )… • IF ( day is a public holiday )… • All of these expressions are NOT VALID • the logical they represent is possible, but they must be expressed in a different manner x
Conditional Statements • CASE statement: • program branches in multiple directions depending on the value of an expression • syntax: CASE ( expression ) IS const1: statements… const2: statements… … DEFAULT: default behavior • the expression can be anything that resolves to a value • the values to be tested against must be LITERAL values
CASE Statement Example PROGRAM menu BEGIN display menu to screen read option from keyboard CASE ( option ) IS ‘a’: read num from keyboard add num to list ‘d’: delete last number from list ‘s’: write list to screen DEFAULT: write “Invalid option” to screen END
Loops • 3 distinct types of loops: • FOR..DO • executes a fixed (at start of loop) number of times • a variable (counter) keeps track of iterations • automatically incremented after each iteration • WHILE..DO • continues looping while an expression is true • condition is checked before loop begins • may loop zero or more time • REPEAT..UNTIL • continues until an expression becomes true • condition is checked at the end of the loop • must loop at least once!
FOR Loop • Syntax: FOR variable IS start TO finish STEP inc DO statements … • The process: • variable is assigned the value start before the loop begins – this happens exactly ONCE only! • before each loop iteration, variable is checked to see if it has reached finish yet – if so, terminate loop • at the end of each loop, variable is increased / decreased by inc. This happens at the end of each loop iteration.
FOR Loop var=start Y var > finish? N loop body loop body var = var+ inc
FOR Loop • Loop can only terminate once var reaches finish • STEP clause is not required • default increment is 1 if it is omitted • Common uses: • accessing or modifying entire arrays • calculating averages, max, min, std deviation, etc • running a task a fixed number of times • The loop variable (var) is often extremely useful • indicates which iteration we are on • used to index arrays • useful in performing mathematical calculations • etc, etc..
FOR Loop Examples • Reading 10 numbers from user and print: PROGRAM for_loop_test BEGIN FOR i IS 0 TO 9 DO read array[i] from keyboard FOR i IS 0 TO 9 DO print i, array[i] to screen END • Calculating average of an array of numbers: Set sum = 0 FOR i IS 0 TO ( size – 1 ) DO Set sum = sum + array[i] print “Average is “, (sum / size) to screen
WHILE Loop • Most general of the loop types • can be used to construct both of the other loops (FOR, REPEAT) • continues to loop while an expression is TRUE • loop guard is checked at beginning of each iteration of the loop • loop body must modify this expression in some way for the loop to terminate! • Syntax: WHILE ( expr ) DO statement1 statement2 …
WHILE Loop N expr = TRUE? Y loop body loop body
WHILE Loop Examples WHILE ( programming doesn’t make sense ) DO read the notes again annoy the lecturer practice Set total = 0 Set decision = “hit” WHILE ( total < 21 AND decision != “stay” ) DO deal another card total = total + card display card, total to screen IF ( total < 21 ) THEN write “Hit or stay?” to screen read decision from keyboard ELSE IF ( total = 21 ) THEN write “You have 21!” ELSE write “You Bust!” to screen Note that the loop body in these examples can change the value of the guard expression!
REPEAT Loops • Almost identical to WHILE loops, except: • condition is checked at end of loop, not start • thus, loop MUST execute at least once! • repeats until condition becomes TRUE, not while condition is TRUE • Syntax: REPEAT statement1 statement2 … UNTIL ( expression )
REPEAT Loops loop body loop body N expr = TRUE? Y
REPEAT Loops • Appropriate when loop must occur at least once: • entering a menu option (repeat until quit) REPEAT display menu to screen get user choice from keyboard UNTIL ( choice is valid )
Defining Modules • Top-down design process identifies modules which perform certain tasks • These are defined in pseudocode by: MODULE my_module ( IN: a, b, c OUT: x, y ) BEGIN module body.. END • All outputs should be defined in EVERY branch of execution • no matter what loops, conditionals, etc, are triggered • inputs do not necessarily have to be used • input variables should not be modified
Using Modules • The calling module or program specifies the variables to be used • for both inputs and outputs • the ordering of the arguments is very important • The input variables are copied to the corresponding variables in the module definition • even if the names are the same in calling module and called module, the variables are different! • each module is a different page of the notebook, thus all the variables are separate and cannot be accessed from each other • passing the variables means copying them between pages • The output variables are copied back in a similar way
Module Example PROGRAM quadratic BEGIN read a, b, c from keyboard calc_quad ( IN: a, b, c OUT: num, r1, r2) IF ( num = 0 ) THEN write “No roots” to screen ELSE IF ( num = 1 ) THEN write “One root: “, r1 to the screen ELSE write “Two roots: “, r1, r2 to the screen END
Module Example MODULE calc_quad ( IN: a, b, c OUT: num_roots, root1, root2 ) BEGIN Set root1 = 0 Set root2 = 0 Set det = b^2 – 4*a*c IF ( det < 0 ) THEN num_roots = 0 ELSE IF ( det = 0 ) THEN num_roots = 1 root1 = -b / ( 2*a ) ELSE num_roots = 2 root1 = ( -b + det^0.5 ) / (2*a) root2 = ( -b – det^0.5 ) / (2*a) END
Module Example PROGRAM quadratic MODULE calc_quad a a det 1 1 0 r1 -1.5 root1 b b -1.5 3 3 r2 c c 0 root2 9 9 0 num_roots num 1 1