Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16
Programming fundamentals
Variables and constants
Programs usually use data in some shape or form. Data in programs is usually referred to as values. Variables A variable is a named memory address that holds a value. The value held in a variable can (and usually does) change as the program is running. A variable's name is known as an identifier. The identifier given to a variable usually follows certain rules: It can contain letters and numbers but must start with a letter. It must contain at least one letter (at the start of the name). It must not contain special characters such as !@£$%&* or punctuation characters. However, an underscore can be used. Spaces are not allowed. It should contain lowercase letters. However, uppercase letters can be used if a variable name comprises more than one word joined together. The name should be meaningful - it should represent the value it is holding. Acceptable identifiersUnacceptable identifiers score Score highScore high score high_score 123score highScore123 $core Variables make it easy for a programmer to use memory locations. The computer keeps track of which memory location the variable refers to. All the programmer has to do is remember the identifier the variable was given. Declaration and assignment Programming languages require a variable to be identified before a value is assigned to it. This is known as declaring a variable: score as integer - this would declare a variable called score which will hold integers. Giving a variable a value is known as assignment. A variable must be assigned a value before it can be used. For example: Score = 0 - this would assign the value 0 to the variable score. Some programming languages, such as Python, enable variables to be declared and assigned a value in the same line of code. Constants A constant allows a value to be assigned a name. Unlike a variable, the value assigned to a constant cannot be changed whilst the programming in running. Constants are useful because they are declared and assigned once, but can be referred to over and over again throughout the program. They are used for values that are unlikely to change, for example: Pi - const PI = 3.142 Constants follow the same naming conventions as variables, except that they are usually in uppercase. Global and local variables A global variable is one that can be accessed and changed throughout the program. Usually a programmer has to declare that the variable is a global. For example: global ID = 75 Local variables are confined to a loop or subprogram. This has the advantage of the programmer being able to use the same variable names again and again for different purposes. When using global variables, a programmer must be careful not to use a local variable with the same name. If this happens, the value of the global variable will be changed, causing the program to produce unexpected results. The three basic programming constructs Programs are designed using common building blocks. These building blocks, known as programming constructs, form the basis for all programs. There are three basic building blocks to consider: sequence selection iteration Sequence is the order in which instructions occur and are processed. Selection determines which path a program takes when it is running. Iteration is the repeated execution of a section of code when a program is running. There are two types of iteration: count-controlled iteration condition-controlled iteration All programs use one or more of these constructs. The longer and more complex the program, the more these constructs will be used repeatedly. Sequence Sequence is the first programming construct. In programming, statements are executed one after another. Sequence is the order in which the statements are executed. The sequence of a program is extremely important as carrying out instructions in the wrong order leads to a program performing incorrectly. In this pseudocode program designed to find the average of two whole numbers, the instructions are in the wrong sequence: average = 0 average = number1/number2 number1 = int(input("Enter the first number: “)) number2 = int(input("Enter the second number: ")) print("The average is ", average) Running this program would result in an error, because it tries to calculate the average before it knows the values of the numbers. This version has the instructions in the correct sequence: average = 0 number1 = int(input("Enter the first number: “)) number2 = int(input("Enter the second number: ")) average = number1/number2 print("The average is ", average) Having instructions in the wrong order is one of the simplest, yet most common, programming errors. It occurs no matter which programming language is used. Selection Selection is the second programming construct. In programming, there are occasions when a decision needs to be made. Selection is the process of making a decision. The result of the decision decides which path the program will take next. For example, a program could tell a user whether they are old enough to learn how to drive a car. If the user's age meets the required driving age, the program would follow one path and execute one set of instructions. Otherwise, it would follow a different path and execute a different set of instructions. Selection works by testing a condition. The test gives a Boolean result – TRUE or FALSE. If the result is TRUE, the program follows one path - otherwise it follows another. In programming, selection is implemented using if then else statements: age = int(input("How old are you? ") if age > 16 then print("You are old enough to drive a car!") else print("Come back when you are older!") endif In the above pseudocode program, the path the program takes depends on the condition. A variable, in this case age, is used to test the condition. If the value age is greater than 16, the result of the tested condition is TRUE and the program follows the first path, which follows the statement then. This path informs the user that they are old enough to drive. If the value of age is less than 16, the result is FALSE and the program follows the second path, which follows the statement else. This path informs the user that they are not yet old enough to drive. The statement endif ends the selection. Count-controlled iteration Iteration is the third programming construct. There are times when a program needs to repeat certain steps until told otherwise, or until a condition has been met. This process is known as iteration. Iteration is also often referred to as looping, since the program ‘loops’ back to an earlier line of code. Sections of codes that are iterated are called loops. Iteration enables programmers to greatly simplify a program. Instead of writing out the same lines of code again and again, a programmer can write a section of code once, and ask the program to execute it again and again until no longer needed. This program would print a message out six times: print(“Coding is cool”) print(“Coding is cool”) print(“Coding is cool”) print(“Coding is cool”) print(“Coding is cool”) print(“Coding is cool”) Count-controlled iteration repeatedly executes a section of code a fixed number of predetermined times. It uses the statements for and next to determine what code is repeatedly executed and how many times. This program would also print out a message six times: for count = 1 to 6 print(“Coding is cool”) next count The first line of the program determines how many times the code is to be iterated. It uses a variable, in this case count, known as the condition variable, to keep track of how many times the code has been repeated so far. The variable is given a starting value (in this case one) and an end value (in this case six). Every time the code is iterated, the value of count increases by one. At the end of the iteration, the value of count is tested to see if it matches the end value. If the result is FALSE, the code loops back to the start of the iteration and runs again. If it is TRUE, the iteration ends and the program continues with the next line of code. The condition variable used to initialise a for next loop can be used within the loop itself. This program uses a loop’s condition variable to print the 10 times table: for count = 1 to 10 print(count * 10) next count Key fact Using count-controlled iteration can lead to fewer programming errors and more flexible programs. As can be seen above, by using iteration a program is simplified, less error prone and more flexible. This is because: there are fewer lines of code, meaning fewer opportunities for typing errors to creep in to increase or decrease the number of iterations, all the programmer has to do is change the loop's end value Condition-controlled iteration Condition-controlled iteration repeatedly executes a section of code until a condition is met - or no longer met. There are two types of condition- controlled iteration: while loops - uses the statements while and endwhile repeat loops - uses the statements repeat and until While condition-controlled loops While loops test the condition at the beginning of the loop. If the condition is met, the code within the loop is executed before the program loops back to test the condition again. This program would print out a message six times: count = 0 while count < 6 print(“Coding is cool”) count = count + 1 endwhile The while statement defines the start of the loop. The endwhile statement declares the end of the loop. A variable, in this case count, is used for the condition. The while statement also tests the condition, in this case to see if the value of count is less than six. If the result is TRUE, the code within the loop is executed, then the program loops back to the condition, which is tested again. The iteration continues until the condition test result is FALSE, at which point the loop ends and the program executes the next line of code in sequence after the loop. Because the condition is tested at the start of the loop, it is possible for the code within it to never actually be executed. Consider this program: count = 6 while count < 6 print(“Coding is cool”) count = count + 1 endwhile The first time the condition is tested, the result will be FALSE as the value of count is not less than six. Because of this, none of the code within the loop will be executed and the program will move onto the next line of code in sequence after the loop. Repeat condition-controlled loops Repeat loops function in the same way as while loops, with one major difference - the condition is tested at the end of the loop: count = 0 repeat print(“Coding is cool”) count = count + 1 until count = 10 The repeat statement defines the start of the loop. The until statement tests the condition. Because the condition is tested at the end, the code within the loop is always executed at least once, even if the result of the test is FALSE. Key fact With a while loop, the code within the iteration may never be executed. With a repeat loop, the code is always executed at least once. Infinite loops Condition-controlled loops can be written to continue forever. This is known as an infinite loop. This program would run infinitely: count = 10 repeat print(“Coding is cool”) count = count + 1 until count = 10 At the end of the loop, the value of the variable count will be 11. Because with each iteration the value of count increases by one, count will never have the value ten, so the loop will run infinitely. Key fact Infinite loops can be implemented deliberately, or by accident. A programmer can accidentally create an infinite loop by not realising that the values the program uses cause the loop's condition to never be met. Infinite loops can be created using either while or repeat loops. Nesting Nesting occurs when one programming construct is included within another. Nesting allows for powerful, yet simple programming. It reduces the amount of code needed, while making it simple for a programmer to debug and edit. Key fact Different types of construct can be nested within another. For example, selection can be nested within a condition-controlled loop. Nested selection When using selection, the number of possible paths at a decision point can be increased by including one selection within another. This program uses nested selection: age = int(input("How old are you? ") if age > 16 then print("You are old enough to drive a car and ride a moped!") else if age == 16 then print("You are old enough to ride a moped!") else print("Come back when you are older!") endif Endif Here, there are two conditions that may be tested, resulting in three possible paths to follow. The second condition is only tested if the result of the first test is FALSE. Nested selection can be built up over and over to include many possibilities and paths for a program to follow. It allows for complex decisions to be made. Nested iteration Iteration can also be nested. This program uses two count-controlled for next loops, one within another, to print out the times table for all numbers from one to ten: for x = 1 to 10: for y = 1 to 10: result = y * x print(y, " * ", x, " = ", result) next y next x For every iteration of x, y is iterated ten times. This program uses condition-controlled while endwhile loops, one within another, to print out the times table for all numbers from one to ten: x=1 y=1 while x < 11: while y < 11: result = y * x print(y, " * ", x, " = ", result) y=y+1 y=1 x=x+1 For every iteration of x, y is iterated ten times. Operators An operator is a character, or characters, that determine what action is to be performed or considered. There are three types of operator that programmers use: mathematical operators comparison operators logical operators These operators are common to most high level programming languages. Mathematical operators Computers are designed to carry out calculations. Mathematical operators allow arithmetic to be performed on values. Mathematical operationOperatorExample Addition + x=x+5 Subtraction - x=x-5 Multiplication * x=x*5 Division / x=x/5 Integer division DIV x = x DIV 5 Remainder MOD x = x MOD 5 Comparison operators Comparison operators allow for assignment and for comparisons to be made. They are used in condition testing. Comparison operation OperatorExample Assignment = x=5 Equivalence = or == if x = 5 or if x == 5 Less than < if x < 5 Less than or equal to <= if x <= 5 Greater than > if x > 5 Comparison operation OperatorExample Greater than or equal to>= if x >= 5 Does not equal <> or != If x <> 5 or if x != 5 Logical operators Logical operators are used to combine logical operators to give more complex decisions. Logical operation OperatorExample And AND if x > 0 AND x < 10 if topic == "Computing" OR topic == Or OR "Computer Science" Not NOT while NOT x You can find out more about Boolean algebra in the computational logic study guide. Applying computer related mathematics Mathematical operators Computers are designed to carry out calculations. Mathematical operators allow arithmetic to be performed on values: Mathematical operationOperatorExample Addition + x=x+5 Subtraction - x=x-5 Multiplication * x=x*5 Division / x=x/5 Integer division DIV x = x DIV 5 Remainder MOD x = x MOD 5 Exponentiation ^ x = x^2 Calculations carried out by computers follow the same principles used when working out sums manually. Addition Addition uses the ‘+’ symbol: 6+6 x+y x=x+2 x=x+y Subtraction Subtraction uses the ‘-’ symbol: 8-6 x-y x=x-2 x=x-y Multiplication Multiplication uses the ‘*’ symbol: 5*5 x*y x=x*5 x=x*y Division Division uses the ‘/’ symbol: 6/2 x/y x=x/2 x=x/y Modulus Modulus gives the remainder from a division calculation: 7 MOD 3 = 1 (7 / 3 = 2 remainder 1) Many programming languages, such as Python, use the ‘%’ character to represent modulus: 6%2 x%y x=x%2 x=x%y Integer division Integer division (also known as floor division) discards the remainder: 7 DIV 3 = 2 (7 / 3 = 2 remainder 1 – the remainder is discarded) Some programming languages, such as Python, use ‘//’ to represent integer division: 6 // 3 x // y x = x // 2 x = x // y Exponentiation Exponentiation uses powers represented by the symbol ‘^’: 2^2 =2x2 =4 2^3 =2x2x2 =8 2^4 =2x2x2x2 = 16 Some programming languages, such as Python, use ‘**’ to represent exponentiation: 2 ** 2 x ** 2 x ** y Use of brackets Calculations within brackets are performed first. If there are no brackets, multiplication is performed first, then division, addition and finally, subtraction: For example: (4 + 2) * 5 =6*5 = 30 Whereas: 4+2*5 = 4 + 10 = 14 4-2/2 =4-1 =3 4*2/4 =8/4 =2 4+2-3 =6-3 =3 Where multiple brackets exist, the inside brackets are dealt with first: ((4 / 2) + (3 * 3)) + 2 = (2 + 9) + 2 = 11 + 2 = 13
Risk Analytics: From Concept to Deployment (World Scientific Financial Data Analytics), 2nd Edition Edward H K Ng - Download the ebook now to never miss important information
Risk Analytics: From Concept to Deployment (World Scientific Financial Data Analytics), 2nd Edition Edward H K Ng - Download the ebook now to never miss important information