Pseudocode Faking it Pseudocode n n Literally False

  • Slides: 31
Download presentation
Pseudocode Faking it

Pseudocode Faking it

Pseudocode n n Literally – “False code” Not a ‘real’ programming language n n

Pseudocode n n Literally – “False code” Not a ‘real’ programming language n n n Many conventions to be followed: n n only used to define algorithms same pseudocode can be implemented in many different computer languages 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 n but they still should have sensible names

Pseudocode n Program structure: n every program begins and ends in the same way.

Pseudocode n Program structure: n every program begins and ends in the same way. . PROGRAM my_program BEGIN statement 1 statement 2 …. END

Pseudocode n Layout is very important! n n n indentation must be used for

Pseudocode n Layout is very important! n n n 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: n n n leave space between lines to add more code give variables meaningful names think first, then write n n module structure, algorithm, etc. . try it in your head or on paper first

Pseudocode Variables n In general: n n n do not need to be declared

Pseudocode Variables n In general: n n n do not need to be declared have no type, and no size Arrays: n a set of values of the same type referred to using the same label n n n 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 11 th element to 0 write num_array[0] to screen Prints 50

Pseudocode n Statements: n can take many forms n simple – single action, defined

Pseudocode n Statements: n can take many forms n simple – single action, defined in simple English statement Set x = 1 Read m, c from keyboard Set y = m * x + c n n n module call – sqrt ( IN: x OUT: y ) conditional – IF or CASE statement loop – WHILE, REPEAT, FOR

Simple Statements n Simple statements should: n be unambiguous get x read x from

Simple Statements n Simple statements should: n be unambiguous get x read x from keyboard n as brief as possible multiply x by 3 and store result in variable y Set y = x * 3 n n “Set” should be used when assigning variables normal mathematical symbols (*, /, +, -, ^, etc. . ) be simple! calculate impedence of circuit calculate Fourier Transform of image n BAD GOOD follow pseudocode conventions n n BAD GOOD make sense BAD VERY BAD!

