Fundamentals of Procedural Programming
Transcription
Fundamentals of Procedural Programming
Programming Glossary HIT1301 - Algorithmic Problem Solving Swinburne University of Technology Alex Cummaudo 1744070 June 19, 2013 cation Technologies Programming 1 nters and dynamic memory management. This will Abstract e programs including: and write values memory This glossary demonstrates my understanding of the concepts covered throughout HIT1301 Algorithmic Problem Solving. This is achieved via a discussion of what programs are compromised of, the programming concepts behind them, how they can be used (including various case studies and examples), and the conventions in writing programs. The document is able to highlight a good understanding of each concept covered across all intended learning outcomes for this subject. lp with this topic: ng video podcasts on iTunesU of the following material at the start of the 11th lecture. o your glossary m using a dynamic array 1 CONTENTS Alex Cummaudo 1744070 Contents 1 Programming Overview 1.1 Instructions and Data . . . . . . . . 1.2 Variables . . . . . . . . . . . . . . . . 1.3 Functional Decomposition . . . . . . 1.4 Arrays and Data Processing . . . . . 1.5 Iterative Design . . . . . . . . . . . . 1.5.1 Case Study - Pop Game . . . 1.6 Good Programming Practices . . . . 1.6.1 Case Study - Messy Program 2 Programming Command Line Tools 2.1 cd - Change Directory . . . . . . . 2.2 fpc - Free Pascal Compiler . . . . . 2.3 ./helloworld - Running Programs 2.4 ./build.sh . . . . . . . . . . . . . 2.5 ./run.sh - Running a SwinGame . 2.6 gcc - GNU Compiler Collection . . 3 Programming Terms 3.1 Statement . . . . . 3.2 Expression . . . . . 3.3 Identifier . . . . . . 3.4 Parameter . . . . . 3.5 Local Variables . . 3.6 Global Variables . . . . . . . . . . . . . . 4 Programming Concepts 4.1 Control Flow . . . . . 4.1.1 Sequence . . . . 4.1.2 Selection . . . . 4.1.3 Repetition . . . 4.2 Indentation . . . . . . 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 6 6 6 7 7 8 9 9 . . . . . . 11 11 11 11 11 12 12 . . . . . . 13 13 13 13 13 13 14 . . . . . 15 15 15 15 15 16 Alex Cummaudo 1744070 4.3 4.4 CONTENTS Functional Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . Iteration of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Programming Artefacts 5.1 Program . . . . . . . . . . . . . . . . . . . . . . . . . 5.1.1 Program Execution . . . . . . . . . . . . . . . 5.1.2 Example: Hello World . . . . . . . . . . . . . 5.2 Procedure . . . . . . . . . . . . . . . . . . . . . . . . 5.2.1 Procedure Execution . . . . . . . . . . . . . . 5.2.2 Example: DrawHouse . . . . . . . . . . . . . 5.3 Function . . . . . . . . . . . . . . . . . . . . . . . . . 5.3.1 Function Execution . . . . . . . . . . . . . . . 5.3.2 Example: A Basic Adder . . . . . . . . . . . . 5.4 Constant . . . . . . . . . . . . . . . . . . . . . . . . . 5.4.1 Example: Constantly Craving PI . . . . . . . 5.5 Variable . . . . . . . . . . . . . . . . . . . . . . . . . 5.5.1 Local Variable Creation . . . . . . . . . . . . 5.5.2 Parameter Creation . . . . . . . . . . . . . . . 5.5.3 Example: myAge in xYears . . . . . . . . . . 5.6 Array . . . . . . . . . . . . . . . . . . . . . . . . . . 5.6.1 Example: My Five subjects . . . . . . . . . . . 5.7 Record / Structure . . . . . . . . . . . . . . . . . . . 5.7.1 Example: Products in a Supermarket . . . . 5.8 Enumeration . . . . . . . . . . . . . . . . . . . . . . . 5.8.1 Example: Seasons use MonthData . . . . . . . 5.9 Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . 5.9.1 Pointer Creation and Assignment . . . . . . . 5.9.2 Example: Cheese and what it goesNiceWith 6 Programming Statements 6.1 Procedure Call . . . . . . 6.1.1 Actions Performed 6.1.2 Examples . . . . . 6.1.3 Example 1: Calling . . . a . . . . . . . . . . . . delay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 19 . . . . . . . . . . . . . . . . . . . . . . . . 22 24 24 27 28 28 28 30 30 30 31 31 32 32 32 34 36 37 38 38 42 42 45 46 47 . . . . 50 51 51 52 52 3 CONTENTS 6.2 6.3 6.4 6.5 6.6 6.7 4 Alex Cummaudo 1744070 6.1.4 Example 2: Calling a Read/scanf . . . . . . . . . . 6.1.5 Example 3: Tick . . . . . . . . . . . . . . . . . . . . Function Call . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2.1 Actions Performed . . . . . . . . . . . . . . . . . . . 6.2.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . 6.2.3 Example 1: Assignment Statement with Function Call 6.2.4 Example 2: Function Call to get parameter value . . 6.2.5 Example 3: Function Call in a condition . . . . . . . Assignment Statement . . . . . . . . . . . . . . . . . . . . . 6.3.1 Actions Performed . . . . . . . . . . . . . . . . . . . 6.3.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . 6.3.3 Example 1: Assign This . . . . . . . . . . . . . . . . 6.3.4 Example 2: Add This . . . . . . . . . . . . . . . . . . 6.3.5 Example 3: Divide This . . . . . . . . . . . . . . . . If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.1 Actions Performed . . . . . . . . . . . . . . . . . . . 6.4.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . 6.4.3 Example 1: If One is One . . . . . . . . . . . . . . . 6.4.4 Example 2: Name Game . . . . . . . . . . . . . . . . 6.4.5 Example 3: Number Guess Checker . . . . . . . . . . Case Statement . . . . . . . . . . . . . . . . . . . . . . . . . 6.5.1 Actions Performed . . . . . . . . . . . . . . . . . . . 6.5.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . 6.5.3 Example 1: Yes or No . . . . . . . . . . . . . . . . . 6.5.4 Example 2: Seventies, Eighties or Nineties? . . . . . While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.6.1 Actions Performed . . . . . . . . . . . . . . . . . . . 6.6.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . 6.6.3 Example 1: The Pre Test . . . . . . . . . . . . . . . 6.6.4 Example 2: Count to Ten . . . . . . . . . . . . . . . 6.6.5 Example 3: Infinite While Loop . . . . . . . . . . . . Repeat Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.7.1 Actions Performed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 54 56 56 57 57 58 59 60 60 61 61 62 63 64 64 66 66 68 72 74 74 75 75 78 81 81 82 82 84 86 88 88 Alex Cummaudo 1744070 6.8 6.7.2 Examples . . . . . . . . . . . . 6.7.3 Example 1: The Post-Test . . . 6.7.4 Example 2: Count to Ten . . . 6.7.5 Example 3: Infinite Repeat Loop For Loop . . . . . . . . . . . . . . . . . 6.8.1 Actions Performed . . . . . . . 6.8.2 Examples . . . . . . . . . . . . 6.8.3 Example 1: Print Subjects . . . 6.8.4 Example 2: Count Down . . . . 6.8.5 Example 3: Infinite For Loop . CONTENTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 . 90 . 92 . 94 . 96 . 96 . 98 . 98 . 100 . 102 5 1 PROGRAMMING OVERVIEW 1 1.1 Alex Cummaudo 1744070 Programming Overview Instructions and Data A program is simply a set of instructions, and the data supplied by the program changes how those sets of instructions work together to make a program work as intended. In relation to week one’s lab work, instructions carried out were mainly graphical representations of what code can do. For example, the ClearScreen procedure is an instruction to wipe the game canvas clean, and requires a parameter, ColorWhite for example. Parameters allow programmers to alter how instructions are run so that the program can then behave in a certain way. From this, it is clear how instructions and data work to complement each other, whereby data is used to modify the behaviour of instructions. This is core to procedural programming. 1.2 Variables Variables can be likened to different kinds (types) of containers which store single pieces of data. These containers can both be read and assigned data. By use of assignment statements, the data is appended to the variable’s place in memory— variables can hence be read and changed. Different variables have different types, which allows the computer to interpret what kind of data has been stored by that variable. This is done by altering the amount of memory assigned to the variable. By changing values, we have richer and more dynamic programs that allow for user input. 1.3 Functional Decomposition Functional decomposition allows difficult and complex functionality in a program to be broken apart into as many small (and simpler) parts as possible. Without functional decomposition, complex and longer programs would be far more harder to implement—the user input functions completed in week five is an example of using functional decomposition. It saves having to unnecessarily rewrite code multiple times; programmers simply reuse code by calling procedures or functions over and over again. Functional decomposition allows a programmer not to think about all the details that 6 Alex Cummaudo 1744070 1 PROGRAMMING OVERVIEW are required; by breaking down problems down into smaller parts, the whole problem does not need to be assessed—only the part of the problem that the programmer is working on. The programmer does not need to know how printf or WriteLn works; they just need to call it to use it; an example of functional decomposition. The ReadIntegerRangefunction would be far longer and complex since it depends on ReadInteger, which in itself depends on ReadString. Rather than having to recode all the blocks in the other two functions that are within ReadIntegerRange, functional decomposition allows developers to call these other functions just once. More is discussed on Functional Decomposition in Section 1.3. 1.4 Arrays and Data Processing Arrays can store very large amounts of data under one variable, making them a very efficient way to process multiple amounts of data in very few lines of code. Arrays are created with a set data type, meaning that every index of an array is of the same type. If, say, the statistics program made in week five did not have arrays, then each value would need to be manually calculated with reference to different variables (think of not having an array of integers with 20 elements—20 integer variables would instead need to be defined!). Arrays can then be processed using loops which can iterate through every index’s value within an array. Not using arrays for data processing is very cumbersome since iterations would not be possible. Different variable identifiers would exist without the one array—thus, loops could not be applied to process the variable’s data as identifiers are constantly changing. For loops help greatly in that they can iterate through every value of the array and process it in whatever ways required—this is where the true power behind arrays is revealed, since processing hundreds of indexes within the array can be done in just one for loop with very few lines of code. 1.5 Iterative Design Creating programs gradually, whereby programs grow with each progressive iteration, is known as iterative design. A new iteration with each new iteration of 7 1 PROGRAMMING OVERVIEW Alex Cummaudo 1744070 the program adds a new feature or concept, and consistently doing this allows for complex programs to be easily built. 1.5.1 Case Study - Pop Game The Pop Game made in week six (see Figure 1) is a good example of iterative design. A custom data type was included in the program’s first iteration—a Shape defined the major entity of the game and therefore it made sense to include this first. Procedures and functions allowed for functional decomposition to be achieved, whereby the program was broken into a series of small individual tasks—CreateShape defined where a shape was, while DrawShape drew this defined shape onto the screen etc. An array of the Shape type variables was then introduced in a later iteration, under an overarching data type created called PopGameData. Through this, data could easily be transferred across the procedures and functions, utilising pass by referencing to alter a variable over more than one stack-frame. By introducing an enumeration, ShapeTypes, case statements were utilised to control the sequence of the program—so that the program responded differently depending on the ShapeType at each index of the Shape array (e.g., draw a triangle if shape.kind was of the ShapeType called Triangle etc.) Thus, the Pop Game is a good example of how a program can utilise control flow to better make use of code (via repetitional loops, if/case statements etc.), data control to better organise data (by combining attributes of an entity into one, custom data type), and functional decomposition to have less complexity in code (since the program is broken up into the smallest, individual components, each with just one task.) 8 Figure 1: My Pop Game at work! Alex Cummaudo 1744070 1.6 1 PROGRAMMING OVERVIEW Good Programming Practices In terms of good programming practices, three items should come to mind: 1. Readability of code: How well are the language-specific programming conventions used? 2. Structure of code: How visible are the blocks of code? Are they distinctly separated? 3. Meaning of code: How well are identifiers named? Humans are unable to interpret meaning unless there is clarity in code, and as such, the understandability of code is imperative to being able to interpret (and hence debug) why a program should or shouldn’t work. All three items help programmers understand each others work. The following case study helps to explain. 1.6.1 Case Study - Messy Program The messy program from week four had poor structure, meaning and readability. For starters, the entire program was coded in one line. Although the computer is able to interpret this one, gigantic line of code, humans definitely would have trouble reading it since it lacks proper indentation to signify where blocks of code are. Structure charts and sequence diagrams are good tools to avoid having little structure within the program, and should immediately be utilised from the initial design of programs. The messy program clearly made no use of these tools, as no functional decomposition was utilised; code was unnecessarily duplicated (again, visualising functional decomposition helps when a structure chart or sequence diagram is used and vice-versa). Proper procedures and functions should be written to avoid a developer having to change multiple lines of code when they would have just needed to change one variable. Little functional decomposition makes debugging a nightmare, since there may be errors in just one part of code duplication; where a function or procedure is used, the error would only exist in that function or procedure—fixing the bug there would fix it every time the function or procedure is called. The program had very bad meaning behind some of the variable names chosen. Fred, Wilma and Barney respectively replaced the meaning behind Colour, X Position and Y 9 1 PROGRAMMING OVERVIEW Alex Cummaudo 1744070 Position. The only way to interpret their true meanings was to see how the variable names were used; looking at the duplication of wilma as the parameter for xPos in DrawCricle was the only way to understand its meaning. By indenting, renaming variables to their proper meaning, and adding procedures and functions where appropriate, it was easy to understand what the program did. Initially, the program made little sense only when: • the blocks could be visualised in their proper order, • duplicated code was removed and compiled into one, appropriate procedure, i.e. DrawBike • illogical variable names were renamed into something more meaningful (xPos, yPos). Only after understanding the program could features be added as required. The changes made the code more readable, easier to interpret, and since there was better use of functional decomposition, debugging the program was relatively easy. Figure 2: The messy program, no longer messy... with added features! 10 Alex Cummaudo 1744070 2 2 PROGRAMMING COMMAND LINE TOOLS Programming Command Line Tools Each of the following commands are necessary to run programs from the terminal. 2.1 cd - Change Directory Change Directory changes the terminal’s current working directory to the directory specified. For example: • cd ~/ changes the working directory to the user’s home folder and, • cd ../ would refer to changing the working directory up one folder. 2.2 fpc - Free Pascal Compiler Free Pascal Compiler compiles raw, human-readable pascal source code and translates it into a machine-readable executable file. For example, fpc -S2 helloworld.pas would compile the helloworld.pas file into an executable file called helloworld 2.3 ./helloworld - Running Programs This is an example of how to run an executable file (named helloworld). The ./ refers that the file, helloworld, is located within the terminal’s current directory. Usually a Hello World program is the first program created in a newly learnt language. 2.4 ./build.sh Building a SwinGame ./build.sh is a bash script which compiles SwinGame binaries made in the SwinGame SDK. It uses: • a Pascal or C source code file • extra resources (such as images, sounds, fonts etc.) 11 2 PROGRAMMING COMMAND LINE TOOLS 2.5 Alex Cummaudo 1744070 ./run.sh - Running a SwinGame ./run.sh is a a bash script which runs the executable build complied from the build.sh script file. This script is required in order run a program build using the SwinGame SDK. 2.6 gcc - GNU Compiler Collection The GNU Compiler Collection, like the FPC, compiles source code written in C (as well as C++, Objective-C, Fortran, Java etc.) into a machine-readable executable. For example, gcc -o helloworld helloworld.c would compile the C source code file, helloworld.c file into an executable file (helloworld) 12 Alex Cummaudo 1744070 3 3 PROGRAMMING TERMS Programming Terms The following terms have specific meanings for software developers. It is important to understand these terms, as they will be used to communicate ideas. Parameters, Local Variables and Global Variables are discussed further in Section 5.5. 3.1 Statement An action which commands the computer to do something within the program; programs run these statements (along with appropriate variables, procedures etc.) and as a collection, these statements run the program. 3.2 Expression Data within a statement either in a literal form (e.g. 47) or is calculated from other values to produce a calculated value (e.g. 40 + 7.) 3.3 Identifier A name given to programming artefacts so that the compiler can identify them while compiling its source code. A keyword is a special kind of identifier which are specific to the language (i.e. case cannot be a variable name since it is a keyword.) 3.4 Parameter Special variables that accept values (arguments) when calling a procedure. The parameter passes the argument for use within that procedure. 3.5 Local Variables Variables declared within a procedure or function and only exist within that procedure or function. 13 3 PROGRAMMING TERMS 3.6 Alex Cummaudo 1744070 Global Variables Variables declared outside a procedure or function can be referenced within any procedure and in the program’s code. It is best to avoid using global variables since it is hard to keep track of them. 14 Alex Cummaudo 1744070 4 4 PROGRAMMING CONCEPTS Programming Concepts The following concepts are central to procedural programming. 4.1 Control Flow Control flow allows for more dynamic programs, whereby programs are made up of three different types of blocks—sequence, selection and repetition blocks. All blocks have a single entry and (sometimes multiple) exit point(s), thereby making them easy modules to ‘plug’ into code. 4.1.1 Sequence Code is run one instruction at a time, one after another until the end of the block is found. Sequence blocks execute code in sequence, that is, it starts from the top of the block and executes each line of code one after the other until the end of the block is found. Sequence blocks are the simplest form of control flow blocks. 4.1.2 Selection Selection blocks make decisions as to which blocks need to be executed, based on certain conditions. Selection blocks test for a condition (i.e. there is a decision point in the code for the computer to make), and based upon the results of the condition, different paths executing different code are taken. This is known as branching—a variety of branches with different instruction can be followed. By using selection blocks, code becomes more dynamic since not all instructions are executed, rather only those that should be executed are executed depending on the conditions set by the programmer. The two main forms of selection blocks are if statements and case or switch statements, both of which are explained later in this glossary (see Section 6.) 4.1.3 Repetition Repetition blocks repeat their instructions, based on certain conditions. 15 4 PROGRAMMING CONCEPTS Alex Cummaudo 1744070 Repetition blocks repeat the same instructions within their block until a certain condition has been met. Repetition blocks allow for better and more dynamic code since the same instructions do not have to be duplicated in order for the computer to repeat them. Instructions that need to be repeated simply needs to be in a repetition block, thereby reducing the amount of lines in the code, making programs run more efficiently. The two main forms of repetition blocks are pre-test and post-test repetition blocks. They vary in keyword terminology depending on the language of the program, nonetheless they are further explained later in this glossary (see Section 6.) 4.2 Indentation Indentation allows developers to visibly see where each block is. Indentation starts at the first line of the block and ends after the end of the last line of the block. Without indentation, the blocks become harder to see and easier to miss, which can make debugging a lot more of a pain to the developer. Here is an example in C: Example in C int main() 1 { 2 3 4 5 6 7 8 9 10 11 12 } 13 14 16 // int i; // bool indent; // i = 10; // // if (i > 30) { // printf("I like to indent.") // indent = true; // i++; // } // printf("All done now.") // // // Block 1 begins here ------ v | Block 2 begins here ---- v | | | | | | | | | Block 3 begins here -- v | | | | | Block 3 ends here ---- ^ | | | | Block 2 ends here -------^ | Block 1 ends here ---------^ Alex Cummaudo 1744070 4.3 4 PROGRAMMING CONCEPTS Functional Decomposition A problem is far more easily understandable when it is broken up into smaller tasks—this is the core of functional decomposition. Analysis of a larger problem as small, individual tasks (which may be repeated) allows for better understanding of the larger complex program since it can be seen from different viewpoints—rather than looking at a problem from the outside, look at it from the inside and assess each step after another until you gain full knowledge of how a complex task works. Figure 3: Visualising functional decomposition becomes easier with a sequence diagram. Procedures and functions allow developers to do this in programs; each procedure and function should perform one step or task A mash-up of multiple tasks in one procedure goes against the principles of functional decomposition since simplicity is key to writing good programs. The simpler the procedure or function, the greater chance you have in understanding how a complex task works. The more procedures and functions you have, the greater control and flexibility you have in calling procedures or functions when need be, rather than having to recode unnecessarily. To help with visualising functional decomposition in a program in its development stage, developers should consider writing structure charts and sequence diagrams (see Figure 3). 17 4 PROGRAMMING CONCEPTS Alex Cummaudo 1744070 In the iteration stages of a program, consistent analysis of procedures and functions should be made to see if it is possible to break them down even further—to minimise the lines of code and the paths for the program to take. 18 Alex Cummaudo 1744070 4.4 4 PROGRAMMING CONCEPTS Iteration of Arrays f\For loops are usually used with a control variable, by convention named i, set at the lowest index of the array and have its pre-test condition set to i is less than or equal to the highest index of the array. At the end of each loop, the control variable is incremented by one. Thus the for loop is run from the lowest index to the highest index; an iteration of each index has occurred. This is what makes arrays so powerful; the fact large amounts of data can be processed so easily with very little lines of code. Refer to following figure and listings as an example. Figure 4: Visualisation of how the for loop works, including the creation of the control variable and pretest loop. 19 4 PROGRAMMING CONCEPTS Alex Cummaudo 1744070 Example in Pascal procedure Main(); var theArray : array [0..10 - 1] of Integer; 1 2 3 4 5 begin for i := Low(theArray) to High(theArray) do 6 7 8 begin 9 theArray[i] := i; WriteLn(theArray[i]); 10 11 end; end; 12 13 14 begin Main(); end. 15 16 17 18 19 20 // 10 - 1 reminds me // that the array is // 0-based // For every index in // the array Alex Cummaudo 1744070 4 PROGRAMMING CONCEPTS Example in C 1 2 #include <stdio.h> #define ARRAY_SIZE (10 - 1) 3 4 // 10 - 1 reminds me // that the array is // 0-based 5 6 7 8 9 int main() { int i; int theArray[ARRAY_SIZE]; for (i = 0; i <= (ARRAY_SIZE); i++) { 10 theArray[i] = i; printf("%d", theArray[i]); 11 12 } return 0; 13 14 15 // For every index in // the array } 16 21 5 PROGRAMMING ARTEFACTS 5 Alex Cummaudo 1744070 Programming Artefacts Programs can be made from a number of different kinds of artefacts. These include the following that are described below: • Program • Procedure • Constant • Variable • Function • Array • Record • Enumeration • Pointer 22 Figure 5: Mind Map describing relationships between programming artefacts and concepts Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS 23 5 PROGRAMMING ARTEFACTS 5.1 Alex Cummaudo 1744070 Program An artefact that declares human-readable source code that can be compiled into a machine-readable executable file. A program contains: • Sets of instructions (statements) which command the computer to do things. This provides functionality. • To organise functionality, programs should contain variables (to store and manipulate data), and procedures and functions (to control task flow better). • Custom data types, allowing programmers to have better control over the data they create. Custom data types extend the vocabulary of the language so that it better suits a program’s needs. • Other artefacts, identified using an identifier. Special identifiers specifically understood by the program are keywords (like if or function.) 5.1.1 Program Execution When a program is run, all of the instructions are executed line by line. When a program is first executed, it is allocated a section of memory by the OS. Memory is required by a program so that the CPU can read instructions, process them, and know what instructions to load next. Since a CPU is much faster at processing, the RAM, rather than the storage medium, is used—therefore preventing excessive read/writes to the storage medium. This memory is used to store: 1. compiled source code (that is, the instructions to execute), 2. global variables, 3. the stack and, 4. the heap. 24 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS The stack stores frames which automatically manage function and procedure calls. However, the stack is of a fixed size—whenever a new procedure or function is called, a fixed size is allocated on the stack for that specific procedure/function. The program itself is added on top of the OS’s own stack. Any procedures executed have their stack frames added on top of the program’s stack and all variables declared within the program have memory allocated within the program’s (which has its memory allocated from the OS). Every frame in the stack has its own fixed size because computers need to know how much memory to allocate and then deallocate once the tasks within that procedure/function (the frame) are completed—i.e., the computer needs to know how far to go back in memory (deallocate memory) when the tasks in the frame are finished. While it is beneficial for a programmer not to manually manage memory allocation within the stack, it is limited in that dynamic memory ranges cannot be used. This is where the heap comes in handy. The heap is another way to organise memory, whereby memory is not ‘stacked’ on top of each other. The heap is also larger, so more information can be stored on it than the heap, since data is dynamically stored on it. However, you cannot interact directly with the heap from the stack. The stack can only interact with its current frame, and so a pointer is used to reference memory inside the heap. You allocate memory with a function (such as malloc in C or New in Pascal) and then assign the result of that allocation to a pointer variable. Using dynamic memory, we can alter the size of arrays (thus making them less static). To do this in Pascal, use the function New(pointerName) to declare pointer in the stack-frame, and then SetLength(pointerName, 4) to set the size of the array, to four. In C, this is a little different. C requires more code to do this, since it does not automatically set memory sizes in the heap for you like Pascal does. To do this: 1. pointerName = (int*)malloc(sizeof(int)*4) will allocate memory in the heap to a pointer. (a) We set the size to allocate to the sizeof an integer times four (so there’s sequential memory for four integers as an array). (b) We cast the result of malloc as an integer, since malloc returns a void type value. (c) We store all of this into a new pointer, called pointerName 25 5 PROGRAMMING ARTEFACTS Alex Cummaudo 1744070 2. pointerNameNew = realloc(p, sizeof(int)*50) We reallocate the memory we just allocated in step one, now to a size of 50. We store this into a new pointer called pointerNameNew. 3. if (pointerNameNew != NULL) pointerName = pointerNameNew We now see if our new pointer had enough space to allocate 50 integer memory spaces in a row within the heap. That is: (a) If the new pointer is not null (so, it actually points to a place in memory that had 50 integer bytes available in a row) then (b) assign the old pointer to the new pointer, so that the array is now of 50 integer bytes in size. The problem in using pointers is that, once memory is deallocated, the pointer may still be pointing to data in the original memory address; this means that, at any time, the original memory may be overridden since it is no longer allocated to a variable (but, the pointer still points to that location.) This is ultimately problematic, since a pointer that is deallocated (but is told to still reference the memory address) will lead to bugs which are difficult to spot. Thus, always deallocate memory from a pointer and tell the pointer to reference nothing. This will then lead to a program crash should there be a reference to the pointer, rather than causing unexpected, weird bugs from occurring. A procedure will have its stack frame removed from the stack once completed. Once all lines of instructions have been executed, the program quits and all memory is deallocated for further use by the program. Its stack frame is removed from the OS stack. 26 Alex Cummaudo 1744070 5.1.2 5 PROGRAMMING ARTEFACTS Example: Hello World This example program simply prints Hello World to the terminal. It is a very basic program, usually only written when a programmer learns a new language and wants to see if they have grasped the very basics of the language. Example in Pascal 1 program HelloWorld; 2 // Defines the executable name // as HelloWorld 3 4 5 6 7 8 9 10 11 procedure Main() begin WriteLn('Hello World'); end; begin // A keyword ('begin') Main(); // Run the main procedure // (i.e. a procedure call) end. 12 Example in C 1 #include <stdio.h> 2 3 4 5 int Main() { printf("Hello World!"); return 0; 6 7 8 // Includes the standard i/o // header file (for printf) // The 'main' function // Main is a function; // it returns an int value // (for the OS) } 9 27 5 PROGRAMMING ARTEFACTS 5.2 Alex Cummaudo 1744070 Procedure An artefact made up of a sequence of instructions within a program that performs a task. Procedures are similar to functions. A procedure usually contains: • Instructions • Parameters and local variables 5.2.1 Procedure Execution The computer first passes arguments (a form of an expression) from the procedure call into the procedure’s parameters. These parameters become local variables within the procedure—they are only accessible within the procedure when being executed (i.e. when its stack-frame is on the top of the stack). Variables declared within procedures are also local variables. Unlike global variables, which can be accessed anywhere throughout the program, local variables make controlling variables and debugging easier, since the variable can only be changed within that procedure. Parameters are special types of variables whose values are passed onto the procedure from the procedure call. This allows for the procedure to accept input from other parts of the program, giving us greater control of how the program runs. 5.2.2 Example: DrawHouse This procedure uses the SwinGame library to draw certain shapes within the game canvas that will look like a house. Note this only draws the house onto the canvas; the program would call this procedure and then call another procedure RefreshScreen to draw the canvas onto the game window. Example in Pascal procedure DrawHouse(); begin // Main building FillRectangle(ColorGrey, 300, 300, 200, 200); 1 2 3 4 28 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS 5 // The roof FillTriangle(ColorRed, 250, 300, 400, 150, 550, 300); 6 7 8 // The window FillEllipse(ColorBlue, 325, 325, 50, 100); 9 10 11 // The door FillRectangle(ColorBlack, 400, 320, 75, 180); end; 12 13 14 15 Example in C 1 void draw_house() { 2 // Void indicates that this function // returns nothing (it's a procedure!) // Main building fill_rectangle(ColorGrey, 300, 300, 200, 200); 3 4 5 // The roof fill_triangle(ColorRed, 250, 300, 400, 150, 550, 300); 6 7 8 // The window fill_ellipse(ColorBlue, 325, 325, 50, 100); 9 10 11 // The door fill_rectangle(ColorBlack, 400, 320, 75, 180); 12 13 14 15 } 16 29 5 PROGRAMMING ARTEFACTS 5.3 Alex Cummaudo 1744070 Function An artefact designed to return results, usually from parameter input. Functions are similar to procedures, and the only difference is that functions calculate values, whereas procedures execute tasks. Functions usually contain: • Variables • Parameters 5.3.1 Function Execution The function call (used as an expression) passes its parameters onto the function. The function then calculates the values based on the parameters and returns the result of the calculation back to where the function call’s expression was. 5.3.2 Example: A Basic Adder This function simply receives input from its parameters (integers) and returns the result (also an integer) of adding the two parameters together. Example in Pascal function Adder(x, y: Integer): Integer; begin result := x + y; end; 1 2 3 4 5 Example in C int adder(int x, int y) { return x + y; } 1 2 3 4 30 Alex Cummaudo 1744070 5.4 5 PROGRAMMING ARTEFACTS Constant An artefact that stores a value which is never changed. It is usually used to give meaning to a specific value. Constant identifiers are usually written in uppercase to differentiate them from variables. Although similar to variables, the main difference is that variables can have their values changed while a constant’s value is never changed. 5.4.1 Example: Constantly Craving PI Rather than hard-code the value of 3.14 in expressions that reference pi, declare a constant, PI with the value 3.14. This would allow the value to be differentiated from other regular single/double values of 3.14. The following program calculates the area of a circle using the pi constant and how it could be used. Example in Pascal 1 2 3 4 5 const PI = 3.14; function WorkOutArea(radius: Integer):Integer; begin result := 2 * PI * radius; end; 6 Example in C 1 2 3 4 const PI = 3.14; int work_out_area(int radius) { return 2 * PI * radius; } 5 31 5 PROGRAMMING ARTEFACTS 5.5 Alex Cummaudo 1744070 Variable An artefact of a specific type that stores a value that can be modified. Variables give programs greater dynamics by changing the way the program works (usually by user input directed into variables). Variables are assigned a type (also an artefact) so that the computer can identify how to read them. Three kinds of variables exist: • Global variables: variables declared outside a procedure or function. • Local variables: variables in a procedure or function. • Parameters: variables passed to procedures and functions. 5.5.1 Local Variable Creation When a local variable is created, the computer allocates space in memory on the procedure’s stack frame for the variable to be used. 5.5.2 Parameter Creation For a procedure call using pass by value, the values in the procedure call are copied into the procedure for use. When these values change in the procedure, they will not affect the original source variables that were used in the parameters on the procedure call. When using pass by reference, parameters get a pointer to the variable passed to them; this means that the parameters changed in the procedure will also affect the source variables used in the procedure call’s parameters. Figure 6 helps to illustrate this, whereby var1 and var2 are copied into the parameters the first example whereas the parameters in the second example are consistently referencing the original variables declared in Main. 32 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS Figure 6: Copying variables into a parameter as per pass by value versus pointers to variables in pass by reference. 33 5 PROGRAMMING ARTEFACTS 5.5.3 Alex Cummaudo 1744070 Example: myAge in xYears The following variable example asks for the user’s age by storing the results of the read/scanf function into a variable called myAge/my age. The program will then tell them how old they will be based on the user’s input once again. By adding the two together in a function called Adder (see functions), the user can see how old they will be in xYears/x years. All uses of variables are local variables in this case. Example in Pascal procedure Main(); var myAge, xYears: Integer; begin Write('What is your age? '); read(myAge); 1 2 3 4 5 6 7 // Declare the local variables // Result of the read // stored in myAge Write('Type in amount of years: '); read(xYears); WriteLn('In ', xYears,' years you''l be ',Adder(myAge, xYears)); end; 8 9 10 11 12 Example in C int main() { // Declare the local variables int myAge; int xYears; 1 2 3 4 5 printf("What is your age? "); scanf("%d", &myAge); 6 7 8 printf("Type in amount of years: "); scanf("%d", &xYears); 9 10 34 // Result of the scanf // stored in my_age Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS 11 printf("In %d years you'll be %d \n", xYears, adder(myAge, xYears)); 12 13 } 14 35 5 PROGRAMMING ARTEFACTS 5.6 Alex Cummaudo 1744070 Array An artefact (more specifically, a form of a variable) that is used to store multiple pieces of data under the one identifier. Each value stored within the array has its own position, known as its index number; referencing a value stored within an array is done by referencing that value’s index number. An array can only be of one type since it is still a variable. In technical terms, this is because each type has its only byte length; arrays work by offsetting from the start of the array (an offset of 0) by that byte length—this is how the computer knows which index is which (as an offset of x bytes—where x is dependent on type—from 0.) Figure 7: Illustration of Subjects array created in the example below Picture an array like a row of boxes that are stuck together (see above). To define the array, you need to know how many boxes to put together (defining the length of the array), and then label the whole row of boxes with a type (let’s say Integer). If I try to put a string within the array I have created, labelled Integer, then my compiler will tell me off since I’m putting the wrong type of data within that box—that array can only store integers! When you create an array: 1. Define the length of the array. 2. Define what type of data it stores. 36 Alex Cummaudo 1744070 5.6.1 5 PROGRAMMING ARTEFACTS Example: My Five subjects This array stores each one of my subject names for this semester. It will store the string / char type and will store 5 values. Example in Pascal 1 var 2 subjects : array [0..5 - 1] of String; // 5 - 1 = that 0-based! begin subjects[0] := 'Algorithmic Problem Solving'; subjects[1] := 'Database Analysis and Design'; subjects[2] := 'Introduction to Business Information Systems'; subjects[3] := 'ICT Environments'; subjects[4] := 'Accounting for Managers'; end; 3 4 5 6 7 8 9 10 Example in C 1 2 3 4 5 6 char *subjects[5-1]; // 5 - 1 = 0-based; pointer to char array. subjects[0] = "Algorithmic Problem Solving"; subjects[1] = "Database Analysis and Design"; subjects[2] = "Introduction to Business Information Systems"; subjects[3] = "ICT Environments"; subjects[4] = "Accounting for Managers"; 7 37 5 PROGRAMMING ARTEFACTS 5.7 Alex Cummaudo 1744070 Record / Structure An artefact which allows for the creation of a custom, composite data type (i.e. a data type made up of many other other data types). Record/Structure allow for all relevant pieces of data of a specific entity to come together (separated with fields). You can reference one field with dot notation (entity.field) or the whole entity with all fields. Records contain fields, each with their own data type, which all come together to form the whole record. You reference a field with a period: entity.field. 5.7.1 Example: Products in a Supermarket This example of a record/structure shows how an entity (such as a product) can be defined as a custom data type with multiple fields (such as name, id numb, location etc.) The example also highlights that a record/structure can also be used within yet another record/structure (Supermarket) which can then be made up of further types (such as enumerations). The following illustration visualises the record/structure of Product in this example. Figure 8: Visualisation of Product 38 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS This page is intetionally blank. 39 5 PROGRAMMING ARTEFACTS Example in Pascal type SupermarketKind = (Coles, Woolworths, Aldi); Supermarket = record owner = SupermarketKind; address = String; end; Product = record idNumber : Integer; name : String; location : Supermarket; end; var bananas : Product; begin bananas.idNumber := 47; bananas.name := 'Golden Fruity Bananas!'; bananas.location.owner = Coles; bananas.location.address = '123 Fake Street'; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 40 Alex Cummaudo 1744070 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS Example in C 1 #import <stdio.h> 2 3 4 5 6 7 typedef enum supermarket_kind { COLES, WOOLWORTHS, ALDI } supermarket_kind; 8 9 10 11 12 typedef struct supermarket { supermarket_kind owner; char address[255]; } supermarket; 13 14 15 16 17 18 19 typedef struct product { int id_number; char name[255]; supermarket location; } product; 20 21 22 23 24 25 26 27 28 int main() { product bananas; bananas.id_number = 47; sprintf(bananas.name, "Golden Fruity Bananas!"); bananas.location.owner = COLES; sprintf(bananas.location.address, "123 Fake Street"); return 0; } 29 41 5 PROGRAMMING ARTEFACTS 5.8 Alex Cummaudo 1744070 Enumeration An artefact which allows for a list of options related to a custom data type. When used, an enumeration kind of data type can only be one of the list of options. Use when there are mutually exclusive options. 5.8.1 Example: Seasons use MonthData The enumeration in this defines a custom data type using enumeration for months in the year. It is then used to work out the season. Since enumerations store data sequentially, the Pascal code’s case statement can check if input is between any month. C cannot do ranges within it’s switch statement, however. Example in Pascal type MonthData = (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec); var theMonth : MonthData; begin theMonth = May; case theMonth of Jan..Feb: WriteLn('It''s summer! Go to the beach!'); Mar..May: WriteLn('It''s autumn! Go rake some leaves!'); Jun..Aug: WriteLn('It''s winter! Stay inside and program!'); Sep..Nov: WriteLn('It''s spring! Go out and smell the roses!'); Dec: WriteLn('It''s summer! Go to the beach!'); end. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 42 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS Example in C 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #include <stdio.h> typedef enum month_data { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } month_data; int main() { month_data theMonth; theMonth = MAY; switch (theMonth) { case JAN: printf("It's summer! Go to the beach!\n"); break; case FEB: printf("It's summer! Go to the beach!\n"); break; case MAR: printf("It's autumn! Go rake some leaves!\n"); break; case APR: printf("Its autumn! Go rake some leaves!\n"); break; case MAY: printf("It's autumn! Go rake some leaves!\n"); break; case JUN: printf("It's winter! Stay inside and program!\n"); break; case JUL: printf("It's winter! Stay inside and program!\n"); break; case AUG: 43 5 PROGRAMMING ARTEFACTS printf("It's break; case SEP: printf("It's break; case OCT: printf("It's break; case NOV: printf("It's break; case DEC: printf("It's break; default: break; 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 } return 0; 48 49 } 50 51 44 Alex Cummaudo 1744070 winter! Stay inside and program!\n"); spring! Go out and smell the roses!\n"); spring! Go out and smell the roses!\n"); spring! Go out and smell the roses!\n"); summer! Go to the beach!\n"); Alex Cummaudo 1744070 5.9 5 PROGRAMMING ARTEFACTS Pointer An artefact which refers to a point in memory. This kind of type allows you to indirectly access and manipulate variables by another variable which points to the source variable. The value stored by a pointer type is the memory address—similar to an index in that an address is the index of an array of bits (data). They are most useful to make relationships between values (that are of the same type). To use a pointer, use the address operator (@ in Pascal, * in C) to get a pointer to an existing value (i.e. to the address of the pointer.) Use the dereference operator (^ in Pascal, & in C) to follow a pointer to its value. To dereference a field of a custom data type in C, use the -> operator. Figure 9: Example of a pointer from Lab 6 Work - Contacts Think of a pointer as a variable which points to an address in memory—the pointer variable only stores an address so when you look at a pointer variable you actually want to look at what its pointing to. 45 5 PROGRAMMING ARTEFACTS 5.9.1 Alex Cummaudo 1744070 Pointer Creation and Assignment When a pointer is first created, the programmer doesn’t assign it to an memory address. This doesn’t mean it isn’t pointing to nothing—it points to random memory (see figure). Once a pointer is then assigned an address, it then will store the address of the memory it points to. This could be another variable; hence changing pointer’s referenced value also indirectly changes the original variable. Changing the address of that pointer variable changes what it is referencing, so then it will point elsewhere. Figure 10: A very weird friend name in the Friends exercise from lab work in week 6; caused by printing the friend name without assigning the friend pointer to a contact beforehand. This is what the pointer is currently referencing when non-initialized. 46 Alex Cummaudo 1744070 5.9.2 5 PROGRAMMING ARTEFACTS Example: Cheese and what it goesNiceWith This example shows how entities can be related using pointers. There are three product variables, cheese (named Camembert), crackers (named Savoys) and wine (named Merlot). The program starts by assigning the attribute of Product.goesNiceWith for cheese; at first it points to wine. It writes the line (referencing wine.name indirectly via the cheese.goesNiceWith pointer). It then redoes this by reassigning the same pointer to crackers and writes the same line (but this time with a different address to point to - crackers) Figure 11: Terminal Output of Cheese Program Example in Pascal 1 2 3 4 5 6 7 8 9 10 11 12 13 type ProductPtr = ^Product; Product = record name : String; goesNiceWith : ProductPtr; end; var cheese : Product; crackers : Product; wine : Product; begin cheese.name := 'Camembert'; crackers.name := 'Savoy'; 47 5 PROGRAMMING ARTEFACTS Alex Cummaudo 1744070 wine.name := 'Merlot'; 14 15 cheese.goesNiceWith := @wine; WriteLn(cheese.name,' is nice with ', cheese.goesNiceWith^.name); 16 17 18 cheese.goesNiceWith := @crackers; WriteLn(cheese.name,' is nice with ', cheese.goesNiceWith^.name); end. 19 20 21 22 Example in C #import <stdio.h> typedef struct product { char name[255]; struct product *goes_nice_with; } product; int main() { product cheese; product crackers; product wine; 1 2 3 4 5 6 7 8 9 10 11 sprintf(cheese.name, "Camembert"); sprintf(crackers.name, "Savoy"); sprintf(wine.name, "Merlot"); 12 13 14 15 cheese.goes_nice_with = &wine; printf( "%s is nice with %s \n", cheese.name, cheese.goes_nice_with->name ); pointer 16 17 18 19 // -> means follow the // and retrieve it's name! 20 48 Alex Cummaudo 1744070 5 PROGRAMMING ARTEFACTS 21 cheese.goes_nice_with = &crackers; printf( "%s is nice with %s \n", cheese.name, cheese.goes_nice_with->name ); 22 23 24 25 26 return 0; 27 28 } 29 49 6 PROGRAMMING STATEMENTS 6 Alex Cummaudo 1744070 Programming Statements Statements are commands that get the computer to perform actions when the code is executed. Each command performs a number of simple steps. The commands listed below are described in the following sections: • Procedure and Function Call • Assignment Statement • If Statement • Case Statement • While Loop • Repeat Loop • For Loop 50 Alex Cummaudo 1744070 6.1 6 PROGRAMMING STATEMENTS Procedure Call An action placed elsewhere in the code and will run a separate procedure when called. Allows for less code to be written if a certain procedure needs to be run multiple times. Use parameters in procedure calls to pass values (arguments) to local variables within the called procedure when called. 6.1.1 Actions Performed When a procedure call is executed the computer performs the following steps: 1. Adds the procedure’s stack frame to the stack 2. Passes any parameters into the the procedure’s local variables (if any) 3. Executes the procedure’s code line by line 4. Once the end of the procedure is reached, the procedure’s stack frame is removed from the stack 51 6 PROGRAMMING STATEMENTS 6.1.2 Examples 6.1.3 Example 1: Calling a delay Alex Cummaudo 1744070 This example calls the delay procedure within SwinGame, with a parameter set to 15000ms or 15s. The program essentially just hangs for 15 seconds doing nothing before ending. Example in Pascal program JustWait; uses SwinGame; begin delay(15000); 1 2 3 4 5 // Call the delay procedure, with a parameter set // to 15000ms = 15s end. 6 7 Example in C #includes 'swingame.h' int main() { sleep(15000); return 0; } 1 2 3 4 5 6 52 Alex Cummaudo 1744070 6.1.4 6 PROGRAMMING STATEMENTS Example 2: Calling a Read/scanf This program prints a new line with a user inputted string. Example in Pascal 1 2 3 4 program WriteString; var userString: String; begin Write('What should I echo? '); 5 Read(userString); 6 7 WriteLn(userString); 8 9 10 // // // // // // Procedure call parameter is the string Procedure call parameter is userString Writes new line based on userString end. 11 Example in C 1 #include <stdio.h> 2 3 4 5 6 int main() { char user_string[255]; printf("I will echo: "); // // scanf("%s", user_string); // // printf("%s \n", user_string); // // return 0; 7 8 9 10 11 12 13 Procedure call parameter is the string Procedure call parameter is user_string Writes new line based on user_string } 14 53 6 PROGRAMMING STATEMENTS 6.1.5 Alex Cummaudo 1744070 Example 3: Tick This program prints a new line to the terminal every x seconds times. Example in Pascal program Tick; uses SwinGame; procedure tick(xSeconds: Integer); 1 2 3 4 begin Delay(xSeconds * 1000); 5 6 // wait x amount of seconds // (* 1000 for s) // Write a line, 'tick' 7 WriteLn('Tick'); end; 8 9 // Define a new procedure // with xSeconds parameter 10 begin //now call tick tick(1); tick(3); tick(5+5); end. 11 12 13 14 15 16 // Pass 1s expression to the procedure // Pass 3s expression to the procedure // Pass 5+5s expression to the procedure 17 Example in C #include <stdio.h> #include <time.h> 1 2 3 void tick(int x_seconds) { 4 5 sleep(x_seconds); printf("tick \n"); 6 7 } 8 9 54 // // // // Define a new procedure with x_seconds parameter wait x amount of seconds Write a line, 'tick' Alex Cummaudo 1744070 10 11 12 13 14 15 16 17 int main() { // now call tick tick(1); tick(3); tick(5+5); return 0; } 6 PROGRAMMING STATEMENTS // Pass 1s expression to the procedure // Pass 3s expression to the procedure // Pass 5+5s expression to the procedure 18 55 6 PROGRAMMING STATEMENTS 6.2 Alex Cummaudo 1744070 Function Call An action similar to a procedure call which calculates and returns the result of the parameters based on the calculations of the function called. Function calls are actually expressions, since the result of the function that was called replaces the function call as a part of the expression it was called in. Parameters allow you to pass variables to the function, and the value returned becomes part of the expression where the function call was placed. 6.2.1 Actions Performed When a function call is executed the computer performs the following steps: 1. Parameters are passed onto the function’s variables 2. The function makes calculations based on its input parameters 3. The function returns the result to the function call’s location (the result now becomes part of an expression) 56 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS 6.2.2 Examples 6.2.3 Example 1: Assignment Statement with Function Call The value returned from this function call is stored in the variable. Example in Pascal 1 2 3 4 5 6 7 8 9 10 11 12 function Adder(myAge, xYears: Integer): Integer; begin result := myAge + xYears; end; procedure Main() var ageInTenYrs : Integer; begin ageInTenYrs := Adder(18,10); // Function calls result // is expression assigned // to the ageInTenYrs variable end; 13 Example in C 1 2 3 4 5 6 int adder(int myAge, int xYears) { return myAge + xYears; } int main() { int age_in_ten_yrs; age_in_ten_years = adder(18,10); 7 8 return 0; 9 10 // Function calls result // is expression assigned // to the age_in_ten_yrs variable } 11 57 6 PROGRAMMING STATEMENTS 6.2.4 Alex Cummaudo 1744070 Example 2: Function Call to get parameter value This example shows a function call calculating a value that is passed to parameter. Note, the adder function called was defined in example one. Example in Pascal procedure Main() begin WriteLn(Adder(18,10)); 1 2 3 4 5 // The function's result is // directly passed on as an // expression to WriteLn's parameter. end; 6 7 Example in C int main() { printf("%d", adder(18,10)); 1 2 3 4 5 return 0; 6 } 7 8 58 // // // // The function's result is directly passed on as an expression to printf parameter 2. Alex Cummaudo 1744070 6.2.5 6 PROGRAMMING STATEMENTS Example 3: Function Call in a condition This example shows a function call calculating a value that is used in a condition in an if statement. Note, the adder function called was defined in example one. Example in Pascal 1 2 3 procedure Main() begin if (Adder(18,50) > 50) then 4 5 6 The function's result is directly passed on as an expression to the if statement's condition // // // // The function's result is directly passed on as an expression to the if statement's condition WriteLn('You''d have grey hair!'); 7 8 // // // // end; 9 Example in C 1 2 int main() { if (adder(18,10) > 50) 3 4 5 printf("You'd have grey hair!"); return 0; 6 7 8 } 9 59 6 PROGRAMMING STATEMENTS 6.3 Alex Cummaudo 1744070 Assignment Statement Assigns a value to a variable • On the left side of the assignment you put a variable • On the right side of the assignment you put an expression 6.3.1 Actions Performed When an assignment statement is executed the computer performs the following steps: 1. Calculates the right hand side expression 2. Stores the result of the calculated expression from ( 1 ) into the variable. 60 Alex Cummaudo 1744070 6.3.2 Examples 6.3.3 Example 1: Assign This 6 PROGRAMMING STATEMENTS This assignment statement simply assigns an expression to a variable. Example in Pascal 1 2 3 4 5 6 7 procedure Main(); var varName: Integer; begin varName := 30 + 20 * 2.5; // Assigns the expression to varName // Results in varName = 80 end; 8 9 Example in C 1 2 3 int main() { int var_name; var_name = 30 + 20 * 2.5; 4 return 0; 5 6 // Assigns the expression to var_name // Results in var_name = 80 } 7 61 6 PROGRAMMING STATEMENTS 6.3.4 Example 2: Add This This assignment statement simply adds one to the variable. Example in Pascal procedure Main(); var varName: Integer; begin varName := 10; varName += 1; 1 2 3 4 5 6 7 // Assigns 10 to varName // Adds 10 to varName // Results in varName = 11 end; 8 9 10 Example in C int main() { int var_name; var_name = 10; var_name += 1; 1 2 3 4 5 return 0; 6 } 7 8 9 62 // Assigns 10 to var_name // Adds 10 to var_name // Results in var_name = 11 Alex Cummaudo 1744070 Alex Cummaudo 1744070 6.3.5 6 PROGRAMMING STATEMENTS Example 3: Divide This This assignment statement simply divides the variable by 5. Example in Pascal 1 2 3 4 5 6 7 8 procedure Main(); var varName: Integer; begin varName := 125 // Assigns 125 to varName varName /= 5; // Divides varName by 5 // Results in 25 end; 9 Example in C 1 2 3 4 int main() { int var_name; var_name = 125 var_name /= 5; 5 6 // Assigns 125 to var_name // Divides var_name by 5 // Results in 25 } 7 63 6 PROGRAMMING STATEMENTS 6.4 Alex Cummaudo 1744070 If Statement A statement that acts as a decision point in the code. Only two branches can follow based upon a boolean expression (either true or false) whose condition is decided upon at the beginning of the if statement. 6.4.1 Actions Performed When an if statement is executed the computer performs the following steps: 1. Evaluate the boolean expression for true / false 2. If true, execute the true branch 3. If false, execute the false branch 4. Continue on with next block at the endpoint of the statement 64 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS This page is intetionally blank. 65 6 PROGRAMMING STATEMENTS 6.4.2 Examples 6.4.3 Example 1: If One is One Alex Cummaudo 1744070 This example will always result in only one path being chosen; the boolean expression being tested here will simply test if the number one is equal to the number one. Since this is impossible to be false (how could one equal three!? ) only the true branch of the if statement is executed. The else part of this statement (i.e. the false branch) will never be executed since the boolean expression condition will always result in true. Figure 12: Flowchart with a true and false clause 66 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 3 4 if 1 = 1 then WriteLn('Of course one is equal to one!') else WriteLn('You should never be able to see this line!'); 5 Example in C 1 2 3 4 if (1 == 1) printf("Of course one is equal to one!") else printf("You should never be able to see this line!"); 5 67 6 PROGRAMMING STATEMENTS 6.4.4 Alex Cummaudo 1744070 Example 2: Name Game This example prompts the user for their name. If their name happens to be Fred or Alex, the program will write to the terminal that Fred/Alex is an awesome name!. Otherwise, if their name happens to be Andrew, the program writes to the terminal I hope you like my glossary. Otherwise, the computer will output, Go away!. Figure 13: Flowchart with multiple and embedded true and false clauses 68 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 3 4 5 6 7 8 9 10 11 12 procedure Main(); var name : String; begin Write('What is your name? '); Read(name); if (name = 'Fred') or (name = 'Alex') then WriteLn(name, ' is an awesome name!') else if name = 'Andrew' then WriteLn('I hope you like my glossary') else WriteLn('Go away!'); end; 13 Example in C 1 2 #include <stdio.h> #include <string.h> // Required for strcmp 3 4 5 6 7 8 int main() { char name[25]; printf("What is your name?\n"); scanf("%s", name); 9 10 11 12 13 // // // // strcmp = string compare It compares the char array (name) with the string provided in the second parameter. If == 0 then there is an exact match. 14 15 16 if ( (strcmp(name, "Alex") == 0) || (strcmp(name, "Fred") == 0) ) printf("%s is an awesome name!\n", name); 69 6 PROGRAMMING STATEMENTS else if ( (strcmp(name, "Andrew") == 0 ) ) printf("I hope you like my glossary\n"); else printf("Go away!\n"); return 0; 17 18 19 20 21 } 22 23 70 Alex Cummaudo 1744070 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS This page is intetionally blank. 71 6 PROGRAMMING STATEMENTS 6.4.5 Alex Cummaudo 1744070 Example 3: Number Guess Checker This example will check a person’s guess against a randomly generated number. It is a snippet of the original code that I wrote (i.e. it is only the checker procedure). If the guess is exact, the player wins, otherwise if it’s too high, it will inform the player that they’re too high and likewise for if their guess is too low. Figure 14: Flowchart with multiple and embedded true and false clauses 72 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 3 4 5 6 7 8 9 procedure CheckGuess(guessNumb, randNumb: Integer); begin if (guessNumb = randNumb) then WriteLn('Wow, you got it! It''s ', randNumb) else if (guessNumb > randNumb) then WriteLn('Too high!') else if (guessNumb < randNumb) then WriteLn('Too low!'); end; 10 Example in C 1 2 3 4 5 6 7 8 void check_guess(int guess_numb, int rand_numb){ if ( guess_numb == rand_numb ) printf("Wow, you got it! It's %d\n", rand_numb); else if ( guess_numb > rand_numb ) printf("Too high!\n"); else if ( guess_numb < rand_numb ) printf("Too low!\n"); } 9 73 6 PROGRAMMING STATEMENTS 6.5 Alex Cummaudo 1744070 Case Statement A statement that selects a branch that matches a value in the condition’s expression. Unlike an if statement (where only two branches may be used) a case statement can have multiple branches. It reads the condition expression and the branch with a matching condition expression is executed. If no matches are found, it is possible to include an else/default expression as a matching value; it will run when no other matches are found. Case statements are weaker than if statements in that integers (and char type in Pascal) values can only be assessed. 6.5.1 Actions Performed When a case statement is executed the computer performs the following steps: 1. Evaluate the expression against all cases 2. Find a match, if any, and execute its branch, otherwise run the else branch (if an else branch exists) 3. Continue on with next block at the endpoint of the statement 74 Alex Cummaudo 1744070 6.5.2 Examples 6.5.3 Example 1: Yes or No 6 PROGRAMMING STATEMENTS This case statement is quite simple; if the match is either Y or N then the appropriate message is selected. If neither has been inputted by the program, the program will indicate so. Figure 15: Flowchart with two possible cases for a case statement Example in Pascal 1 2 3 4 5 6 7 8 procedure Main(); var selection : char; begin ReadLn(selection); case selection of 'Y', 'y': WriteLn('Yes!'); 'N', 'n': WriteLn('No!'); 75 6 PROGRAMMING STATEMENTS else WriteLn('I don''t understand!'); end; end; 9 10 11 12 Example in C #include <stdio.h> 1 2 // need to convert character to int since // c does not support switch cases with // chars 3 4 5 6 int main() { int selection; // selection is a number char input; // input is the char inputted 7 8 9 10 scanf("%c", &input); 11 12 if ( (input == 'y') || (input == 'Y') ) selection = 1; else if ( (input == 'n') || (input == 'N') ) selection = 0; 13 14 15 16 17 switch (selection) { case 1: printf("Yes!\n"); break; case 0: printf("No!\n"); break; default: printf("I don't understand!\n"); 18 19 20 21 22 23 24 25 26 76 Alex Cummaudo 1744070 Alex Cummaudo 1744070 break; 27 } 28 29 6 PROGRAMMING STATEMENTS } 30 77 6 PROGRAMMING STATEMENTS 6.5.4 Alex Cummaudo 1744070 Example 2: Seventies, Eighties or Nineties? This procedure simply asks for input of a year between 1970 and 1999. It will then categorise the input. Figure 16: Flowchart with multiple case statements Example in Pascal var 1 year : Integer; begin ReadLn(year); case year of 1970..1979: WriteLn('It's 1980..1989: WriteLn('It's !!'); 1990..1999: WriteLn('It's else WriteLn('You must be end; end; 2 3 4 5 6 7 8 9 10 11 12 78 the 1970s! Get on an Apple II!!'); the 1980s! Get on an Macintosh 128K the 1990s! Get on an iMac!!'); on an IBM-PC.'); Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in C 1 #include <stdio.h> 2 3 4 5 // This is slightly harder with a switch statement in C because // case labels cannot be non-constant (i.e. cannot be ranges) // Better to use an if statement if you wanted to check a range. 6 7 8 int main() { int year; // Selection is a year 9 10 scanf("%d", &year); 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 switch (year) { case 1970: case 1971: case 1972: case 1973: case 1974: case 1975: case 1976: case 1977: case 1978: case 1979: printf("It's the 1970s! Get on an Apple II!!\n"); break; case 1980: case 1981: case 1982: case 1983: case 1984: case 1985: case 1986: 79 6 PROGRAMMING STATEMENTS Alex Cummaudo 1744070 case 1987: case 1988: case 1989: printf("It's the 1980s! Get on an Macintosh 128K!!\n"); break; case 1990: case 1991: case 1992: case 1993: case 1994: case 1995: case 1996: case 1997: case 1998: case 1999: printf("It's the 1980s! Get on an iMac!!\n"); break; default: printf("You must be on an IBM-PC.\n"); break; 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 } 52 } 53 54 80 Alex Cummaudo 1744070 6.6 6 PROGRAMMING STATEMENTS While Loop A pre-test loop, meaning that a condition is checked first before the loop will begin. Once the condition becomes false, the loop will be broken. As such, code will be repeated zero or more times (since if the condition is false to begin with, the code simply won’t execute). 6.6.1 Actions Performed When a while loop is executed the computer performs the following steps: 1. Evaluate conditional expression. Go to step 2 if true, step 4 if false. 2. Execute block if condition is true 3. Reevaluate conditional expression. Go to step 2 if true, step 4 if false. 4. Continue on with next block at the endpoint of the statement 81 6 PROGRAMMING STATEMENTS 6.6.2 Examples 6.6.3 Example 1: The Pre Test Alex Cummaudo 1744070 This example illustrates the pre-test condition example; since the pre-test condition tests for one is equal to two, the loop will not run at all (as one is equal to two is impossible to be true—one is only equal to one! ). Figure 17: Flowchart with a false while loop. Example in Pascal while (1 = 2) do WriteLn('You won''t see this!'); 1 2 3 Example in C while (1 == 2) printf("You won't see this!\n"); 1 2 3 82 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS This page is intetionally blank. 83 6 PROGRAMMING STATEMENTS 6.6.4 Alex Cummaudo 1744070 Example 2: Count to Ten This program adds one to an iteration variable on every loop. It prints the iteration variable to the terminal on every loop. The loop runs on the condition where the iteration variable is less than or equal to 10. Hence, it counts values upward from 1 to 10 to the terminal and quits once the iteration variable is no longer less than or equal to 10. Figure 18: Flowchart with an increasing iteration conditional while loop. 84 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 var 2 i : Integer; begin i := 1; while (i <= 10) do begin WriteLn(i); i += 1; end; end; 3 4 5 6 7 8 9 10 11 Example in C 1 2 3 4 5 6 int i; i = 1; while (i <= 10) { printf("%d \n",i); i++; } 7 85 6 PROGRAMMING STATEMENTS 6.6.5 Alex Cummaudo 1744070 Example 3: Infinite While Loop This program is an infinite while loop. Simply put, the program will never leave the loop (since the condition is always true, and the while loop requires a condition to be false to end the loop) and thus the program never finishes unless manually terminated by the user. This is an example of an annoying bug that can result by poor use of loops. Figure 19: Flowchart with an infinite while loop. 86 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 while (true) do //always true so always execute! WriteLn('Infinite Loop!'); 3 Example in C 1 2 while (1) printf("Infinite loop!\n"); // 1 means true explicitly 3 87 6 PROGRAMMING STATEMENTS 6.7 Alex Cummaudo 1744070 Repeat Loop A post-test loop, meaning that a condition is checked after before the loop has run. Once the condition is true! in Pascal or false! in C, the loop will break. As such, code will be repeated at least once (since the conditional test is tested after the loop has executed). 6.7.1 Actions Performed When a repeat loop is executed the computer performs the following steps: 1. Execute block statement 2. Evaluate conditional expression. Go to step 1 if false, step 3 if false. 3. Continue on with next block at the endpoint of the statement 88 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS This page is intetionally blank. 89 6 PROGRAMMING STATEMENTS 6.7.2 Examples 6.7.3 Example 1: The Post-Test Alex Cummaudo 1744070 This example illustrates the post-test condition example; since the post-test condition tests for one is equal to one, the loop will run only once but no more than one time (as one is equal to one will always be true, and so the condition for true will occur at the loops first repetition). Figure 20: Flowchart with a one loop repeat loop. 90 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 3 4 5 6 begin repeat WriteLn('You will only see this loop repeat once!'); until (1 = 1); // Since 1 = 1, true is found and the // condidtion to quit the loop is met end; 7 Example in C 1 do { 2 printf("You will only see this loop repeat once!\n"); } while (! (1 == 1)); // Since 1 = 1 (and the // ! operator negates this) // the loop will stop after post// test is performed 3 4 5 6 7 91 6 PROGRAMMING STATEMENTS 6.7.4 Alex Cummaudo 1744070 Example 2: Count to Ten This program adds one to an iteration variable on every loop. It prints the iteration variable to the terminal on every loop. The loop runs at least once, since it’s a repeat loop, and runs on the condition until the iteration variable is greater than 10. Hence, it counts values upward from 1 to 10 to the terminal. Figure 21: Flowchart with an increasing iteration conditional repeat loop. 92 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 3 4 5 6 7 8 var i : Integer; begin i := 1; repeat WriteLn(i); i += 1; until (i > 10); end; 9 Example in C 1 2 3 4 5 6 int i; i = 0; do { printf("%d \n", i); i++; } while ( ! (i > 10) ); // While not > 10 7 93 6 PROGRAMMING STATEMENTS 6.7.5 Alex Cummaudo 1744070 Example 3: Infinite Repeat Loop This program is an infinite repeat loop. Simply put, the program will never leave the loop (since the condition is always false, and the repeat loop requires a condition to be true to end the loop) and thus the program never finishes unless manually terminated by the user. This is an example of an annoying bug that can result by poor use of loops. Figure 22: Flowchart illustrating an infinite repeat loop. 94 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 3 repeat WriteLn('Infinite Loop!'); until (false); 4 Example in C 1 2 3 do { printf("Infinite loop!\n"); } while (1); // 1 means true explicitly 4 95 6 PROGRAMMING STATEMENTS 6.8 Alex Cummaudo 1744070 For Loop Action and a pre-test loop, best used to iterate/process data (such as an array). The for loop is unique in that it initialises the control variable (conventionally i) at the beginning of the for loop, will automatically increment/decrement it, and will then test to see if that control variable meets a condition. When the condition is true, the block will execute, and once this has finished, the control variable will increment one. The pre-test condition is checked once more and will either repeat the block or continue onto the next block (if the condition is false). 6.8.1 Actions Performed When a for loop is executed the computer performs the following steps: 1. Set control variable (conventionally i) to a value in order to initialise the control variable. 2. Run the pretest loop condition. If true, go to step three, otherwise go to step five. 3. Run the block within the for loop. Once completed, increment the control variable by one. 4. Run the pretest loop condition again. If true, go to step three, otherwise go to step five. 5. Continue on with next block at the endpoint of the statement 96 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS This page is intetionally blank. 97 6 PROGRAMMING STATEMENTS 6.8.2 Examples 6.8.3 Example 1: Print Subjects Alex Cummaudo 1744070 This example illustrates how arrays can be used with a for loop; the for loop will iterate through every element of the array (i.e. from the lowest element of the array to the highest element of the array) and print the value stored at that index to the terminal. The array used is that defined in the subjects example. Figure 23: Flowchart illustrating the for loop iterating through the array. 98 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 for i := Low(subjects) to High(subjects) do WriteLn(subjects[i]); 3 Example in C 1 2 int i; for (i = 0; i < size; i++) 3 4 // By C convention, pass the size // of the array in when testing. printf("%s\n", subjects[i]); 5 99 6 PROGRAMMING STATEMENTS 6.8.4 Alex Cummaudo 1744070 Example 2: Count Down This for loop illustrates how easy it is to iterate through values via for loops. No initialisation or decrementing of control variables are required with for loops since it is predefined in the definition of a for loop. The result of this loop would simply be counting down from 10 to 0. Figure 24: Flowchart illustrating the for loop decrementing through numbers 100 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 for i := 10 downto 0 do WriteLn(i); 3 Example in C 1 2 3 int i; for (i = 10; i >= 0; i--) printf("%d\n", i); 4 101 6 PROGRAMMING STATEMENTS 6.8.5 Alex Cummaudo 1744070 Example 3: Infinite For Loop This program is an infinite while loop. Simply put, the program will never leave the loop (since the condition is always true (the incrementing will ensure that i never reaches -1 since it is initialised at a value of 1). The for loop requires a condition to be false to end the loop and thus the program never finishes unless manually terminated by the user. This is an example of an annoying bug that can result by poor use of loops. Figure 25: Flowchart illustrating the for loop iterating endlessly repeating 102 Alex Cummaudo 1744070 6 PROGRAMMING STATEMENTS Example in Pascal 1 2 for i := 1 to -1 do WriteLn('This will repeat forever'); 3 Example in C 1 2 3 int i; for (i = 1; i < -1; i++) printf("This will repeat forever \n"); 4 103