Module Calls n Syntax: module_name ( IN: input 1, input 2, … OUT: output

Module Calls n Syntax: module_name ( IN: input 1, input 2, … OUT: output 1, output 2, … ) n both IN: and OUT: should always be present, even if there are no inputs or outputs n number and type of inputs and outputs MUST exactly match the module definition n n but the names of the variables don’t have to match. . Examples: sqrt ( IN: x OUT: y ) fft ( IN: signal OUT: signal_fft ) n How to define modules? We’ll get to that in a little bit. .

Conditional Statements n IF statements: n branch program execution depending on value of a

Conditional Statements n IF statements: n branch program execution depending on value of a boolean expression n n should be a TRUE or FALSE answer! syntax: IF ( expression ) THEN statements. . . n ELSE block can also be added, to be run when the expression is FALSE IF ( expression ) THEN statements… ELSE more statements… n note the indentation - it is the ONLY way to tell when the IF statement ends!!

Conditional Statements n IF statements can also be nested n ie, one inside the

Conditional Statements n IF statements can also be nested n 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 n 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

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 r 1 = -b / ( 2 * a ) write “One root: “, r 1 to the screen ELSE Set r 1 = ( -b + det^0. 5 ) / ( 2 * a ) Set r 2 = ( -b – det^0. 5 ) / ( 2 * a ) write “Two roots: “, r 1, r 2 to the screen END

Logical Operators n The standard mathematical operators for comparisons are used in pseudocode: n

Logical Operators n The standard mathematical operators for comparisons are used in pseudocode: n n <, <=, =, >, != Expressions may also be combined via logical operators to form compound expressions n AND, OR, NOT IF ( a = b AND c > d ) THEN … IF ( size = 0 OR size = max ) THEN …

Invalid Expressions n Expressions controlling IF statements (and loops, etc) must be easily calculated

Invalid Expressions n Expressions controlling IF statements (and loops, etc) must be easily calculated n n n Complex expressions should not be used, eg: n n n simple comparisons ( = <= > != etc. . ) logical combinations of the above (AND OR etc) 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 n x the logical they represent is possible, but they must be expressed in a different manner

Conditional Statements n CASE statement: n n program branches in multiple directions depending on

Conditional Statements n CASE statement: n n program branches in multiple directions depending on the value of an expression syntax: CASE ( expression ) IS const 1: statements… const 2: statements… … DEFAULT: default behavior n n 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 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 n 3 distinct types of loops: n FOR. . DO n n WHILE.

Loops n 3 distinct types of loops: n FOR. . DO n n WHILE. . DO n n executes a fixed (at start of loop) number of times a variable (counter) keeps track of iterations automatically incremented after each iteration continues looping while an expression is true condition is checked before loop begins may loop zero or more time REPEAT. . UNTIL n n n continues until an expression becomes true condition is checked at the end of the loop must loop at least once!

FOR Loop n Syntax: FOR variable IS start TO finish STEP inc DO statements

FOR Loop n Syntax: FOR variable IS start TO finish STEP inc DO statements … n The process: n n n 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 var = var +

FOR Loop var=start Y var > finish? N loop body var = var + inc

FOR Loop n n Loop can only terminate once var reaches finish STEP clause

FOR Loop n n Loop can only terminate once var reaches finish STEP clause is not required n n Common uses: n n default increment is 1 if it is omitted 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 n indicates which iteration we are on n used to index arrays useful in performing mathematical calculations etc, etc. . n n

FOR Loop Examples n Reading 10 numbers from user and print: PROGRAM for_loop_test BEGIN

FOR Loop Examples n 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 n 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 n Most general of the loop types n n n can be

WHILE Loop n Most general of the loop types n n n 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 body must modify this expression in some way for the loop to terminate! Syntax: WHILE ( expr ) DO statement 1 statement 2 …

WHILE Loop N expr = TRUE? Y loop body

WHILE Loop N expr = TRUE? Y loop body

WHILE Loop Examples WHILE ( programming doesn’t make sense ) DO read the notes

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 n Almost identical to WHILE loops, except: n n condition is checked

REPEAT Loops n Almost identical to WHILE loops, except: n n 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 statement 1 statement 2 … UNTIL ( expression )

REPEAT Loops loop body N expr = TRUE? Y

REPEAT Loops loop body N expr = TRUE? Y

REPEAT Loops n Appropriate when loop must occur at least once: n entering a

REPEAT Loops n Appropriate when loop must occur at least once: n entering a menu option (repeat until quit) REPEAT display menu to screen get user choice from keyboard UNTIL ( choice is valid )

Defining Modules n n Top-down design process identifies modules which perform certain tasks These

Defining Modules n n 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 n All outputs should be defined in EVERY branch of execution n no matter what loops, conditionals, etc, are triggered inputs do not necessarily have to be used input variables should not be modified

Using Modules n The calling module or program specifies the variables to be used

Using Modules n The calling module or program specifies the variables to be used n n n 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 n even if the names are the same in calling module and called module, the variables are different! n n n 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:

Module Example PROGRAM quadratic BEGIN read a, b, c from keyboard calc_quad ( IN: a, b, c OUT: num, r 1, r 2) IF ( num = 0 ) THEN write “No roots” to screen ELSE IF ( num = 1 ) THEN write “One root: “, r 1 to the screen ELSE write “Two roots: “, r 1, r 2 to the screen END

Module Example MODULE calc_quad ( IN: a, b, c OUT: num_roots, root 1, root

Module Example MODULE calc_quad ( IN: a, b, c OUT: num_roots, root 1, root 2 ) BEGIN Set root 1 = 0 Set root 2 = 0 Set det = b^2 – 4*a*c IF ( det < 0 ) THEN num_roots = 0 ELSE IF ( det = 0 ) THEN num_roots = 1 root 1 = -b / ( 2*a ) ELSE num_roots = 2 root 1 = ( -b + det^0. 5 ) / (2*a) root 2 = ( -b – det^0. 5 ) / (2*a) END

Module Example PROGRAM quadratic a MODULE calc_quad a det 1 r 1 1 0

Module Example PROGRAM quadratic a MODULE calc_quad a det 1 r 1 1 0 b -1. 5 b root 1 3 -1. 5 c root 2 3 c 9 r 2 0 num 1 9 num_ roots 1 0