You are on page 1of 144
A-level Computing/AQA/Print version/Unit 1 Contents = 1 Auhors = 1.1 Contributors and proof readers = 2 Book Overview = 2.1 AS modules = 2202 modules #23 Programming = 23.1 Tow to read the book = 3 Unic 1- Summary = 3:1 Definitions = 3.2 The examination = 4 Problem solving ‘© 4.1 Introduction o principles of computation = 41.1 Decomposition = 4112 Pattern recognition = 413 Patter generalisation and abstraction = 414 Algorithm design = 415 Limis? 42 References = 43 Stages of problem solving 15 43.1 Understand the problem ‘= 43.11 Define the problem = 432 Define boundaries = 433 Plan solution = 43.4 Check solution = 4.4 Top-down design and Step-wise refinement = 45 Stages of problem solving = 45.1 Understand the problem = 45.11 Define the problem = 45.2 Define boundaries = 453 Plan solution = 45.4 Check solution 1 46 Structure chars = 46.1 Selection = 462 heration 1 4.7 Decision tables = 4.8 Finite state machines = 4.8.1 Finite state automaton = 482 Mealy Machines = 4.853 State transition tables 1 4.9 Algorithm desig = 49.1 Sequenes = 492 Assignment = 493 Selection = 49.4 Repetition = 4.10 Trace tables = 4.11 Pseudo code = 4111 Structured English = 4.12 Searching and sorting = 4121 Bubble Sort, = 4.12.11 Step-by-step example = 4.12.1. Pseudocode implementation = 4122 Linear Search = 5 Fundamentals of programming 5.1 Variables 1 52 Introduction = 53 Variables = 54 Comments 15.5 Inputs and outputs = 55.1 Outputs = 552 Inputs = 56 Arithmetic operators = 56.1 Why the funny symbols? = 56.2 Addition = 563 Subiraction = 564 Multiplication = 565 Division = 565.1 Nomal = 56552 Integer division = 5.6.5.3 Remainder Division = 5.6.6 Exponentiation = 56.7 BODMAS 1 5.7 Built-in datatypes S711 Assignments = 5.8 Constant definitions 1 5.9 Selection 259.1 IF Statement = 5.91.1 Nested Ifs 1 59.2 Case Statement 5.10 Keration = 5101 While Do = 5102 Do While Loop = 5103 For Loop 1 $10.4 Loopy Loops = 5.11 Built-in funetions © SLL Arithmeti functions = SILT1 Round = 5.11.1. Truncation 1 5.11.2 String handling functions S121 Length 5.1122 Position 5.11.23 Substring 5.11.24 Concatenation = 5.1125 String conversion functions * 5.12 One-dimensional arays 5121 Uses 5.13 Funetions and procedures 5.14 Declarations 5.15 Calls 5.16 Parameters = 5161 ByRef = 5162 ByVal 1 5.17 Global and local variables = 5.18 Two-dimensional arrays = 5.181 Noughts and Crosses = 519 User-defined datatypes = 519.1 Enumerated = 519.2 Records and Fields 1 5.20 File handling = $20.1 Reading fies = $202 Waiting files = 5203¢8V = 520.4 File of records = 5.21 Validation = 521.1 Erortypes © 5.21,1.1 Compilation (Syntax) error = 5211.2 Runtime enor = 521.13 Logie (Semantic) error 1 5.22 Catching errors = 523 The role of variables = 5.24 Fundamentals of structured programming ‘= 524.1 Use procedures that execute a single task = 524.2 Use procedureséfunctions wih inlerfaces = $24.3 Use sensible variable datatypes ‘= 524 4 Meaningful identifier names = 5.2441 Use sensible variable names 24.4.2 Use sensible Function/Procedure names = $24.5 Try to stick fo one naming convention = 524 6 Don't make your names too long. = $24.7 Indent your work = 524.8 Use comments where necessary 1 5.25 The advantages of the structured approach = 526 Moddlo arithmetic = 527 Logical bitwise operators = 5271 Programming = 5.28 Set operators = 5281 Membership = 5282 Union = 52853 Difference = 5284 Imersection = 528.5 Programming 1 6 Fundamentals of data representation = 6.1 Bit pattems in a computer = 62 Denary, Binary and Hexadecimal number systems = 63 DenaryiDecimal = 63.1 Binary = 63.11 Max and range = 64 Hexadecimal = 6.4.1 Converting Between Bases 65 Binary arithmetic = 65:1 Addition = 65.2 Multiplication = 6.6 Binary facto = 67 Binary Fractions = 6.8 Two's complement = 68.1 Converting Negative Numbers = 69 Binary Subsraction 1 6.10 Status register = 610.1 Overflow = 6.10.2 The most common flags [Information coding schemes 2 ASCIL 3 Unicode 4 Frror checking and correction 5 Parity bits 6.16 Hamming code 1 6.16.1 Checking if correct 6:16.11 Detecting and correcting errors = 6162 Applying hamming code 6.17 Gray coding 6.18 Images 6.19 Bitmaps: 6.20 Overview 621 Resolution = 621.1 Pxample = 6212 Questions = 622 Colour Depth © 6221 Example = 6222 Questions 623 Vectors (624 Comparison between vector and bitmaps 6.25 Sounds 6.26 Analogue ané digital 6.27 Sampled sound = 627.1 Sampling rate = 6272 Sampling resolution = 6273 File sizes = 6.28 Sound compression = 62811 Lossless = 6282 Lossy = 629 Nyquist theorem = 6.30 References 631 Sound synthesis 1 632 Streaming audio 1» 7 System development life eyele +71 The cycle = 711 Cycle = 72 Analysis = 73 Design = 74 Implementation #75 Testing 75,1 Tes Plan = 75.11 Black Box Testing 75.12 White Box Testing = 75.13 Diy Run Testing © 75.14 Summary = 75.2 Typical, Froncous, Extreme = 76 Evaluation = 8 Skeleton code = § 1 Footnotes A-level Computing is an A-level course run for students inthe UK, Note: current version of this book cam be found at hiip://enswikibaoks org/wikiA-level_Computing/AQA Authors + (AA) Peter EI Kemp (editor) - London + (CIE) Peter Astbury - Alexandria, Eaypt Contributors and proof readers + Students from Christ the King Sixth Form College * Stadents from Loxford Schoo! + Stodents from Wreake Valley Academy + Peter L Higginson - Reading Thanks for helping out Book Overview This ita hook about A-Level Computing It aims to fit with the AQA GCE A-Level Computing (tp ilestore aga org, ukisubjectsspecificationslalevel/AQA-2510-W- SP-14 PDF) syllabus but is not endorsed by AQA. It should be useful as a revision guide or to find alternative explanations to the ones in your textbook. If you haven't heard ofan A-Level then this book probably wart be of mach interest ta you but you can find out about them at Wikipedia. IF any part ofthis book is unclear or even wrong then please past a comment on the digcussion page or simply fix it yourself In particular, please say i the book assumes any knowledge or skills which not all A-Level Computing students have AS modules ‘+ COMP! - Problem Solving, Programming, Data Representation and Practical Exercise + COMP2 - Computer Components, The Stored Program Concept and the Inlemet A2 modules: + COMPS - Problem Solving, Programming, Operating Systems, Databases and Networking + COMPS The Computing Projet Programming Accepted anguages (please note tha support fr PHP, C and Ct at AS Level was withdrawn in 2011. Ct has been reintroduced in 2015) save Peal Python vB 1c A2 Projects ean be written in any language, How to read the book You will meet several coloured boxes, bere are their meanings: Specification link What the specification says you must learn for each chapter Example questions and how to salve them Questions to test yourself, click below Answer: [Expand] Topics that aren't examined but you might be interested in There will bea lt of concepts that you need tobe familiar wit, definitions ate highlighted like so: ‘Word - meaning Jnit 1 - Summary This exam is worth 60 of your AS grade (30% of the full A-Level). Is examined in June only Adtevel Computing : Unit 1 Introduction to principles of compitation ~ Stages of problem solving ~ Top-down design Step-wise refinement Problem Solving Structure charts + Decision tables + Finite state machines « Algorithm design «Trace tables Pseudo code * Searching and sorting JA program + Variables « Comments « Input and outpat « Arithmetic operators - Built-in datatypes * JConstant Definitions + Selection » Iteration Built-in functions » One-Dimensional Arrays » Fundamentals of Programming | Funetions and Procedures - Global and Local Variables ~ Two-Dimensional Arrays ~ User-defined datatypes File Handling » Validation » The Role of Variables » Fundamentals of Stuetured Programming © | Modiulo arithmetic « Logical bitwise operators » Set operators Bit pattems in a computer + Denary, Binary and Hexadecimal number systems + Binary arithmetic Binary factions + Two's complement « Status register « Information coding schemes + ASCIL « Unicode + Fundamentals of Data Representation} Error checking and correction «Parity bits - Hamming code - Gray coding, “Images Bitmaps - Vectors Comparison between vector and bitmaps + Sounds « Analogue and digital + Sampled sound + Sound compression - Nyguist-theorem - Sound synthesis - Streaming auto Systems Development Life Cyele |The eycle + Analysis Design = Implementation «Testing «Evaluation Skeleton Code Janis «2014 +2013 +2012 +201 Definitions Unit | definition ist, The examination 2015 Exam 2014 Exam 2013 Exam 2012 Exam 2011 Exam Problem solving A-level Computing/AQA/Problem Solving, Programming, Das Representation and Practical Exerise/Problem Solving Introduction to principles of computation st behind the computing revolution. Over the course of this book I also hope to take vou through the steps the art of using computers to solve problems. This doesnt mean getting you to think like a compute, ut it does mean getting needed to practice computational thinkin you to think in ways that you ean use computers fo solve problems. Computational thinking is made up of four pars!) + Decomposition + Patter recognition + Patter generalisation and abstraction Algorithm design Let's take a look at what each ofthese mean Decomposition Part of being a computer seientst is breaking down a big problem int the smaller problems that make it up. Ifyou ean break down a big problem into smaller problems then you can ive them toa computer to solve. For example i] gave you acake and asked you wo bake me another one you might struggle, but sf you watched me making the cake and worked out the ingredients then you'd stand a much beter chance of replicating it Ifyou can look ata problem and work out the main steps ofthat problem then youl stand a much better chance of solving i Lets look at an example, the equation to work out the roots ofa quadratic equation _ nb VF Aae 2a On first look it might appear litle seary, but if we decompose it we should stand a better chanee of solving it Yr 2 dc 3H Pa eared sgh t VE - dae a 1g = et VT 2a 5 repeat for p/P dae By noting the steps down to solve a problem we can oflen recognise patterns, and by giving alist of steps we are one step close to creating en algorithm Pattern recognition Often breaking down a problem into its components sa litle harder than taking apart an algorithm, we oflen gel given a set of raw data then are asked to find the pattem behind it 1,4,7, 10, 13,16, 19,22, 25, This is prety easy with number sets, the above ts the pattem A, = r+ 3 But pattern recognition might sso involve recognising shapes, sounds or images. If you camera highlights faces when you point it at some friends, then is resognising te pattern ofa face in a pete detected by pater recogiton If your phone tells you the weather when you ask i: "What isthe weather Like in Witham’, then i has recognised the word "weather" and that "Witham" isa small own, in Essex, linking them together Patter recognition isthe computing behind why you get given tailored adverts when you log into your mail account or social network, hey have recognised the pattem of what someone like you wants to buy. Patter recognition might predict the weather, but chaos theory means that isnot always perfect. Pattern generalisation and abstraction Once we have recognised pattems we need to put it in its simples erms so tat it ean be used whenever we need to use it, For example, if you were studying the patterns of how people speak, we might noice that all proper English sentences have a subject and predicate. Algorithm design Once we have our pallens and abstractions we can slat fo write the steps thal a computer can use fo solve the problems, We do this by creating Algorithms, Algorithms aren't computer code, but ae independent instructions that could be turned into computer cade. We often write these independent instructions as pseudo code. Examples of algorithms could be to describe orbit of the moon, the steps involved in setting up new online shopping aecount or the sequences of tasks involved for a robot to build a new ear eee ont, tot) eid eden) Exercise: Computational thinking ‘What are the four main parts of computational thinking? Answer: lexpand) [Can you spot a patter in this set of numbers? 0,1,1,2,3,5,8, 13, 21,34, .. Answer: (Expand) }Can you come up with an algorithm to make a cup of ea? Answer: [Expand] Limits? Nowadays computers are ubiquitous and some would argue that there are no problems out there that 2 computer, given enough time, couldnt solve. But is tis true? Is every problem solvable by a machine and can we ever know if this is the case? Exercise: Introduction to principles of computation [Do you think that every process in nature can be simulated by a computer? Answer: [Expand] ‘Very early on in modern computing, a British academic named Alan Turing devised the halting problem, This problem is to do with whether we ean determine if program will ever come to ahalt of run forever, for example: |S anserariteina(‘etto") i ‘This would never finish, it would never come to halt as x wll always be larger than 8 and never get any smaller. This means the while loop will continue forever, constantly printing out "hello" In the two cases show it is easy to tell ifa program will halt or not, but i isn't so easy. Imagine we get a more complex piece of code! “This is harder but still solvable taking 2 little more thinking an a littl time on the processor. We could get apiece of code that takes weeks, years or even thousands ‘of years to finish. But how can we know that all programs will end or not? To determine whether the program halts we’ + run program with a given input, if stops we know it stops + BUT:Fitkeeps running beyond a reasonable amount of time we cannot conclude that it will loop for ever (maybe we need to wait a Title longer.) ‘Surely we create a mathematical proof te determine whether code will end or not T hear you say. Well le’'s prove just the opposite Prog A ae Halting) Loop Solution —> oR —> al Input x 4 Healy “The ting solution I kes an np rogram A anda set of inputs Xt then determines wheter the program wl ish executing not Prog A Hating) Loop Solution —> oR — Proga Litt Halt ‘You ca epace the Input X with a ‘copy ofthe program A. As the program A is made from code, tis «an be eanformed into Is and Os, ving He data input LLetus ereate a program K that will loop forever i the result of H is to halt, and ball ifthe result of H is to loop for ever: Teich) = nate then “oop raver FH says hak, K wil oop sys Joop K wil ha, thus he Haing Solion wl be undesiable ‘We can therefore se that there are examples of programs such as K that we cannot determine whether they ate ever going to halt. + Read more on the halting problem References 1. pwn google com/edulsomputationa-thinkng? Stages of problem solving Solving problems is never easy, v0 you need o break them down into manageable chunks: Understand the problem Before we should star solving a problem, we need to understand exactly whal the problem is that we are dealing with, Only then ean we stro think of solutions By doing this we can avoid spending a lot of time on unsuitable solutions that we'd then have to throw away’ Knowing the level of thinking required to solving the problem and having an idea ofa solution which is relevant tothe problem. Define the problem To fully understand a problem we need to think about the following: + Givenis): the initial situation + Goal: desired target situation Ownership: who does wat + Resources and constrains: tools, knowledge, skills, materials and rules, regulations, guidelines, boundaries, timing For example ter observing and researching the business I have found out the following: + Givents) [Blectronie Crafts isa small programming house looking to create a football game forthe mass market. They have experience making games for the Super MES. and are looking forthe next hit + Goal ‘To create a football game forthe Super MES, © Ownership ‘Barry 1s a graphics designer, Mike 1s the lead programmer, Coral 1s an Al programmer, Jaya 1s the boss. Resources and constraints ‘The Electonic Crafts offices have 4 development machines running Linux and Ct, The platform that is being developed for is the Super MES using Visual Basic, Bary, Coral and Jaya have all programmed the Super MES before, but Mike hasn't Mike is skilled in C'-+ Tne game must be complete within 9 ‘months, Fletronic Cras have a game engine already running on the Super MES that you could use. Fletronic Crafts specialise in eartoon like games for children and this football game should be branded as such. There should be no violence or swearing. Define boundaries Understanding the limits to coming up witha solution and knowing what can ad eannot be done through lateral thinking, These boundaries may also be known asa type of constraint I: is important to define what your system is not going to do - as important as considering what it should do, Most software projects fil because of specification creep where the code in development moves away from the requitements because someone (often the developers themselves) feels that it would be good f the application also did his and thinking. You will end up with code that you do not know ow to test or fix when it goes wrong - which 8 sign of poor development that markers will not be able to ignore! Plan solution. Once you have defined the problem, given, goal, ownership and resources you need to stat thinking about how you will implement a solution. This might involve using jools such as flow charts, pseudo code, top down design, finite state machines ete. These will allow you to get lated with actually making the solution, We will meet al ofthese methods shorly Check solution Once you have created a solution you need to check it against the original problem. IF solves the problem then you have a successful solution. It doestt then you have filed and will have to go back to the drawing board to try another solution that works Note that you can (and should) test your design on paper against the specification (and your test plans) before you code it Ths "walk through* approach is often done in eam working - which encourages the consideration of abnormal data input, or using work flows that had not been thought of Top-down design and Step-wise refinement A top-down approach (also known as stepwise design) is essentially the breaking down ofa system to gain insight into the sub-systems that make it up. Ina top-down, approach an overview of the system is formulated, specifying but not detailing any first-level subsystems. Fach subsystem is then refined in yet greater deal, sometimes in many additional subsystem levels, until the entie specification is reduced to hase elements, Once these base elements are recognised then we can build these as computer modules. Once they are built we can pul them together, making the enlie system fiom these individual components. ‘Top-down design - in whch design begins by specifying complex pieces ard then dividing them into successively smaller pieces ‘To show you an example of Top-Down design well take the et of making pancakes. Starting fom the top we have the task to 1+ Make some pancakes ‘But saying that by itself isnt enough fo actually make any pancakes, we need to break the task down: + Make some pancakes 1 Organise Kitenen 2. Make Pancakes 3. Serve Fach ofthese tasks ean then be broken down further: 1. Organise Kitchen 1 Clean surfaces 2. Get out mixing bowl, whisk, sp0on, sieve 3. Get out plan flour, salt eggs, ful fat milk, butter 4 Putonapron 2. Make Pancakes 1. Siftsalt and flour inte bow! 2. Break eggs into bow! 3. Whisk 4 Add water and milk 5. Add buter| 6 Whisk 7. Cook 3 Serve ‘And each ofthese tasks can be broken down further, let us take a look a the Cook: + Cook Get pan to semperature Pour bater in Spread batter to edges Use plastic spatula to cheek bottom of paneake When brown, ip Use plastic spatula to check bottom of pancake ‘When brown finish ‘We can break down some of these tasks even further. So starting ata single point, the creation ofa pancake, we have broken down the task into it individual pats Exercise: Top-down design [Draw a top-down design tre to three level depth for making a moder Firs Person Shooter Answer: (Expand) Stages of problem solving Solving probleme is never coy, vo you need to break them down nto manageable chinks Understand the problem: Before we should star solving a problem, we need to understand exactly what the problem is that we are dealing wth, Only then ean we str o think of solutions. By doing this we can avoid spending a lot of time on unsuitable solutions that we'd then have to throw away. Knowing the level of thinking required to solving the problem and having an idea ofa solution which i relevant to the problem. Define the problem To fully undersia 8 problem we need to tink about the following: Givens): he initial situation * Goal: desired target situation + Ownership: who does what + Resources and constrains: tools, knowledge, skills, materials and rules, regulations, guidelines, Boundaries, timing For example After observing and researching the business I have found out the following: + Givenis) Bectronie Crafts is a small programming house looking to ereate football game forthe mass market. They have experience making games for the Super MES and are looking forthe next hit. + Goal “To create a football gume forthe Super MES + Ownership ‘Bary is a graphics designer, Mike i the lead programmer, Coral san Al programmer, Jaya isthe boss. + Resources and constrains ‘The Electronic Cras offices have 4 development machines running Linux and C++, The platform tet is being developed fri the Super MES wsing Visual ‘Basic, Barry, Coral and Jaya have al prograramed the Super MES before, but Mike has Mike is siled sn C+. Tae game must be complete within 9 ‘months, Electronic Crafts have @ game engine already running on the Super MES that you could use. Electronic Crafts specialise in eartoon like games for children and this football gume should be branded as such. There should be no violence or swearing Define boundaries Understanding the limits to coming up with # solution and knowing what can and cannot be done through lateral thinking, These boundaries may also be known as a type of constraint cis important to define what your system is not going todo - as important as considering what it should do, Most software projets fail because of specification creep = where the code in development moves away from the requitements because someone (often the developers themselves) fels that it would be good ifthe application aso Jid his and © > Fag [Eserson- you dnt ned to know his for the exam] Check dataset o proces to top oF start processes. For example when the nd of File "© [that s being read is reached, or flag to say whether data sent wes inthe correct format Lets take a look ata simple example of how this might be executed when representing the fllowing code: pete) ps terectnm, ue) toate sanction svesana.t) enor BT hands comes resin) ‘mb > necieiencinet 1 eatpnnatsd sale tint ergs «a Calculate Average ‘oy oy inputNums, loutputavg average ‘A stuctuce chart fr the above code Create structure charts forthe following code: ontion average.) noe 0 saptettety tabi etinet tion) Selection Process Process Process ‘Surutare Chart representation oF the section code A selection in a Structure Char is determined by the diamond symbol. This means a condition willbe checked and depending on the result, different modules will be executed, | Shiuoer SSemrwoer Weration Process Ka Process Sirosiee Chart oF he cde tothe i Using the semi circular arrow we can represent iteration in Structure Charts, The arrow encompasses a lik to a module, implying that module is executed multiple umes. Let take a look ata coded example Create structure chats forthe following code: sb haanythren) Eee cn see } sy teary ett a 9) i Cease Se = ate function va) I tnction ate, ©) | sanction storan tcsbeereAEG(‘oopran etrted enter your vaner") i crore cin’) i a ened i eeeteireesec amber of trees a 9) Decision tables Decision tables are compact and precise ways of modelling complicated logic, such as that which you might use ina computer program. They do this by mapping the Jfferent states ofa program to an action that a program should perform, Decision tables take on the following, format ‘The four quadrants ns | Conlition alternatives (Conil ‘Actions | Action envies The limited-entry decision table is the simplest to describe. The condition alternatives are simple Boolean values, and the action entries are check-marks, representing which ofthe actions in a given column are ta he performed A technical support company’ writes a decision table to diagnose printer problems based upon symptoms deseribed to them over the phone from their clients, They type he following data into the advice programs 1. Printer does print 2. Red light is Mashing 3. Princer is recognised The program then uses the decision table to find the correct actions to perform, namely that of Check / Replace ink Printer troubleshooter Rules Printer does not prt VY PPR EDS Conditions [A red light is Mashing ¥[y[y|N[¥[¥[y]N) Printer is unrecognised ¥ [nly [y]¥[s ‘Cheek the power cable Xx ‘Cheek the printer-computer cable [X| [3 Actions [Ensure printer sotware is installed [x] [x] [x[ [x (Cheekireplace ink x]x ES ‘Check for paper jam x| [x Let’ take a Fook ata computer game example, for a football simulation the following rues ae set up. Rules 90minues —_Y|Y) |V, ‘Team A Winning Y Conditions ‘Team B Winning) | [Y|Y Draw Y Game Over XX. ‘Team AWins |X ‘Actions [Team B Wins x Extra Time x Keep Playing |XX ‘What happens when: 1, 90 minates up 2. the game isa draw Answer: Keep Playing and give them some extra time Create a decision table forthe following program in an office email system + Send email when Recipient address present, subject present, before 5:30pm + Ifafter 5 30pm then put in pending folder + If Recipient address missing or subject message, give warning message Answer: [expand] Describe the use of Decision Tables Answer: [expand] Finite state machines a —Quno) Example of simple finite sate smachive p> sart ate = seep tte A finite sate machine consists of states, inputs and outputs, The number of states is fixed, when an input s executed, the sate is changed and an output is possibly produced, Finite state machines are widely used when designing computer programs, but uso have thei uses in engineering, biology, linguistics and other sciences thanks to their ability to recognise sequences. A finite state machine expressed visually isa State transition diagram. tis used to show all the states, inputs and outputs. Each state is represented with acre, and each vasition with an arrow. Transitions are labelled with an input tat causes a transition and possibly an output tat results from A double circle signifies the accep sate. Not all FSMs will have an accepting state and itis possible they could run forever A finite state machine canbe wit or without outputs Finite tate automaton te State Automaton - an FSM with no outputs — OKRA ‘OM Looking atthe above diggram we can see tat it starts in state SI, an input of 1 will keep iin state one, and an input of 0 will move itt state $2. Once in $2 an input of {will keep it there, and an input of 0 will switch it back to SI. This means thatthe following inputs are valid Ic might appear to accept any binary value, but this isn't ue. The only state it ean accept in is state S1. This places the following rule on all accepted inputs: "A combination of binary digits involving an even numer of zeros’. This is useful for parity checks. If try the following | am stuck in state S2 and the FSM has not accepted. Can you create a FSM to ony aecept Binary numbers with add mambers of 1s? Exercise: Finite State Automaton For the FSM above which ofthese inputs are vali saacdb ababacdaaae abed acda sedbab Answer: [Expand] For the FSM above which ofthese inputs are valid 987654321+994-0 s.54284 BeBe TH6eSe4e34201 oeeaee 9988-77 Answer: [Expand] Draw a finite state automata that will secept the word Banana whilst using only 3 states Answer: =xpand) Drawa fi estate automata that will accept the words: + Tim © Gait = Genrim Answer: Meal Machines Mealy Machine - an FSM with outputs Some FSM output values dependant on the state and the input values: uw 010 Is outputs Shifing all the bits right, and dividing che binary number inpt by two, Exercise: Mealy Machines 150 For the Mealy machine above, what do the following inputs output: 1 50 2. 20,10,20 3. 10,10,10,20 What does this machine do, what do the outputs tll you? Answer: expand] What is the difference between a mealy machine and a finite state automaton Answer: [Expand] such things a nondeterministe finite automaton where, for agiven input there are multiple paths (or none) that could be taken Th this section we are learning about deterministic finite automaton, This means that fora state and a valid input there is enly one possible tansicion to tke, Thee are Insta p, for input | there are reo posible tastions State transition tables A state transition table follows every state and input, Inputs are usally placed on the let, and separated from the outputs, which ae on the right. Here's «simple example ofa state machine with «wo states, anda binary input Tnput| Current State] Next State| Output ° 8 Sul 1 s S| null ° S St null Ss null Exercise: State transition tables Create a state transition table forthe following FSM. 1 - QAKQ -@ G) Answer: Create a state transition table forthe following FSM. nd] uo QB.Q @.. ©) uo oo Answer: [Expand] Draw the FSM for the following state transition table Input |Current State| Next State Output Timer| Green| Green null Butlon, Green| Yellow | all Timer Yellow | Red null Timer) Red Green| nul Answer: Draw the PSM forthe following state transition table Input] Current State] Next State| Output aw oul b | @ al | mul 2a | ul eal at | mul 2 au nul 2 aul Answer: Algorithm design Algorithm -a set of instructions independent of any programming language that calculates a function or solves a problem, Express the solution toa simple problem as un algorithm using flowcharts, pseude-code or structured English and the standard constructs Sequence Om> z: Assignment Assigning a value io variable Selection Selection is choosing a step Easianrtetingt $e poxtoe'y Eecsateaeiteline(" equals 0°) Excebteeseelina(" $2 sapere") Repetition A sequance of steps that loop until arequieznent i met. Doe While (A = TRUE) End While ‘While (A= TRUE) De e End we For (A, B, C) DoD Loop Trace tables {able -@ technique used to test algorithms to make sure that no logical errors occur Hand tracing ory running’ allows you to use a trace table to 1 see what code will do before you have to run it + find where errors in your cade are Taking a program like the one below we need to keep track (trace) all he variables and outputs. To do this we create w trace table output 313 The exam will normally ask you to create a trace table of some sort so you need tobe very confident with them, The exam will usually give you the headings but justin case, there are several steps in making a race table, the fist one i to note the table headings, this involves the following 1. VARIABLES: note all the variables in the piece of code you are looking at (this includes arrays). Note cach variable a8 a heading 2. OUTPUTS: note if there is an output and put this as a heading 3. INPUTS: if there are inputs specified, put an inputs column and be prepared to fill it in. [is very easy to jump right in when filling in trace tables, but you must be careful, The exam will ry and trick you, so trying (o predict what trace table will do i nota good idea, Infact, the best ea iso switch your brain of and tackle the problem line by line, exactly a a computer would, Take a look atthe following example in mang) otuee = (284,05,658) 1. note all the variables: num array / sum / avg x 2 note i there isan output: yes 3. if tere are inputs specified: 90 ‘So we should construct the following table: 0 [1]2/3/4)5|6 sum avg x output 108356120 0 ‘Now looking a the names of the variables you might be tempted 10 add all the values in the aay together to Find the sum, and then find the average number from this caleulation 35/7 = 5 However youd be wrong, create a trace table and see if you can find the correct answer Answer: expand] Complete the trace table for he following code, where the number input is 39 eros riteton) Answer: What does the above code da? Answer: (Expand) | Complete the trae table fr the following code [Expand] What function does the above vode perform? Answer: (Expand) Pseudo code Pseudocode - informal high-Level description of a computer program or other algorithm, intended for human reading rather than machine reading pseudocode uses a combination of programming terminology and plain English to describe algorithms ina form that is easier for people to understand than conventional programming laguage code, There are no standards for pseudocode and a program in pseudocode isnot an executable program. Psuedocode is used in textbooks and scientific publications to deseribe various algorithms, and also in planning of computer program development, for sketching out the structure ofthe program before the sctual coding takes place. [typically leaves out deals that are not esseatial for human understanding ofthe algorithm, such a variable declarations, system-specitic cade and some subzoutines. Example: Pseudocode Below is an example ofa pseudocode algorithm Piece) [ Structured English Structured English - A restricted part of the English language used to describe algorithms Structured English i very similar to Pseudo code, but it tends not to use so many mathematical symbols, Often people start with Structured English, convert it to Pseudo Code and then write Executable Code. Examples of common keywords: START, B61", ENC, STOP, 00, AHILE, OD ABTLE, FOR, UNTIL, 0 UNTIL, REPEAT, END MAILE, ep UNTEL, END REPEAT, IF THEN, TF, ELSE, TF ELSE, EMD TF, THEN, FLSE THEN, ELSE TF, 50, CASE, EQUAL, LT, Le, 6T, GF, NOT, TRUE, FALSE, AND, OR, xOR, ‘Structured English Preudo Code Executable Code nave EQUAL “harry” THEW mane av "harry" TH tine tyole reine’) i What ae the rules when writing pseudocode? Answer: [Expand] Whats the difference hetween pseudocode and a programming language such as javascrip? Answer: (Expand) For the following pseudocode write a VB NET equivalent Answer: [Expand] Write pseudocode for the following probl ‘Answer: ‘[Expanc] Searching and sorting Bubble Sort ” ‘A bubble srt, a sorting algorithm ha ‘ntnuoudy steps through ais, swepping ites until they appar in he corset order Bubble sort isa simple sorting algorithm that works by repeatedly stepping through thelist to be Sorted, comparing each pair and swapping them if'they are inthe wrong order. The passthrough thelist repeated until no swaps are needed, which indicates thatthe lists sorted, The algorithm gets is name from the Way larger elements "bubble" to the top of the list Its. avery slow way of sorting data and rarely used in industry. There te much faster sorting algorithms out there such as insertion sort and quick sort which you wall meetin A2, 653 18 7 2 4 Step-by-step example Let us take the array of numbers "S 1 42 8", and sot the array fom lowest number to greatest number using bubble sort algorithm. In each step, elernents written in bold are being compared, First Pass: ($1428 )—5( 18428), Here, algorithm compares the fist two elements, and swaps them since $> 1 (18.428) —$( 1 4528), It then compares the second ané third tems and swaps them since 5>4 (14528) —3( 14258), Swap since 5>2. (14288)—3( 14258), Now, since these elements are already in order (8 > 5), algorithm does not swap the The algorithm has reached the end of thelist of numbers an the largest number, 8, has bubbled tothe top. It now stats again. Second Pass (14258 )—4( 1425.8), noswap needed (14258) 5(12458), Swap since 4 >2 (12.458) —3(1 2.458), no swap needed (12.488)3( 12458), no swap needed Now; the aray is already sorted, but our algorithm does not know itis completed. The algorithm needs one whele pass without any swap to know iti sorted Third Pass: (12458) 4(12458) (12458) 9(1 2458) (12458) 9(1 2488) (12.488) 5(12488) Finally, the array is sorted, and the algorithm can ters inate. Peeudecode implementation The algorithm can be expressed as Nay Exercise: Bubble Sort We will now look at an example in Visual Basie using an array of people's eights. The following data st is being passed Ineight| 1 9x 2 9 54 2 3 4 su vemteserecytet ment) Ae Sons) Feapelcane oy'stang [Construct a trace table for the above code Swapped Count MaxSize neisat apped Count MaxSize Temp non False 4 ‘mall 98/12 99/54 Answer: (Expand) What does the above code output? Answer: [Expand] ‘Show the following lst after ono pass of bubble sort Sort into alphabetical order: nto alphabetical order: G.CNA,P,C Answer: [Expand] Sort into numerical order: 12, $6,0,23, 10 Answer: span] Show the following after? passes Sort ino alphabetical order: Answe! (Expand) Sort into numerical order: {Expand Lets look at a more complicated example, an array of structures, TopScores The following data set is being passed TopScores [Name Score 2 Dave 78 3 Gerald 23 ‘Colin 75 nt = 1.Score > Topscare( count). scare Then ‘eg. core = Tepscores(eo)scare Exercis : Bubble Sort (Harder) _ Draw a trace table to se it works "P TopScores Swapped Count MaxSize 1 2 3 4 Michael 45 Fale 14 null pull Dave 78 Gerald 23 Colin 75 {Expand Linear Search The following pseudo code describes atypical variant of linea search, where the result ofthe search is supposed tobe either the location ofthe list tem where the desired value was found; or an invalid location -/, to indicate thatthe desired element does not oecur inthe list, SrehSten © Soaaierreadiiae) Try the code above searching fr items "w" and then for item "2" Code Output Soa coer ennetcyy Code Output "Cat" "Mouse’,"Frog","Lion’, "Panda" *Llama’,"Bee* For the array abave, how many searches would it ake to find the following data Panda! Answer: [Expand] “camel” Answer: (Expand) For an 7 length list of items, what isthe maximum number of searches it would take to see ifan item is there or not? Answer: (Expand) "Make a race table for the code above, where searchiven= "0" Answer [Expand] Extension: Binary Search fast, for example if you had 1,000,000,000 names ina database and you searched for "Miles, four things might happen + Miles is at the beginning ofthe database and you find him quickly ' Miles is in the middle of the database and you find him in around $00,000,000 searches + Miles is at the end ofthe database and it takes you along time to find him | Or 1 Miles is in your list and it will take 1,000,000,000 comparisons to prove this! “The worst case senario is 1,000,000,000 searches. The wverage case $00,000,000. There must be a fster way. There is! your dat is sorted then you can perform a Binary Search. This involves splitting the data into half. For example, let's search for Miles again in a much smaller list (AY "Bernie", Claire" "Mohammed", "Peter" yon", "Yvonne" + We compare Miles tothe mide name, "Mohammed, Miles is before Mohammed inthe alphabet so we know that Miles won't be in the right hand side ofthe Hist, we ean how it aay” (PAW Beenie 1 We spit his new list in half and compare Miles with the new middle name, “Bernie”, Miles is later in the alphabet than Bernie, o we ean throw the left hand side away. (CAN? bernie *Catee” 4 Peiee?-*Simon! . ire" pee ee eee * Finally we compare Miles to the middle name of this single item list, ‘that Miles iain the list. "aire", Miles isthe same as Claire, there are no more items to compare so we know ‘This only took 3 comparisons using binary search, it would have taken 7 using linear search. Tt gets even better when we use large lists. For example, our 1,000,000,000 item list would only take a maximum of 30 searches using Binary Search! It's very useful to have sorted data ‘You will learr more about binary search and the speed of algorithms in A2 Fundamentals of programming Features of Imperative High Level Languages IMlusrate these features for a particular imperative, third-generation language such as Pascal © A program, + Variables + Comments + Input and output Use the fllowing eppropriately + Buin Inege, byte real, boolean, character, string, dateime. + User-defined "Enumerate, subrange, sts, records, arrays + Datatypes = Builtein datatypes + Constant Definitions * Bulltin functions += User-defined data ypes 1 Type Definitions + Variable Declarations + Constant Definitions * Explain the advantages of named variables and constants Assignment + Teeation * Selection (© Procedure Function Decteretions + Procedure and Function calling - Explain the advantages of procedure/functions + Procedure and Function Parameters ' Deseribe the use of parameters to pass data within programs. + Understand the different mechanisms for parameter passing. by value and by reference Arithmetic operators including moduto arithmetic +,-, x, DIV, MOD Relational operators =, <,>, <>, <=, >= Boolean operators NOT, AND, OR Logical bitwise operators NOT, AND, OR, XOR, Set operators Union difference, intersection, membership Built-in unetions + Arithmetic functions: ound, trancaton. + String handling fumetions: length, position, substring, concatenation. * String conversion functions to/om integer, real, date/time, + Selection * eration + Functions and Procedures + Operators = Anthmetie operators = Modulo arithmetic = Relational operators = Boolean operators * Logical bitwise operators 1 Set operators Recognise the different roles a variable ean take: ‘fixed valu, stepper, most recent bolder, most wanted holder, gatherer, transformation, follower, temporary. + Global and Local Variables + The Role of Variables ‘Understand the structured approach to program design and eonstruction, + Construct and use structure tables, structure charts and hierarchy charts when designing programs. + Use meaningfal identifier names + Use procedures/fanctions with interfaces + Use provedures that execute a single task. + Explain the advantages of the structured approach, + Fundamentals of Structured Programming Anrays ‘One- and Two-Dimensional Arrays - Use arays in the design of solutions to simple problems ds, Records and Files ‘Read/uritefromito @ text file (including esv file) Readiwrite records fromto a file of records * Data Structures ‘= One-Dimensional Arrays = Two-Dimensional Arrays ' Fields, Records and Files lidation + Understand the importance of validation of input + Program simple validation Validation + Debugging Variables questions Introduction When vou fist load Visual Stadio and select to run a Consoie kpe1tcation, you wil be presented with some souree code These lines of code wil tell the compister what o do, currently they do very little and we need to get started: Tradition has i that de fist progra IF you are using Visual Studio then you can make the program run by pressing FS orbiting the Rum button that looks lite lke this: You should get the following output programmer should write is “Hello World!". Write the following seurcecode int a command line VB.NET programming Code Output There itis, youre on your way to becoming a programmer! There is a Jot more to lear and over the cours ofthe next few sections yor! gt crash course in programming First ofall let's look at another program and find out what it's doing matty iI take a look at each Tine: sodute node - this lin tells the computer that ths particular progeam is called module! in main defines the section of code that is executed first 3. Console. urdteline(*helto...29")- this line writs plan text to the console window, There are lots of other console commands we ean perform such as console. beep ard console, color, We'll lam about thers i the inputeutput section 4. console-arsteline(" * 6 =~ & 6 * 6) ~this writes outa combination of text (everything between tae “speech marks") and calculation (56), joining the two together with the ampersand (&2) 5. console.readline() - Ifyou are running VB fiom a command line this won't be necessary, but for people using Visual Studio it i. consale.readlsne() was fo ‘you to hitthe return key. Modern computers are very fast and ifyou didn't have this then the words displayed on the screen would appear and then disappear £90 {ast forthe eye to see, the sereen would appear, then instantly disappear, take this line out and see what I mean 6. end sub defines the end of the main code section fend module - signifies the end of the small program we have written Phis shotald output the flowing: Code 01 Se ed But wait second, this program: isnt much use! Your name probably int Peer and you're even less likely to be 29. Time for you to write some code yourself Exercise: Hello World! a short program to write the following to the sereen, replacing the name Dave with your own name (unless it also happens to be Dave) ‘Code Output Peter My name is Dave and this homework is too easy pean Sn [expand] You can show your friends and family. But wait! I's a rubbish program if you want to share it amongst your friends! Fach one of them will hve to go and change the source code, then bit run, Rubbish unless you live ina countey’ where everyone has the same name, let's call that country Davia, I'm pretty sure you don't live there. We beter look at making a program that isa litle more interactive, where people can change parts ofthe program without having to keep ee-writng it For that we'll need something called a variable Variables Lets take a look at tis program: Consstesete inate * nae BI) But instead i says Code Ouipal eee scene) This also means you are 348 months o! De Wht a friendly program! Let's break it downline by line in isa variable declaration, creating a temporary data store, 2 variable, an calling it ane It also makes sure that whatever goes into nage will be a sting by Setting itto as string We declare another variable called age and make sue itis stored as an integer (a whole nurnber) The variable name that we created earlier is now assigned a value and as i's a string we beter use speech marks - "Pete The variable age that we created earlier is now assigned a value and as i's an integer we beter not we speech marks - 29 This line wails things to the screen, starting withthe text "Helo * which attaches that variable we saw eater Io, bt instead of putting the variable name, puts the contents of the variable ("Hello Peter"), then it attaches some more txt ("Hello Peter you are ") and adds another variable age. Bven though age isan integer wwe can stick i together with a string ("Helio Peter you are 29"), ‘Then finally it uses the ampersand once more to attach the final piece of text ("Hello Peter you are 29 years ld) 6. This line works in pretty much the same way, but it does calculation, working out the age in months, Computers ate lke giant caleulators and you can perform all the sums you can perform on your litle pocke: cale performed and far far more using them! 7. The great things about variables i that we can use them again and again, here we say "Bye " and using an ampersand stick on the name ofthe pesson, This is va, by using a variable we only aeed to wte "Peter" once and save it a8 nane. If someone else came along and wasted to change the rogram they just need 10 thange the value of rane, Programming is all about being as lazy as possible 8, Good old consele.readline() stops the sereen disappearing too fast prt I ‘Variables work ie abeled ones that allow you sore things insiée thom to retrieve later What you have just seen i a declaration of two variables, name and age. A variable is a known or unknown value that has been given a symbolic name. This allows the name tobe used independently ofthe value. Its advisable that a meaningful name for readability and convenience. This name is known as the identifier. To declare 2 variable in VB NET we do the following Most programming I feame !~ Name) aages have rules about identifiers: they generally have to use only Alphanumeric characters (a, 0. 9) and some languages ae case sensitive variable short term memory used to store temporary values in programming code Once you have declared a variable you need to assign ita value. Assignment, in programming tems, i the giving of value toa variable, for example Producing: Code Output Lipdate the code a ve to display the age in days, hours, minutes and sesond, No use of calculators! Use the cade to do all the work for you Answer sxpand) [Give a good reason why you made age a variable in the previous code Answer: Expand] What wil comstewetetint "x autiohing oy y= Answer: (Expand) Comments Over the course of the next few chapters you might see a lot of text in the code examples tht doesit seem to do anything other than aid understanding ofthe code. This ext i called a comment and if you have this book in colour youll see that these comments are highlighted in green, ‘comment - programmer-readable annotation inthe source code of a computer program that helps programmers understand the code but is usually ignored a un time in Visual Basic all comments start with an apastraphe () or the word ne, Let's take a look at a quick example: vine) sects Seared sete seniren, Another use for comments i o disable code that you don't want to delete but you do want to keep. By commenting out the code it cans that you can always restore it later if you want Io, Ish? a good idea to eave commented out code in final code, but it iva very common practice when you are developing something pple teint ne are) Inputs and outputs An important part of computer vode is allowing your user to input data into the program, things such as text, Key presses or even a data feed from # motion sensor games controller Once the data isin the program you want the system to output responses these may take t Jocuments or data output to another program, form of output toa screen. graphics text, output to a sound device, printed For this unit you need tobe familiar with afew input and output commands. The lite black box that appears on your screen is called the console. In VB.NET all the commands t read and rite fom this are accessed from the console. command, let's take @ look at some: Outputs For the AS course its unlikely you will ned anything beyond the print to screen command and the write to file command (se later), There are two write to sereen commands that you should be familiar with -congotesarta( tte *) SERRE doe cy This would output the following: Code Outpt Notice the difference between a nsteline and a write command Extension: Console methods \We can doa lt of things with the censete command, Ifyou are using Visual Studio then type the following Up should pop some suggestions, Play around with sackgroundCotor and Foregrounacolor ers will most likely hate it. conste-pent pia ten ‘Stools SepLloe sn) beep ot a0eou for 6.5 seconds Find out more about the console command on the MSDN website (hp msdn microsoft comfen-uslibrary/system console_methods( vs 80) aspx) Inputs Fe make your program interactive you'll need your use to input commands, forthe exam these wil mast likely be text instructions or reading from a ile (covered Inter), You might look at buttons and games contollers next year. In VB.NET there are two types of input command that you need ta know There is also the console. ReadKey()eommand that reads ina single character. Take a look at this example: es tt Ci vt ne Code Output Please select fom options ni See Exerci inputs and Outputs [What docs the following code « Answer: [Expand] Write code to display the following tothe scree: Lg coe usput Answer: (Expand) ‘What would the following look like aaterdtelig(-teter your age: “) forthe inp: Nobby Answe! [Expand] Arithmetic operators ‘Operator - «programming device that performs Function on one ot more inpuls, for example arithmetic operators (-/*) Visual Basic NET provides a basic set of operators to calculate simple arithmetic, Lets look at a short example of arithmetic operations before we jump into the operators themselves in this example we will also be using some basic variables. The Dim operator ereates the variable First, We Set the total Sales to 3142.51. The * operator calculates multiplication, so line 4 is equivalent co multiplying 03 and Sales together. Sales is 3142.51, s0 our result should be the product of 0.3 and 3142.51, and stored in Cormission, Why the funny symbols? With the exception of addition and subtraction, the symbols used are differen othe ones used in real life, This is simply because the ether symbols are not available 1 standard keyboard (try and find = mon yours) or the symbol isin the alphabet and can be used for naming a variable (x), Addition This adds two numbers together, and is denoted by th together, Examples y the amount indicated onthe right Ic also works with Strings as a concatenation operulor. Ped 8, cert 8 A for Seed” Fe fences fotutt fe Jon dutsea ovr en foce™ Multiplication This multiplies two aumbers, and is denoted by the "*” symbol. Examples Division There are more types of division than the one denoted by the "!" symbol. Ther i als integer division and remainder division, Normal Mtoe tat at ue the Single Lae to hove seine) symbol. If stings ae involved it may also do String concatenation, that means sticking the two strings Tis divides two Tumbers, and gives the result without the remainder 1 the quotient 1s a Gecimal, E-xamples: Remainder Division This divides two numbers and gives the results remainder if the quotient s a decimal, This is denoted by the operator "Mod." Examples: Exponentiation This is raising a number to @ power For example 72in VB Net code is This results inthe number 49 being assigned tothe variable x. It can also be used to calculate the square root of a number, The square oot ofa number is the number raised tothe power of 0.5, Note Ie is necessary to ensue thatthe variables be correctly declared to get the desired results. The following example works, but will produce the wrong result, This is because the Integer class does not allow decimal places (ust like mathematical integers) Since x is declared as an Integer type, the value square rot, areal number, is stored incorreely Any nth oot of number is the aa be calulated by rising the number to the power OF / This x bocause BODMAS You have probably learnt about the order of operations in maths. BODMAS also applies to computer calculations. This means that when calculating a sum, the program wil ealculate: 1. Brackets 2. Order (powers n°? ete) 3. Division 4 Muliplication s 6 ‘Addition Subsaction fin doubt use the brackets! z Oaipat Built-in data types All programming languages have built in datatypes that are used when declaring variables (though not all programming languages have variables - dont worry about his yet though!) Some very common datatypes, and the anes you need to know forthe exam, areas follows: Type Description Memory Space st whole number fom 2,147,483 648 though 2,147.483,647 4 bytes Byte a whole positive number fom Oto 255 Lyte eal Vital Basie doesnot use Real Number, instead uses (Single) and {Double}, which both allow for decimal places {Single} [15x10 34x10 bytes {Double} [5.0 103 to 17 109 8 bytes Decimal 7.9228 x 107% 4979228 x 107* 16 byes ‘either TRUE or FALSE Boolean Altermatively Tor 0 Alternatively Yes or No Character |A single characte String | A collection of characters Date/Tim Using these data types we can sar to write simple computer program But wait a second, thi gives you an odd output, it says: Code Outpt told it that Barry was 56.3 years ol ‘The reason is because I have used an integer to store the age and not areal (single or double) datatype, deca al part. Integers, afterall, dnt store decimal places! Assignments Depending on the datatype, we assign values in different ways + Integers, Bytes, Real, ‘There ae several different types of date format that you ean apply. O10 1/0001 to 12/31/9999 and ‘times from 12:00:00 AM (midnight) through 11:59:59 9999999 PM. 4 bytes (1) 2 bytes ‘A unicode string with « maximam length of 2,147.483,647 characters bytes ingles, Doubles = Plain assignment without speech marks Example 37453, 2 (002.375 9997775, 38 TRUE i ‘cabbage osi7is2t 4342: it therefore drops the String, Char = Assignme: with speech marks Age Name Gender Heighi(metres) Date of Birth license (Do they have. Using the correct datatype declare variables for a person's driver license) Answer: [Expand] + Name + Age + Gender Write assignment statements forth owing variables using yourself as an example Answer: nd) [Which of the Following assignments ave comet, which are wrong and why. Answer: [Expand] [Give two reasons why ist important to get the corect datatypes Answer: [Expand] Write code that asks the use to insert three numbers with decimals, then outpts them (1) all maltiplied together, and (2) added together. For example: Answer: (expand) Extension: Strongly and weakly typed languages ‘You don't need to know this part fr the exam, but it should help you understand why we need to convert. We have two types of programming language strongly typed and weakly typed. Stoongly means that you cart add a string toa integer, even ifthe string contains a number. Weakly typed allows you to adda string to an integer ifthe string contains a number ‘Weak Typing Strong Typing Pseudocode | eperteereee, © i ? C+, Python Languages | Visual Basi, Perl, PHP, Rexx Java, Constant defini ions Constants ae like variable in their declarations and the ability to look atthe value stored inside ranning, the value of a constant remains (rather unsurprisingly) constant. 2, however you can not change the values while the program is Example: Declaring pi as a cons Ifyou ty to change a constant vale it will bring up an error. They are very usefil for values thet donot change or rarely change such as VAT pi, e, ee. BY using & constant you dont run the risk thal you might accidentally change the value, you wouldnt want to accidentally change pi to equal 4as All your calculations would go sang! Exercise: Constants Write a program that works out the area and circumference of a circle, seting pi to a constant. Use the equations: area =? and citcumference = 2[lr For example: [ir Neco i oot meee) en ETE Answer [Expand] Write program that works out the cost of two clothing items showing the price, VAT, and price inclusive of VAT. VAT = 17.5% For example Code Output aa ore er eee eee veer rear? ne ped S7eeiees SEAT ESEE Lod Anewer: sxpand) | Why might you want to use a constant in your code instead of « normal variable? Answer: [Expand] ‘When si suitable to se a constant Answer [Expand] Selection An important part of programming is the use of selection, that isthe ability to do something if estan eritera is met. This may be as simple as inreasing your heals bar ina computer game if you eat a chicken drumstick or inserting the cooling rods into the muclear reactor ifthe temperature excceds a certain value, IF Statement The most common selection statement isthe IF statement, the idea is that you compare a value to some criteria, IF the value and criteria match then you proceed ina certain way, otherwise you do something else, For example peat fe the queen Ten Waite a single IF statement forthe following ‘Ask a user for thei eye colour, if they say green call them a "Goblin, else they must be a differen type of monster Lg Cove Ope Pee eet ip coce Onna See ee cs PS ern Answer: [Expand] [gp core Onin etre ns Re ere el Code Output one a neem Using one IF statement write cade to handle the above, HINT: you might need more than one clause inthe IF. THEN section, Answer Expand] Now for some very simple AI [gy Code Ouipa Oe nm me et Have you had some exercise: Yes or Na? No Go for a walk, you might feel b Inall other situa Answer: sxpand) Nested Ifs Sometimes when we are trying to write complex cade we will ned to use @ combination of Is. Inthe example above we might want to still treat an under-age gu with respect, an under-age commoner with contempt, serve an 18+ queen with respect, and serve an [8 commoner with common manners. In fact it seems as if we need 4 different IF statements. We could solve i ie this This seems avsflly cumbersome and we will ow Tock a more elegant way of solving this, using Nested TFs First oF ll, nested means placing one thing inside anothe o place an IF inside another, Try the examples above with the following data, both solutions should provide the same answer : poe 2 ean ee pon “tsetse Exercise: Nested IF statements Wiite nets oF IF semis for the Zllowing Acar canbe hired when a person is over 21 and not itoxcated. Lg Code Output nro Ce ee eared os ene Ieshould also handle [i Nectexe console writeine("How old are you?") eee nce es eee etna) Answer (Expand) Create a login screen todo the following: Ly RN Eee na lease enter Jonay5 they get the username wrong it should immediately kick them out and not ask for the password. IFthey get the password wong it should kick them out Answer: mn: Single line IF statements sxpand) ‘As you shouldbe aware by now a lot of programming is doing things as quickly as possible. You might be fed up with writing ong if statements, having to keep briuing that enter key to make new lines, There isa faster way to code: singe line IF statements cee rites bee") i ongelewwriteline(‘crink cola") i But be careful, code lke tis ean often be harder to read and therefore debug. Onee it has been through the interpreter / compiler it almost certainly won't be running any faster either, it's just there for you to save a litle space. For the exam keep tothe longer version. Case Statement [EASE] i F 1 [ie eno] [Eno] [Eno] [En r END. The other type is the Case statement, ths can be summarised by several istatements where the value is compared to several eiteria and the action of frst erteria matched is performed, otherwise a default action may be performed. However, most programming languages wil give you a shortened way of implementing a case stalement without the need to write all ofthese iPstatements For example In VB.NET we use the select case cask WrtteLin(eteecr 2,2, 3 snluve') role eiteine(Sceger & on op &9 ©) Exercise: Case statements [Create a program where someone types inthe name of an animal and it oufputs the sound the animal makes. The animals t should bangle are Pig Oink. Cow = Moo Bear - Grr Shoop - Baa Tige Gr everything ese - Meow Ty end complete this tsk by only using 5 case statements Answer: [Expand] ‘You are now going to use a ease statement to eeate an electronic piano Note| Frequeney ‘A [220.00 B 246.94 261.83 D 293.66 B 329.68 F 349.23 [39200 Create a case statement in the code below, tha il play the notes written above. The while tue loop means thatthe code will never end and will continue fo ever. For bonus points try and get the code to accept both upper and lowercase inputs Answer [Expand] Iteration An incredibly important part of computing isthe ides of iteration, that is repeating the same thing again and again. You probably use iteration every day. Take writing ines ina detention for example; you write some lines, check lo see ifyou have met the line limit, and ifyou haven you write some more lines, check if you have mel MCeraln cittinecourt & @ Cais iit ic and so on, until you do meet the line limit and then you can stop 1 should always do my programming homework eee ea SEE ea aa eer ers eRe CC es easing the sped of a car while the a pressed down and until you bit its top speed ay NS] gram that counts fom 2 [Expand] \Weitea program that takes an input and outputs the times table for that number eee 1727 ears Perpesl eee) eer oes 787249 eed es ee Answer: [Expand] Wits a program that ad inclusive to [Expand] wate Da hile (A= TRUE) Do 8 End While The while loop’ For example: Code Ouipal Do While Loop 008 End Whi Another type of while loop is @Do-While loop. This i slightly differen frors the While loop in that you pe ask again This means you perform the task whatever the circumstances of the cheek: Si oe op pene Visual Basic handles this with some ereclewrteline(oge 8“ yea olds shu ater schol") This is great for young students Code Output Sorento aaron eter etn etl Code Output eee eee Seen and While Do For the dodgy example above re-write the Do While as a While Do loop Answer xpand] Be careful when you use each loop! For Loop The most complicated tol you may casiest ways 1 trate in Visual Basie Ics far easier to use in vb @ isthe for loop, This is a glorified While loop and don't be put off by how complicated it looks. IL also tends to be one of the Vor leaps also allow you to count Cownwards, Por exampte if You creating a timer that counts dowa to a target. To do this we use the step - 2 code, making the allowing code: display Code Output Exercise: For loops 40 times: Write a for loop to display the words "Iwill eat my green Answer: [Expand] Write code that will input a lower and higher number, then write the numbers on the se higher. Use fr loop, it should display the following -n, starting atthe lower and writing each number until you reach the Code Output aa ecu ete) 10 in Rn rey Answer: xpand] Write a for loop that will output the frequencies: 100,200,300,400, 20000. HINT, you might want o start at 1 and multiply. Remember consote.beep(200, 200) Answer [Expand] Git the computer to keep asking @ user whether they are “Ready to launch”. Ifthey say anything other than "Yes" then keep asking the question. If they say yes, then count down from Sand end with the words "BLAST OFF!” Code Output i Perea eae erent ea OG Extension: Ifyou want to really show that you know how to use ease statements, gt it to say: FIVE, FOUR, THRE! numbers TWO, ONE instead of showing the Answer (Expand) You have met the the main sorts of iteration that you can use, some being more suited for solving certain problems than others “Nae + Do While + For Click here to leatn more Loopy Loops Some times it might bea good idea to combine several loops together Take a look a this example “comolevmriteline(x 8": *} This code uses a loop inside a oop to printout the times tables. All that time y spent learning them at school can be rewritten in sx lines of codel Code Output Exercise: Loopy loops Write for loop inside loop to display a Christmas Tre, like so Code Oulpal Answer (Expand) | Adjust the code above so that the user inputs how high the tree is Answer {Expand Built-in functions You need to be familar with several programming routines that came built iato mos ‘ou lot of effart in writing code to perform common tasks. You might be asked to use ther in the exam so lea them! ymmon programming languages. These routines are very useful and should save Arithmetic functions Youll have tobe Familiar with several Round fhe Found Tunction 1s used to round numbers to 2 limited number of decimal places using the Math. Round() Function: Se traeattis. sat) “eure 15 This is particularly useful when you ae trying to perform DIV in modular arithmetic ‘An essential pat of most games is the ability to use random numbers, These might be used to randomly place gold coins on a map, ot caleulate whether you hit target witha rifle at some distance. ‘andoananber = ren Mere) ‘The above code will give you a random number between 1 and 2, 147,483,647. You might well require a number that is litle smaller To get a random numer ‘between two set numbers, in this case Sand 10 you can us the following: ‘So how exactly can we use this? Take a look a she fllowing game: 2 rans (2,368) {oPlanse isis the randon mabe beaten 5 ad 18") tyr est} feet! Tosletredfiet) cbeale wetelinet oe Hen") Adjust the code above to tll the user how many guesses they took to find the random number. TINT: youll need a variable Answer: [Expand] urd = tach ound, 2) Tee Answers vexpane) Write some code to output the integer part ofa number input by the user Answer: sspand) ‘Write code to output the integer and decimal parts of an input number Code Output 1 eer aes Lea peter [Expand] String handling functions Very popular examination questions involve manipulating strings. These simple functions will help you with this task Length This function is wed to find the length oF any string you pass it, counting all the characters, including the spaces. In visual hasc to find the length ofa string we use the Len("sone sting") funetion that returns the integer length ofthe sting that it has been passed: Code Opal Position This funtion allows us to find the position ofan item within given string and retums the positions location, In visual basic this s performed by the following commend: nstr((string],_[Sten]) For example we might want to find the location ofan end afa sentence by looking for fllstop Code Output We can also his command to search for strings Within stings. For example if we Were to look for to see ifa sentence contained a certain n cose pak Subst o This fuetion allows you to snip items out of a string and return a substring. Visual Hssic uses the following command: [string] Substring({startPosi tion] ‘Weill have to ignore the area code TengthofReturnst=ing)), For example we might want to find the local namber from a landline phone number we have be Concatenation This function allows you to stick stings together (concatenate) so that you can start to build strings using variables, Visual Basic uses the following command: ( onesie atelint foe hve othe mane ote 84) Inthe above eode you can see the various role of variables in collecting together 10 inputs and adding them altogether (gathering) Variable) Rote total |Fxed vale ie _(tper eather input mot recent holder Type Description Examples tos waned [A variable that Keep track ofthe lowes or highest ealulatng the top sore nva Tob cam, the lowes score in an exam and he highest folder [vlueinaset of mputs umber of pied wag als seen by ard watcher ina particular year ‘sed 0 kosp check of previous valve of variable, foower |e Fee heck of previous val Followers ar often uted when sorting vray, in rotines auch as bubble insertion sat [A variable ued for toring someting Tora wey short temporary [Ayame wed fr slrng something 8 ¥) S07 epyary yes ae oe sed for swaping ales tween le variables sed to store the esl of «calculation invlving cransonmarion Ws 9 store te sul transformation veriales ace used to cleulate soc things as compound interest soscnneactant = saree) 1 nscarteaice) Inthe code above you can see the use of the most wanted holder to store the maximum value from an array of numbers. As you eyele through each item in the aay {asing the stepper c), you update the rostwantecholder to store the maximum value that vou come across, Let's take a look at a more complex example en -seeentes) Bjeo'S eatete) nen prev 2 Seorestey Fee tte “The cade shove describes a single pass of bubble sort. Using the temporary variable, ven, we bubble the largest array value tothe tp ofthe array, by comparing the current array valu (scores(c) and the follower prev. In summary \Variable| Role temp [temporary prev follower ale fixed valve © stepper Finally let's look at an example ofa transformation, we bave used lots of loops so far, but variables certainly arent only used in loops: (Deankesanttet insert Ue racks: Sessa hati ‘Cavdle atiteline caren = = 64) ‘Varinble| Role f TRtet ier en } For the above code name the variables that act as Role | Variable ‘uansformation ‘most wanted holder ‘most recent holder igatberer fixed value stepper Answer: [Expand] ‘The roles you see here are included i the syllabus and itis very likely that they willbe examined. There are several other roles out there which aren't covered here, these include: one-way lag + onganizer * container walker ‘You can find out more about them here (hip www es joensuu fsajaivar_rolesindex html) Fundamentals of structured programming You should already have seen how you can use structure tables, structure charts, hierarchy charts and procedures/ancions in breaking down a complex task, This setion wil look at how to write the best formed and mast readsble code we can {F you want tobe a good programmer (and get good marks inthe exam) then you have to make sure that your code is easly read by other people, There are several things you should ty and do when coding USE PFOCEGUPES MAT EXECUTE A SHEIE NaS Fach procedure / Funetion dees a single thing, such as calculate the current health ofa player in a game. This means you can then use them as building blocks to build bigger solutions. Ifyou make your procedutes / functions do too many things at once, then they are very hard to re-use indifferent projects and harder totes, Use procedures/functions with interfaces + Breaks the problem into chunks + You can test each separately + You can reuse code Use sensible variable datatypes Make sure thatthe datatype you use are sensible, You will get marked down for using the wrong datatypes in your database tables and variables. For example: Ifyou are recording the total namber of chocolate bars in a shop you don't need to use a Long or Float, you ean only have whole numbers of chocolate bars and its unlikely youll have over a few milion items, Use an Integer! Meaningful identifier names When you are declaring parts of your program and you return tothe code some time later, you want to be able to understand what cach variable, procedure and function does without having to trace out the code. The easiest way to start doing this is to name them correctly se sensible variable names Ifyou ae using variables to store things they must have a name that makes sense so you know what it does when you read its name in your code For example. ITyou are evording the total numberof chocolate bats in shop you dont want to use & name Tike variablel. What does variable mesn? Use a sensible name such as NumChoe. Use sensible Function/Procedure names IF you ae creating subroutines to process things in your code make sure you give them a sensible name so that people know what they are doing when they see them in he code, For example: Ifyou have writen apiece of code to calculate the average price ofa chocolate bar then don't allt FunctionA(), what does FunetionA() mean?! Cal it Choeaverage() Try to stick to one naming convention Ir you are using lots of variable names and function names, stick to a single style for naming them. Ifyou use los of different conventions things are going to look ualy. Wikipedia guidance For example + frstName, lasName, calelateDoB, numl.egs + FitsiName, LastName, CaleulateDoB, Numlegs + First_Name, Last_Name, Calculate_oB, Num, Don't make your names too long Long variables can be very hard to read and much easier for you to make mistakes when writing them, ty to shorten things where possible For example Too Long Just Right ThislsYourFirstName FirstName the_value_of_a_chocolate_bar|ChoeVal Indent your work A lot of programming environments help to indent your code automatically und you should he able to find one forthe language you ae using, Indenting helps people to read and understand your code quickly as it elerly shows the structure of functions, procedures, selection and iteration statements, For example the following is very hard to read Fay osc Ssrineedann eects eine. as 8 Use comments where necessary Some ofthe bet written code doesnt need comments because if you have siuctured it corzectly and used all the proper naming conventions it shouldbe pretty easy to read. However forthe eode you are writing you should put some comments to explain what each section docs, sti zach ag The advantages of the structured approach + Easy to read and fix code Problems broken down into easy to manage chunss + procedures / functions are reusabe, you can use them in diferent projects + You can test modiles individually Exercise: Structured programming What might be considered wrong about the use ofthe subroutine above? How could it be fixed? Answer: [Expand] List thre reasons for using fictions and procedures to structure your code Answer: Gottesneitetthlloy elette dnsert your age: “> oesriteaaly, daly. Give three structured programming techniques that could be used to improve the code above Answer: (Expand) Modulo arithmetic Modular arithmetic i all about finding the remainder from long division (MOD), and the total numberof times that a number goes into a division (DIV), Lat’ take a look ata quick example of 10 divided by 7 (you might want to remind yourself about long division) Hopefully that wasn' too hard. We now need to introduce some terminology, MOD and DIV: + MOD = finds the remainder from long division ie, 10 MOD 7= 3 + DIV= finds the numberof divides in long division ie. 10 DIV7 Exercise: MOD and DIV Tay these examples, working out the MOD and DIV of each 7/2 Answer: [Expand] 175 Answer: a2 Answer: (Expand ee Answer: UExpand] Now ay these explieit calculations: 11 MOD & Answer: {Expand sMopa (Expand) nsw {Expand [600 DIV 20 Answer: [Expand] Hopefully you are now pretty good with MOD and DIV, but what exactly isthe point of all this? A very common example in past exam paper has been using the MOD ani DIV to work out abiary equivalent ofa denary number Example: Converting Denary to Binary using DIV seitiy seer. ta) top av E Tin taney =) i BERET tne atep et uso shrlan deh osnary Be starting fen he agpet value ‘erstettfbuet) “Try the code out and see if it works. Try to write a trace table and see how it works forthe number 67 (again another papular question in exams): Answer: expand] Another common use i in finding out whether a number is odé or even using the MOD function, We know that MOD returns the remainder from a division sum, So for example 4 MOD 2 ~ 0, § MOD 21,6 MOD 2 ~ 0 and so on. By modding something with 2 we can work out whether it is odd or not due tothe return value are NBEE te me te ne) "Spee mae He) Logical bitwise operators As you have probably discovered already, converting a postive binary number into a negative binary number involves changing bits. As does converting a capital ASCII jeter ito & lowercase ASCIL letter. How exactly does a computer perform ths action? The answer les with bitwise operators: Bitwise Operator] NOT) | ANDi) ORD | XRD 5 Q) Description invert iaput where exactly two Is_ were one or more Is| where exactly one 1 Input p ‘o1cor010 01001010 ‘1007010 ‘1001010 Input Hi 10000 Hr 10000 1110900 Output To110101 [61000000 niio10 rori010 So how can we use these for useful tasks ina computer? If we look closer atthe examples above we can see that seting Input 2 bits wo Is or Os has a direct inpact on the Output, We'l call Input 2 mask, and we apply this mask to change the values in Input I in certain ways, Consider these questions about Masks: ' Ife have an AND mask bit as 0 what isthe output in all cases? + Ife bave an AND mask bit as | what isthe output in all cases? 1 Ife bave an OR mask bit s 0 what isthe ousput in all cases? Ife have an OR mask bit as 1 what isthe ousput in all cases? + Ife ave an XOR mask bit as 0 what is the output in all cases? + Ife bave an XOR mask bit as 1 what is the output in all eases? in summary: AND OR XOR 0 clears the value retains the value seins the value retains the value sets the value invers the value uses setting chosen bits fo O setting chosen bits to | inverting chosen bits, finding differences between bit sts So know we know how each Bitwise Operator works we ean use them with masks to calculate things: Input data 11011011, I want an output with bits 4 and 5 set 100 and I don't care about the others, (77200727) Answer: [Expand] [Input data 11011011, 1 want an output with bits 1 and 8 set to 1 and I dont care about the odhers. (19997701) Answer: [Expand] Input data 11011011, I want an output with bits 34,56 set to 1, bits | and 8 set to O and I dorit care about the others. (07111170) Answer: [expand] coon nee nee NN NN ENLIST Example: Turning a positive binary integer into a negative ‘We ate going to convert the number 37 into -37 ‘Example: Finding a lowercase ASCII letter ‘We are going to find out the how to convert any Upper case ASCII value into is lower ease equivalent, First lets ind out the difference between two letters, well look at'P and and'A’ and’! : exeno00e pease f slonos: er Fen tat at we nae to Sy cit an aa ae, Svar Exercise: Masks For the example above we can also do this by using a XOR, ean you find out how? Answe [Expand] What about converting an upper-case liter into a lower-case leter, try with X (01011000), you cart use AND what can you use? Answer: (Expand) Programming You can program logics bitwise operators to change the case of letters and even enerypt messages. Unfortunately it isn't aways possible to play around with binary digits and you may have to work with decimals instead. Lets take a lool an an example using an AND: pe W904 se 9 OTL ons 8282. IF we MAD the ae ogether we Be Lets check: You can also use ner, xOR, oF and any’ combination of them, Let's look ata slightly more interesting example: Example: Bitwise programming We are going to write a short program to swap the ease ofa sentence that you input, for example, if you typed (Code Ouiput enn as Premera Strteee's easde teslned) i ebay ENE sores upper and Loner case Bitwise programming Exerci Programa bitwise mask that will lip the 2d and Sth binary bits ofeach letter of wn entered sentence 1o convert i into a secret code Answer (Expand) Write code that uses bitwise operators to display whether an input number is a Odd or Even, For example if they input 64 it should output 0 the user inputs 9, the program should output {IF Answer: (Expand) Set operators sets de +410 be familiar with te following terminology + Membership + Union * Dillerence + Inerseetion For the following examples we are going to use two sets, To define a set use the curly brackets {) and place all values of that set inside them bet A: ALL evar naturals up 20 a ineluding 2 = (8 Membership Membership defines what is contained in particular set, it makes claims as to a particular things set membe: writen by ©, The reverse "is NOT an element of is written by @, Let's take a look at some examples: s0cB = 6EAANDSEB "768 "8G U ion When we have sets we oflen want to perform actions on them, for example trying o find all the unique members contained inswa sets. The union(\) of and B, denoted by 4 U B, isthe set ofall things which are members of ether 4 or B. Iv is silat tothe boolean Function OR. The union command allows us to perfor tis action. = 11,2} © (2,34) ={1,2.34 (notice that we don't count 2 twice) © {1,2} U fred, white} =[1, 2 ed, whit = {1,2,g1een} U (red, white, green) =(1,2, red, white, green} = 1,2) 0 .2)= 0,2) Exercise: Union Let us take a look a the two sets we are using as examples: Answer: BA) UB Answer: (Expand) [aU 47.13zed) Answer: BuB Answer: (Expand) Difference pifference() i used to work out the members unigue to one set, members that are not also inthe other set, It is similar tothe NAND. 4) = {p @ Alar ¢ Bp. Meaning lemons tat are members ofA bat not members oB boolean Funct \ Let us look at some exampiest Let us take a look atthe to sets we are using as examples AB Answer: BVA Answer: [Expand] BY (12,357.11) Answer: AN 10.112,3.5,8,13) Answer: (Expand) Intersection We use interseeton(() to find out ll the elements that are members of one set, and also atthe same time members of another se, Its similar tothe boolean function AND. x €.4 91 Bx € 4 ANDx € B. Letus look at some examples: 12,3) 12,3,4) = (2 1,2, 3} {ear her squireel} ~ 0 (this means an empty set) feat, dog, canary} 11 (wolf, canary, whale, eat} = (cat, canary} ANB Exercise: Intersection Let us tke a look atthe two sels we are using as examples: A B= Answer: [expand] [AT teoat6.9) Answer: [Expand] [AT (goat3.9} Answer: =xpand]) BA B5791) Answer: Programming Not every programming language offers the ability to perform set theory calculations out ofthe box using the LINQ libraries that you have to import :o get it working Boeke In Visual Basie it has only been available since VB NET CovaheuriaL int tes of A and 0") cestie rian Geneatesurive Ira(“Di ste ‘cansexearistinte bin intersecean « A ntersect Fundamentals of data representation ‘From the Specification : Binary number system. Pure Binary Representation of Denary Integer + Deseribe the representation of unsigned denary integers in binary. Perform conversion om denary to binary and vice-versa Binary Anthmetic + Ad two binary numbers and multiply two binary numbers Representation of signed integers by Two's Complement + Describe the use of Two's Complement to perform subtraction, Convert a denary integer ino Two's Complement and vie versa “The Concept of Number Bases: enary, Binary and Hexadecimal + Deseribe the conversion of’ denary integer to hexadccimal form and vice versa Describe the use of hexadecimal as shorthand for binary. Integers and Numbers with a Fractional Part + Drawa distinction between integers and numbers with a fractional part in a computer context Describe how an unsigned denary number with a factional pat is represented in fixed-point form in binary. ‘From the Specification : Information Coding Schemes Describe standard coding systems for coding character data + Understand ASCIL + Understand Unicode Differentiate between the character code representation ofa denary digit and its pare binary representation Error checking and correction Parity bits, Hamming code, Gray coding 1 Deseribe Gray coding, Explain why and where itis used. From the Specification : Representing Images, Sound and other data mages DDeseribe how bit puters may represent other forms of date inluding graphics and sound. Bitmapped Graphies + Bitmaps: resolution, cofour depth and simple bitmap file calculations Vector Graphies Vector graphics: drawing list— objects and thei properties. Compare bitmaps to vector graphics, advantages, disadvantages ‘The need for compression und basic techniques for compression Sound files o...4 40... es ‘Sampled Sound and Nyquist-theorem in oni sees + Sampling resolution, sampling rat. Sound Synthesis + Deseribe MIDI and its advantages for storing sound digitally Streaming audio + Expl what itis and why its used, ‘Analogue and Digital Data, Analogue and Digital Signals. + Differentiate berween analogue and digital data and analogue and digital signals. ‘Analogue to Digital Converter + (ADC) Describe the principles of operation ofan analogue to digital converter. Bit patterns in a computer The language that @ computer understands is very simple, so simple zhtit only has 2 different numbers: 1 and 0. This is called Binary. Everything you see on a computer, mages, sourds, games, text, videos, spreadsheets, websiles ele. Whatever iis, i will be stored asa string of ones and zeroes ‘paecaenaena9n9en90n9q9on090090 non on neaaen9enapnonaa9n9onoRo9N0900G0 900000 ‘Sabedaevsauocugcasouaaeogogai 1110422152 11019 a2guoso9oa90R00000000000 000000 ‘Scogcacuseuaeuasusouodaadd + boc nev voduouacueeL 1s uaguncusoaace0du0Unc0 200000 ‘buaedaenoonaocasnarla5sou090090 00 99npouagna6naqn00001 9039000090090 960.00 Sanedactoozacnae aongeno909dp9d 200 pednotaedoonaoz090000% 29500000000 900000 ‘SdbedocuseJaeuL suoodosuacaounou eUvoJuoUacuoousouaGuacu90uz6v0J00UoU00U000 ‘puedo? sapnacnaon9px0009"09000 99uotaeHaonapsoxcooB90R05000190000 90000 ‘SubeuacuLovaeuacuooloauogu0: vou ou vouuougcuocL adUaguacusGua6u0JULURoUR0U000 ‘pueda segoneocacnaon9q9000%1 1 Leach dannotaee 1 Tos0p000090206000000190 960.00 ‘uber iusoueeugcuoouaauogogi4 cou voJuougestsguosuosuaguoouadooU114 000000 ScogcLovteuacuscuoousseacoart 2c cu sducuseuLi1 souacuscuseaaceuboUbL4000000 ‘bupec Lobaona¢cacn9on95900090090 90 99uponaeH9onajs00000090205090090010 900000 ‘Sabet oveguocugaasouasuogo9qn9qae0couuougedaousguoqcoa9au00000000020 00000 ScogcL love aeuacuoouooeacvoun0~ cu soUueuaeus0souacuneL 902000000001 14000000 ‘pueda 9ona¢n9cn90n95900090090 R90 99noTagHaonagnoNoaoD 902050900901 90 9600 Sanedaet senecnsonsongano9nadp9d 00 odnoigedeena9z090000 9000500000 090900000 ‘SubeuaetLodaeuacuoolosaacaoub9ueUvoJuouacusodsouacuacu9oua6v0U0~0DcUR0U000 ‘bupedaetoono: nasnaonapsogaganoL 1112112 1141 pagnogcoop90x05000000000 960.00 ‘Subeuacuseu00L1 cuaododeacaoun9 doUboUbouacuvodsUaGuacu90ue2 0aJ00UoUR0U000 ‘buedgeaene6c9cn9009"Losn9np90a00 d9nnotaenaonaon0011o90005000000000 960000 ‘bubedoovsaueeugauoougada12 Jou eu voJuouvodgous=1 12 Upsu9guagv9d00U000 000000 Scogdacuseuacuscuoouoseaguasd 11 izs1s11121 11 soUoguncuooaaceoUboUBeU 200000 {cao sacoaenoera6n000.00 agape ia acoacooczabna00.00.00200e00E0 Seo «standard unit to measure computer memory, consisting ofa value thats either 1 or 0 Byte -a standard unit to measure computer memory, usually consisting of8 bits. eg 10101011 Exercise: Bit patterns in a Computer How do computers store data? Answer: (What sort of data ean be stored in binary? Answer: [Expand] What does the following binary string represent: 10011100, Answer: [Expand] How many bits in a byte? Answer: How many bits in 7 bytes? Answer: Denary, Binary and Hexadecimal number systems Before we jump ino the world of number systems we'll ced a point of reference, I recommend that you copy the following table that you can refer to throughout this chapter to ebeck your answers, Binary | Denary 0 «00 ° 1 at 1 10 2 3 oot! 3 4 100 | 4 5 out 6 ono 6 7 out 7 8 1000 8 9 roa 9 A wo | 1 B wil 4 c vio] D ot 3 E ino |e F mi Is 10 001 000 | 16 Menary/ecimal Denary i the number system that you have most probably grown up with. Itis also another way of saying base 10."This means that there are 10 different numbers that you can use fr each digit, namely Notice that if we wish to say ten’, we wse two ofthe numbers from the above digits, | and 0 Thousands) Hundreds Tens] Units 103102101, 1040 1000100 1) 5 3 73 Using the above table we can see that each column has a different value assigned to it. And if we know the column values we can know the number, this will be very useful when we start looking t other base systems. Obviously, the number above is. five-thousands, nine-hundveds, seven-tens and three-unit, Binary You should know denary pretty well by your age, but there are different base systems out there, and the most important ane for computing isthe binary base system, Binary isa base-2 number system, this means tha there ae two numbers tha you can write for each digit With these two numbers we should be abe to write (or make an approximation) of ll the numbers tha we could write in denary ‘One-hundred and twenty-cights|Sinty-fours|Thirty-twos| Sixteens Eights Fours| Twos| Units vo 26 DS BM 2S WADA 20 18 a 32 we 8 4 24 0 1 1 o 1 > | o Using the above table we can see that exch column has a value assigned to it that is the power of two (the base number, and if we take those values and the corresponding digits we can work out the value ofthe number: 1464 + 1*32 + 1*8-+ 192 = 106, Ifyou ae asked to work out the value ofa binary number the best place to start is by labelling each column with ts corresponding value and adi columns that hold |, Let's take a look at another example together all the 128|64|32|16)8)4]2/1 0 0 ot ti So now all we need to do isto add the columns containing Is together: 1916 1 1°81 184.1 1921 191 =3) Exercise: Binary Convert the following binary numbers ito denary 00001100, Answer: (Expand) 011001, Answer: [Expand] Ja0000111, ue Jo1o1o101y Answer: [Expand] How do we tll ifa binary number is odd? Answer: (Expand) ‘short cut to working outa binary number that is made of sold anes, such as: 011111113 Answer: {expand I we were to use octal, base § number system, list the diferent numbers each digit could take Answer: [Expand] Max and range A common question that youll need to know the answer to, and on that many people get wrong, is a question about the maximum denary value you can store ina set number oF binary digits, o alternatively, the range of values that you can stoe in a set number oF binary digits, Read carefully, these are not the same thing Consider the following example: IF were to have 5 binary digits, the maximum value that | could store would be 113, this equates to4+2+1=7,y IF were to be asked, the range of numbers then we bave 8 options: We could count these all out and write down: "There are 8 different values 3 binary digits can take", But this isn very clever, what i you wanted to find out the range and maximum values for 34 bits, vou cant be expected to write them al out. We are looking fora rue to save us the Ja and stop us making mistakes, Can you work ou 2 rule i terms of n Maximum denary value ofp binary digits Rule: Maximum denary value= on For example. for 3diis: yn _ 93 _ 7 Assaleulated previously Number of diferent values fr binary digits Rule: Number afvalues= oy 2 Forexample, for 3 digis: yy oa _ gAscaleulted previously __Exercise: Max and range of binary numbers | Give both the maximum value and number of different values forthe following n binary digits [Expand] 8 Answe [Expand] 0 Answer: (Expand) For an address bus with 6 wires, what is the highest address that can be given? How many addresses can accessed? Answer: [Expand] Hexadecimal You may notice fiom the table that one hexadecimal digit ean represent exactly 4 binary bits. Hexadecimal is usefil fo us asa shorthand way of writing binary, and makes il easier to work with long binary numbers Hexadecimal isa bese-16 number system which means we will have 16 different numbers to represent our digits. The only problem being that we run out of numbers ser 8, and knowing that 10 is counted as two digits we need to use letters iste We can do exacly the same thing as we did for denary and binary, and write out our lable, 16°S_ | 16°4 16°3|1672]16°1 1670 1048 576 65536 4096 256 | 16 I o Cea So now all we need todo isto add the columns containing values together, bu rnber that A= 10, MODE AI56 © ODIENE + (SH ~ DA, You might be wondering why we would want to use hexadecimal when we have binary and denary, and when computer store and calculate everything in binary, The answer is that it is enirely for human ease. Consider the following example Representation Base EFFEIL base-I6 hexadecimal ITsi45 base-10 denary 1110111711111 11000010001 base-2 binary All the numbers are the same and the easiest version to rememberlunderstand for humans isthe base-I6, Hexadecimal is used in computers for representing numbers for human consumption, having uses for things such as memory addresses and error codes NOTE: Hexadecimal s used as ts shorthand for binary and easier for people to remember. It DOES NOT take up lest space in computer memary, only on paper or in your head! Computers sill have to store everything as binary whatever it appears as on the to make i air for as to remember sin ecord her Exercise: Hexadecimal Convert the following Hex numbers into decimalldenary. rr Answe [Expand] Answer: [Expand] lop Answer: (Expand) 37 Answe [Expand] ]Why would we use dhe Hexadecimal system? Answer "Name a use ofthe hexadecimal system Answe [Expand] Converting Between Bases The sum that you saw previously to convert fiom hex to denary seemed a litle cumbersome and in the exam you wouldnt want to make any etors, we therefore have to find an easier way to make the conversion, Since binary bts are represented by one hexadecimal digit, itis simple to convert between the two. You cx up binary bits into groups of 4, starting from the right, an ang extra so the ei equ and then cnve cach group to thet hexadecimal eqvelen For example, the inary mabe 01101100111 10103 ean be vite ike is psa te 101 So the binary number 01101 10011110101 is 6CFS ia hexadecimal. We can check this by ready know how to do this: First well convert the binary number, saree | 16384 | #192 By multiplying the columns and then adding the results, the answer is 27893 Notice that the column headings are all 2 raised toa power, column headings that are powers withthe base 16, lke this since you and soon, To convert from hexadecimal to denary, we must use Sx 1l=5 15 x 16 — 249(VOH should memorize the values A-F) 12 x 256 = 3072 6 x 4096 = 24576 Totaling them all up gives us 27893, showing that 01101100111 10101 is equal to 6CFS. To conver fiom denary to hexadecimal, its recommended to just convert the number to binary frst, and then use te simple method above to convert from binary to hexadecimal In summary, ta conven from ane number to another we can use te following rule: Hexadecimal <> Binary <-> Denary (Hexadecimal SF) x 0101 | 1111 o1oniiit Exercise: Hexadecimal and Base Conversion Convert the following Hexadecimal values into Denary 126 Answer: [Expand] ASy6 Answer: [Expand] 6 Answer: {Expand Wie Answer: (Expand) Convert the following Binary numbers into hex. 101011013 Answer: (Expand) Hotty Answer: [Expand] woot, Answer: (Expand) 11010100001, Answer: Convert the following decimal numbers into hex [Expand] 1240 [Expand] 1% Answer: [Expand] Why might you use Hexadecimal? Answer: [expand] Give two uses of hexadecimal? Answer: (xpand) Binary arithmet You should be comfortable with adding, subtracting and multiplying in d imal, Computers need todo the same in binary, and you need 10 know it fr the exam! Addition Lets look at an example of adding in decimal: This is pretty simple, we just add up each column, but what happens if we have can't it che result in one column. Well have to use a cary bit inary with a very quick example, with a check in denary’ Gai os ae ONESIES FO EI NOLS IIS How cary bis we SATS, dition Exercise: Binary Addition 1010+ 0001 Answer: (Expand) }o1001001 + 90110000, [Expand] Answer: }o1010100 + 00110000, Answer: 01001010 + 00011011 Answer: (Expand 01111101 + 00011001 Answer: [Expand] 00011111 + 0011111 Answer 10101010 + 01110000 Answer: at primary school Lets recap Multiplic OO 28 IEE torn deary 20 82 Lets try a more complicated example Psat (2) on bY TDiesuble crac eth the dectna seater] Exercise: Binary Multiplication wit 10 Answer: [Expand] neu Answer: Wot 101 Answer: and] nian Answer: [Expand] If you multiply @ binary sumber by 2, how many spaces does it move tothe le?” Answer: (Expand) I'you multiply @ binary number by 16, how many spaces does it mave tothe let? Answer: [Expand] Extension: Bit Shifts tons ofthe flowing numbers you may notice something peculiar: [Each time we shift the sumer one space to the lef, the value ofthe number doubles. Ths Joes only work for one bit, take a look a this more complicated example ‘Again, one sill othe lel andthe number has doubled, On the other hand, one shif tothe right halves the value. ‘Computers are notoriously bad at doing multiplication and division, it takes ots of CPU time and can really slow your cade down, To try and get past this problem ‘computes ean shift the values in registers and as long as multiplication or division is by powers of 2, then the CPU time is reduced asthe ation takes only one line ‘of Machine Code. There are several types of shifls that processors ean perform + Logical Shift Shifting ether Ie or right, you add a 0 on the empty end, rotating left logically rotating ight logically Arithmetic Shift ‘You maintain te sign bit ofthe number being shifted. Please note the Lo complement shift example is also an example ofan arithmetic shif as the sign remains the same. Youll find out about sign bts when learning about swo's + Circular Shift ‘The it tha is pushed off one end appears onthe ther Circular rotation le Circular eotation right Binary fractions Binary Fractions So far we have only looked at whole numbers (integers), we need to understand how computers represent You should have leaned at Primary School ow a decimal fraction works: w|4 rf. 10_| 700 11011 10° 10-1110? | Vie ti? te} As you can see, the column headings have been extended to q—1 _ 1 and y q-2 _ _1 . We can do the same thing in binary with the column headings 51 _ 1 107 ==" 107? = =< 0° = i009 a 2 __ and soon. The number 12.75 in bit binary with 4 bts aRer the binary point is therefore 8 +4 +0.5-+0.25 a sfal2faf} fafa 2 4 at} o°} | ato? fa o rfid Notice that forthe same numberof bits ater the point, the binary fraction provides less accuracy. have 100 different values with two digts. Youll see in a moment how this can cause trouble Example: converting decimal {o binary decimal ‘We are going to convert the number 6,125 into binary fraction by using the grid below sfafata] [tfaya} a 214/18) 16 ofr fifo] fofo]s fo 442401 ‘This seems simple enough as 6.125 but what about this more interesting number: 64 alaf2}a] Jl} tia) a 21418116 ofififo].jofi}ajo [But this doesnt look righ?! This number set correct ait only reaches 4 +2 + 0.25 + 0.125 = 6.375, we need more bits forthe binary faction places. However, a ‘computer might restrict you tothe numberof bits you can use, o well use the number closest tothe one we were aiming. for. You could feel abit annoyed at this, but, deuit worry, you rake his compromise everytime yu try to represent with he deine tions, 033333333, a So you might ask how a computer does complicated mathematics iit struggles so hard with fractions. The answers we have looked at so far have only used one byte, computers can ust far more space than this. They ean also manipulate the number of bis they have been given in two ways: 1 increase the numberof bils to inerease range of number * increase numberof bits after the decimal point to merease accuracy In practice they will also use clever techniques such as floating point numbers that you will meetin A2, Exercise: converting from denary to binary fractions Now sry some questions yourself and see how you get on. Remember, where there areit enough bits for the decimal place, write down the number clases to your target number. In each case use & bits forthe binsey with four bts after the decimal poi ns Answer: (Expand) 4.5625 Answer: {expand 33333333, Answer: (Expand) Try and convert these binary fractions into denary 011.0100 Answe! [Expand] 011.1001 Answer: (Expand) I want to increase the range of numbers stored in a fixed point binary number, wat should I do? Answer: [Expand] IFT want to increase the accuracy of numbers stored ina fixed point binary number, what should I do? Answer: Two's complement Nearly all computers work purely in binary. That means that they only use ones and zeros, and there's no - or + symbol thatthe computer can use. The computer must represent negative numbers ina different way, We can represent a negative number in binary by making the most significant bit(MSB) a sign bit calumi headings Foran 8 bit mimbe will look like this ‘which will ell us whether the number is positive or negative. The ams |o¢|az]is}afaf2] a MSE. LSB Here, the most significant bit is negative, andthe ot because (-128+32+16+8+4+1 ~-67) «bits ate postive. You tart with -128, and ad the other bits as normal, The example above ts -67 in denary Lin binary is 111111 Note that you only use the most significant bit as a sign bit ifthe number is specified assigned. Ifthe number is unsigned, then the msb is positive regardless of whether Lis a one oF not Signed binary numbers [the MSB is 0 then the number is positive, i | then the number is negative. ‘Method: Converting a Negative Denary Number into Binary Twos Complement Lets say you want to convert -38 into Binary Twos Complement First, find the binary equivalent of 35 (the postive version) IIE EE EEE EE EE I IE IEE SIE if i's 0, make ita 1; ifitsa 1, make ita0 Converting Negative Numbers To find out the value ofa twos complement number we must frst make note of its sign bit (he most significant, left most bid) ithe bit isa zer0 we wark out the number as usual, ifs a one we are dealing witha negative number and need to find out its value ‘To find the value ofthe negative number we must find and keep the right most | and al its ois right and then flip everything to its le Here i an example Joss anu cote she outer 2 negative oss amis cand oe one ost one Jan ms foe ote 9 ‘We can now work aut the value ofthis new number wich is ‘To find the value ofthe negative number we must take the MSB and apply a negative value toi. Then we can add all the heading values together How about a more complex example? Joss ue rote the rater 2 neste ] oss tage cand th ote ost one Kass ana ‘To find the value ofthe negative number we must take the MST and apply a negative value toi Then we can add all the heading values together his, that's how “Method 1: converting twos complement to binary So we knaw how to work out the valus ofa negative number that has heen given tous, How do we go ahout workin 1g out the negative version of a positive mumber? Like Take the binary version of the postive number joo an 3) ‘Method 2: converting twos complement to binary Take the binary version of the positive number starting with -128, we know the MSB is worth -128. We need to work back fiom this: Exercise: two's complement numbers Convert the following two's complement numbers into denary: Answer: min Answer: (Expand) Jorn 1101 Answer: nd] 1001 1001 Answer: (Expand) 011 1000 81 (hexadecimal) Answer: A8 (hexadecimal) Answer: [Expand] [Convert the following numbers into negative numbers written in binary Answer: }a110 0000 Answer: oman Answer: {Expand 12 (denery) Answer: spand) [67 (denary) Answer Expand] Ey Answer (Expand) 34 (hexadecimal) Answer: UExpand} TE (hexadecimal) Answer: [Expand] Binary Subtraction Exampl binary subtraction ‘When it comes to subiacting one number ftom another in binary things ean get very messy (G3 Sear} Ss 20 = fuce me Gos onto cusp ais tne oite co ste Now ty the sum again ‘Which comes out as Exercise: Binary subtraction Find the answers to the following sums in binary, show your working ‘ue 0 (18) Answer: (Expand) Answer: Answer: [Expand] bs (nnd a hen fon wo 120) Answer: [Expand] Status register Maths ina processor is normally performed using set numbers of bts. For example where you add 8 bits to 8 bts. This will often cause no problems ata serie! oxy This may appear to have gone ok, but we have a problem. IF we ate dealing with twos complement numbers the answer fiom adding two positive numbers together is negative! As you can see inthe sum above, we have added two negative numbers together and the result isa positive number. To deal withthe situations mentioned above we use the status register ‘Status Register - information about process states such as whether a result is er0, posiive/negative or resulted in overflow: The most common flags Flag, Name Deseription Z_Zevoilag “Indiates that de result of an arithmetic or logieal operation (or, sometimes, a load) was 220. Enables numbers larger than a single word (inthe examples shove 4 or 8 bts) tobe aded/subracted by © (Carry flag carrying a binary digit from ales significant word tothe least significant bit of a more significant word as needed (One indicates whether the result was negative whereas te other indicates whether a subtraction or addition has taken place “Indiates that the signed result of an operation is too large to fit in the register width using twos ‘complement representation Parity ag Indicates whether the number oF set bits oF the lst result is odd or even SIN Sign lag / Negative fag © Overflow flag FFor the sum that we met earlier we will ake afook at how the staus register an be used to stop the incoreet answer arising Fagsees (a) L prone 9) iene on Status register: Z = False |C= alse [N= True] 0 = True [P= Even Using these lags you can see that the result is negative, ifthe original sum used only positive values, then we know we have an error Looking a the other equation: aw (0) Status register: 2 = False | Using these flags you ean see that the result is postive when the original used two negative numbers. We can also see that overflow oscurred Exercise: Status register What is the problem with the result ofthe following 4 bit sum! Answer: [Expand] In the context of calculations what is overflow? Answer: [Expand] What do we need the status egister for? Answer: (Expand) [Name three flags ina status register: Answer: [Expand] ‘Show the Status register forte following sum Information coding schemes So far we have sen he differen ways that binary can be used to store numbers. As we already know, most computers can only understand binary and we oflen need to sore alpha-numeric text (numbers, eters and other characters). To do ths a computer will use a coding scheme. The most popular coding schemes are ASCII and Unicode, Youll need to know haw each works and the benefits and drawbacks of using them, ASCIL The 10+key PC US English QWERTY keyboard layout evolved ‘im the star typewriter Keyboard, wth exe keys fr compating ASCH normally uses 8 bits (1 byte to store each character, However, the 8th bi This gives ASCII the ability to store a total of i used as acheck digit, meaning that only 7 bits are available to store each character, a*T = 328 different values. uibered fom 32 to 126 (ema) ASCII values can take many forms: + Numbers + Letters (cpitals and lower case ate separate) Punctuation (?/NE8 ete) + nor printing eommans (ener, eseape, F) Take a look at your keyboard and see low maay different Keys you have, The number should be 104 fora windows keyboard, or 101 For raitional keyboard. Wit the sift funtion Valus (a, A; b, B ele) and recognising that some keys have repeated functionality (two shit keys, the nur pad), We roughly have 128 fuctions that a keyboard can perform Binary [Dec[lex[Abbr] [Binary [Dec[Hex|GWyph] [Binary [Dec[Hiex|Giph] [ Binary [Dec|lex]Giyph ‘ao .aoe| 0 [00 NUT. 0100000) 32 [30/7 | Tao ca0a| ss |40| @ | (11000) 96 coocoot| 1/01 [SoH oloooot|35 |21/ 1 | too000i| «5/41 |_| [1100001 97/61 ‘aoco10| 2 [02 |/STX) ol0o010|34 |22/ "| eowoi0|@ /42| B | (11000098) @| ‘qa woii) 3/03 [ETX| [oi0ooit|35 [23/# | |lwowil| 67 /4a|¢ | [niowoii| w/e |e eooie| 4 [04 [ror clool0|36|28/ $ | IeooI00| es 44D | [1100100 100| 6a ‘aoo101| 5 [0s ENO) [olvo1o1|37 a5] % | |To00101/6 [4s | E | [niooIei[101) 65 | « cooorto| 6 [06 |ACK) otooti0|38|26 | & | ooutt0| 70/46 | | [rig0it0)102) 66 coooit| 7/07 BEL oloowit|39 27+ | oor} 71/47/ G| [noon 103/67 ‘ao 000) # [08 | BS 0101000) 40 |38| (| 100 1000) 72 | 48 | | (1101000 104) 68 | Go 1001) 9 | 09 HT] [o101001| 41/29) | (01001) 3/49) 1) 0 N001 10s) 69 |i {oo1010) 10 |6A | LF [ol0i010|42/aA/ + | Teo 1010) 74 |4A| J 107010|106| 6A coo 10/11 /OR VT) oli 43 [aR + | too to1i]75 4B) K | [1107011 107| 68k oo 100/12 /eC FF (ol01100| 44/26), | 1001100) 76 4 L1101100|108) 6c 1 coo 1101, 13/6 CR) olLior| 45 aD | Te TI0:| 77 4D |M_) [T101101 109) 6D) _m (G0 1110) GB | $0) 010110) 48 1001110) 78/4) N | (1101110 110) 6E | coon 15 /OF | st olouu|4r|aF/ 7) oouni|79/4F| 0 | (nomi) «Fo {1 coo0| 16 [10 /PLE) [o1¥ 0000/48 [30/0 | Hor e000] ao | 50] P| (1110000172) 70 p corcoot) 17/11 pct) [ottooot| 4931/1 | Torocot/st si iLeooi/113/ 71g ‘oroo10| 18 | 12 [pc2) [otioo10| so 32/2 | ToLoo10/ m2 /s2/_-R | (TiLoow0|ri4| 7a ‘oroo1t/ 19 [18 pcs) [otsoort|st 33/3 | voroo/s [sa|_s | lneou|ns| 7s coro100) 20/14 pc#| (olto1o0|s2 34/4 | Torolo/s¢| 54 T | ivolco|ti6| 4: oLolot|21 [15 [NAK) olto1o1|s3 [as/ 5 | floveiviles|ss| uv) [iooijim7)75/ coro1to| 22 [16 SYN) olto1io|sé [36/6 | iovoiiols6| 56 _V_ | [1ino0/is) 76 | coor) 23 [17 ers) olor ss [37/7 | tovoni|e7/s7)wW | (mio ns) a7) w 011000) 24 [18 (CAN) 6111000) 56 [38/8 | 101 1000| 8 | 58 |x | [1111000 120) 78x cor 1001/25/19 FM) oir toot|s?|39/ 9 rol rooi| 89/59 Y) [1it001 12) 79) or to10) 26 [1A SUB) [ott 1010) sé ToL1010/ 90s) Z | Nit Wo10/122|7A 2 001 1011) 27, ESC) (0111011) 59 101 1011) 9 t ALE 1011) 123 t or tio0/ 28 |1C | FS oltt100|60/3¢/< | Tor 1100/2 /s¢ | \ ii ti0o|r2e 70 | (001 1101) 29, Gs O11 1101) 61 = TOL 1101) 93 1 TE 1101) 125 d cortiio)30 |B RS oiTtti0/@ [3B > tor ttio[9# se) >) [iitiit0 6) 7 ~ corti) 31 [iF |-us otrniit|6s ae)? | ‘oranit|95 [se 1) 127] 9F [DEL {you look carefll tthe ASCII representation of each character vou might notice some patterns, For example Auanary | mee See eye 110.0001 97 61a 110 0010 9862 100011 99 63 © 99. This means that if we ate told what value a characteris we can casily work out the value of subsequent or prior characters As you can see, a Without looking atthe ASCTI table above! If we are told thatthe ASCII value forthe character'S' is 011 0101, what isthe ASCII value for’ ‘We know that's three characters afters as §,,7,8. This means that the ASCII value of 8' willbe three bigger than that for‘ (Checking above this is the correct value. Ifyou are worried about making mistakes with binary addition, you can deal with the decimal numbers instead, Take the example where you are given the ASCH value of, 110 0111, what s'e” ‘We know that’ is two characters before, ase, £8 This means thatthe ASCH value of'e' willbe two smaller than that for‘ Without using the er table (you wont get i inthe exam!) answer the following questions: [The ASCH code forthe letter: is 90(base10), what is the letter 'X’stored as Answer: Expand] How many ASCH ‘characters! does the following piece of text use haste rete, psc reas Answer: For the Latin alphabet ASCII is generally fine, but what i'you wanted to write something in Mandarin, or Hindi? We need another coding scherse! ‘You might have to use ASCII codes when reading from text files. To see what each ASCII code means we can use the folivng function Chel(x) which returns the ASCII code with denary value x. Try out the following code to see the fist 128 characters. Whal is special about character 10? cpnetesriteine( ASC for" ck onsale entire) a cst) Unicode The problem with ASCII is that it ony allows you to representa small numberof characters (~128 or 256 for Extended ASCID). Ths might be OK if you ae living in an English speaking county, but what happens if you ive n a country that uses a diferent character set? For example: Japanese characters iF + Cyne Kupiouna + Gujarati rae + Ueda 33 You can see that we quickly un into trouble as ASCII cant possibly store these hundreds of thousands of extra characters in just 7 bits, What we use instead is unieode There ate several versions of unicode, each with using a different numberof bis to store data Name! Descriptions UTE sbi is the most common unicode format, Characters ean take as litle as S-bits, maximizing 8 [encoding expanding to 16, 4, 32, 40 or 48 bits when dealing with large sets of characters UTP | it, variable win encoding can expand 3 its Orr UT 5, gdh encang Hah crater takes xl 32-is With over a million possible characters we should be able ta store every character from every language on the plant, take a lok at these exam code point|glyph* character, [UTF-16 code units (hex) Us007A 2 LATINSMALL LETTER Z OTA Us6c34 (CJK UNIFIED IDEOGRAPH-6C34 (water) 6C34 U+10000 |) LINEAR B SYLLABLE B008 A ‘D800, DCO UNDIE|g MUSICAL SYMBOL G CLEF D834, DDIE You can find ou more about unicode encoding on Wikipedia Exercise: ASCII and Unicode sompatibilty with ASCH, But it alo allows for variable-width | Without using the crib table (you won't get itn the exam!) answer the following questions [Expand] The ASCII code for the letter's is 111 0011, what is the letter'm’ stored as Answe [Expand] Give a benefit of using ASCH: Answer: (Expand) Give a benefit of using unicode over AS Answer: [Expand] How many different characters can 7-bit ASCII represent? Answer: (Expand) You are designing a computer system for use worldwide, what character encoding scheme should you use and why” Answer: [Expand] Error checking and correction them got cotrupted” Think of tis situation: You are buying a new game from an online retailer an put £40 into the payment box. You click: the number 40 s sent to your bank stored in a byte: 00101000. Now imagine ifthe second mos significant bit gol corrupted on its way to the bank, and the bank received the following 01101000, You'd be paying £104 for that game! Ercor Checking and Correction stops things lke this happening, There are many ways to detect and correet corrupted data, we are going to learn to. Parity bits Sometime when you see ASCH code it only appears to have 7 bits Surly thy’ should be using a byte to represent a charecter, after al that would mean they could represent more characters than the measly 128 they can curently store (Note there is extended ASCII that uses te Sth bil as well but we don't need to cover that here), The eigth bt is used as a parity bit co detect thatthe data you have been sents corect It wil not beable to tll you which digit is wrong, so it int corrective Thece ate two types of parity odd and even need it you think back to primary school you would have learnt about odd and even numbers, hold that thought, we are going to Odd numbers 1.3.5.7) 1 Even numbers :6,24,6,8 (note 0 is here too) Example: How to detect errors using parity bits ‘When we send binary data we need to count the numberof Is that are present in it For example sending the ASCII character"! 1000010. Ths has two occurrences ‘of 1. We can then apply another bit tothe font of it and send it across the internet, + Ife are using even parity 91000010, + Ife are using odd parity 11000010 [Now when the data gets to the other end and we were using even parity + 01001010 - odd party, there has been an err in tearsmission, ask for data to be sent again + 01000010 - even party, the data has been sent correctly Exercise: Test your knowledge of parity bits /Tzy and apply the corret parity bit tothe following: 1011010 (even party) Answer: 1011010 (odd parity) Answer (Expand) 111110 (even parity) Answer: [Expand] 0000000 (od parity) Answer: (expand) However, if we receive 10010110, knowing thatthe number had odd parity, where isthe error? The best we can dois ask forthe dae to be resent and hope its correct next time, Parity bits only provide detective error. We need something that detects and cores, Hamming code Building on what you have learn about parity bts we are now going to see a system that not only allows you to detect ifthe data you have been sent i incorrect, but it wil allow you to correet the error. The way hamming code does ths isto use multiple check digits in the same pice of sent data Checking if correct ‘Number the column headings 2. Highlight the column headings that are powers of 2 (1,2,4,8), these ate the parity bts 4. Work your way through the patity bits 1. 2°0=1 check 1, skip 1, check 1, skip I. write down whether i's odd or even parity 2. 21=2- check? skip2, check 2, skip 2. write down whether it's odd or even paity 5. 292-4 check 4 skip 4, check 4, skip 4. write down whether if odd ot even paity 4 ee Let's take afook a an example of data sent with odd parity 11/10] 09] 08/07/06] 05|04{03|02|01| number the columns and highlight the powers of 1000 0 0 G1 1 1 |L [insert your datz 10 (0 0 (0 0 0 11 11 1 [highligh the check bts 1/0) 0) 0 | 1 | 1 taking the Ist power of 2°0 (1) check I skip |= odd parity ro oo 1/1 | taking the 2nd power of 2°1 (2) check 2 skip oooL taking the td power of 2°2 (4) check 4 skip 4 100 ‘aking the 4th power of 2°3 (8) check & skip & = odd parity 8 we tan out of digits, not to worry take is faras the bits given allow. As we ean see each line i odd parity, and the sent dat was supposed to be odd pail, this umber is correct. Now sry this example with even parity toot 100011 Answer: expand] 11011110010 being sent with odd parity Answer: [Expand] 100100011110 being sent with even parity Answer: [Expand] Detecting and correcting errors 1. Number the column headings 2. Highlight the column headings that are powers of (,2,4,8), these ate the parity bits 3. Inset your data and highlight the parity bis 4 Work your way through the parity bits 1 check 1, skip 1, check I, skip 1. write down whether it's odd or even parity ‘heck 2 kip 2, check 2, skip 2... write down whether i's odd or even parity check 4, skip 4, check 4, skip 4 write down whether i's odd or even parity 5. If there isa disparity between rows, bighlight all the ex data an find where it overlaps Let's ake a look a an example of data sent with even parity e—_e_— re cacti. satchel 100 1 0 01 @ 1 1/1 [insert your data tools o 1 [1 [highligh the check bits 1 1 L ©) 0) 1) A | (taking the Ist power of 20 (1) check I skip I= even parity e oo 1 ‘taking the nd power of 21 2) check 2 skip 2= odd parity PROBLEM ‘taking the 3rd power of 2°2 (4) check 4 skip 4= odd parity PROBLEM! roo. ‘aking the 4th power of 2°3 (8) check 8 skip 8 = even parity Note that two of the lines, 21 and 2°2, show that an error has been detected, This means that somewhere tha these lines cross over abit has been corrupted, namely bit 6 or bit 7. If we know wich one itis we can then switch it and correct the error, Look at the other checks that are in play, do any of them take part inthis crossover? Looking at it, the 2°0 lie also checks column 7 and it found it fine, So we are left with columa 6 being the problematic one, As Haruming code is corrective, le’ fp that column and we should have a correct pieee of data Another way of finding errors isto add the check digit values together, the errr occurs where the check digit equls 4 and 2. Add 4 +26, the eror is withthe 6th igi! 11/10] 09] 08/07/06] 05|04|03|02|01| number the columas and highlight the powers of 2 100 1 0 1 1 0 1 1 [insert your date 10 (0 1 0 1 1 O 1 (L/L [higitiohe the check bits TO 0 111d taking the Ist power of 2% (1) check I skip I = even parity 10 on TL | _taking the 2nd power of 21 2) check 2 skip 2= even paity io ‘taking the rd power of 22 (4) check 4 skip 4= even parity ‘taking the 4th power of 2°3 (8) check 8 skip 8 = even parity “The number is now even parity and correct: 10010110111 Exercise: Detect and Correct the error in the following Hammed Code [Now ty this example with even parity lototoo1011 Answer: (Expand) 11111101000 sent with odd parity Answei (Expand) [00111000101 seat with even parity Applying hamming code ‘Number the colum headings Highlight the column headings that are powers of (1.2.48), these are the parity bits Insert your data into the bits that areit party bits Work your way through the party its 1, looking at2°0 "check I, skip 1, check 1, skip 1. write the party bit in coluran I to make the bits the desired parity 2 looking at 2°1 check 2, skip 2, check 2, skip 2. write the parity bitin column 2 to make the bits the desired parity 5. looking at 2°2 check #, skip 4, check 4 skip 4. wrte the parity bit in coluza 4 to make the bits the desited pavity 4 Example: Applying Hamming code to an ASCII character We are going to take a look at sending the ASCII letter €: 1100101 with odd parity ‘This data would then be ready to send eye eee ele ae Oe eee 1/0 2 011 0 2 [1 2 2 inser your data in columns that arent parity bits ir] ol wl ol ht taking the Ist power of 20 (1) check I skip I then work out the digit that is needed to go into the parity btw apply odd party hh oh 1 taking the 2nd power of 21 2) check 2 skip 2 then work out the digit that needed to go into te parity bit to apply odd pasty ?= 1 oll bk ‘taking the 3ed power of 2°2 (1) check 4 skip 4, then work oot the digit that is needed to go into the parity bit to apply odd E party ?=0 hile ‘aking the 4th power of 273 (8) check & skip 8, then work out the digit that is needed to go into the parity bi wo apply odd parity ?= 1 ‘We have now worked out the odd party Hammed number realy for sending: 1101010011 Exercis Applying Hamming code to an ASCII character ‘Apply even parity hamming cade so we can transmit the ASCI character 'D' (1000100): Answer: (Expand) Apply even party hamming code so we can transmit the ASC character'G Apply oda parity hamming code so we can transmit the denary value 9 Answe [2xpand] Gray coding Changing binary number from one vast another can involve changing sveral is at once. For example hanging fom 7 8, 0111 to 1000 anvolves 4 digits changing, but why is this an issue? As vou know, computers are very fast and sometimes multiple things happen at once, especially ifyou are dealing with realtime systems. If program ‘A’ wanted to read a number stored by program 'B!, and read the number mid way through that number changing, program 'A' might ead a midstate, an incorrect number. Taking the simple example above, imagine if we were dealing with money where program B was working out the intrest on your eccount, increasing your money from £7 to £8. Program A might be a cash machine telling you how much money you had in your account. IFyu Took atthe program above you see that the eash machine would ell you that you had £13, so you take out £13 and then become immediately overdrawn, (Bank databases actually use locking to solve tis, bu the example is & good one) This could be particularly catastrophic if his errr occurred inthe military. Can you imagine an anti-ai battery (Program A) deciding where to fire its missiles, and d 1 reading the direction of enemy planes stored on a remote radar system (Program B), shooting the missile inthe wrong direction and shooting down an allied plane! What is needed is Gray Code, a number system that changes one bit ata time to avoid midstates. Take look at the examples below and see how only one bit changes for subsequent number ee eee —— Rotary encode essing deviees masked in 3-it binary reflected Gray code (BRGC) Roiny encode angfemessring ovis marked in 3-bt inary Usually in the exam you wouldnt be asked to convert enything more that 3 or 4 bits. But in ease you do here is an easy method for converting binary to gray code Take the fist bit a it is 2. For the next bt, add the previous bt to the eurent bit 3 Ifyou have scarry ignore it, Eg, I+1=10, Take its O rather than 10, 4 Repeat forthe rest of the bit, 4 Converting Binary to gray Explain how Gray Code works Answer: (Expand) Explain why we might want to use Gray Code Answe [Expand] | Compiete the following sequence of Gray Code stats: Answer: Images A large part of using modem computers involves sending pictures and films to each other, along with using a graphical wer interface. All of this involves computers saving and processing images. Ths section will cover the wo main image types: veetar and bitmap, along with some compression te ‘Tx Magnification a Veco a wice aa \ Bima ais and bitmap repesemttion of an imsge Bitmaps Overview sphics- a collection of pixels from an image mapped to specific memory locations holding their binary colour value Pixel - the smallest possible addresseble area defined by a solid colour, represented as binary. in an image le hows an Bitmap image wih a potion relly enlarged, in which the individual pixels are rendered as ite squares aad can easly be sen Try looking closely at your ‘monitor or motile phone sersen lo ee yo san ap the pels photographs Resolution Image Resolution - how many pixels an image contains per inch’em ‘Screen Resolution - the number of pixels per row by the number of pixels per column manbers of pve Example Example: Calculating sereen resolutions Using the diagram above we are going to work out how many pixels are required to display a single fame on a VGA screen (Checking the resolution: Questions Exercise: Calculating sereen resolutions What isa Pixel? Answer (Expand) What is Image Resolution? Answer: nd] Wht is Sen Answer: What is the resolution of «100 pixel by 70 pixel image? Answer: (Expand) ‘What is the resolution ofa 30 pixel by 40 pixel image? Answer: expand] What is the resolution of 11D 1080p image? (use the diagram above to help) Answer: fT have an image resolution of 700 pixels, and width of the image? Answer: [Expand] Whats a benefit of having a higher resolution image? Answer: [Expand] What might be draw back of having a very high ution image Answer: (Expand) Colour Depth Colour depth - The number of bts used to represent the colour ofa singe pixel ee oe oe ae ~ | a Fa Description | Mono-chrome, only stores black and white RGB(70 61,55), RGB(79, 146,85) Stores limited colours RGB(I29,111,134), RGB(149, 146,166) ‘Number of colours per pixel = Pad 2 = 16 Colour depth Sit 24 bit Example a Number of colours per pixel 28 = 256. 2 = 16777216 I: seems prety obvious thatthe higher the colour depth, the closer the picture will look to reality. Why then dont we just ramp up the colour depth on every image that we make? The answer should be obvious, fora fied resolution, the higher the eolour depth, the larger the ile size Example Example: Caleulating file size for different colour depths Al the images above are of the same resolution: Deerae «ers pines [the first image uses 1 bit to store the colour fr each pixel, then the image size would be: hse of Piels* colour open = ngs Sire See the rest ofthe calculations: For the third image using 4 bits to store the colour foreach pixel, then the image si aver of els ale orth =e se er of ints = colo: opth = i ner of ets color oepth = tage sire “ Windows 98 > Windows ME > Windows XP -> Windows Vista > Windows 7-> Windows 8 Windows 8.1 > Windows 1 + FIFA Intemational Soccer > FIFA Soccer 95 > FIFA Soccer 96 > FIFA 97 -> FIFA Road tothe World Cup 98-> FIEA 99 > FIFA 2000 > ete, With the Systems Development Life Cycle, you neve just qui, you are alwys looking at ways to improve or surpass whit you have creed Analysis When you are given any problem you should start of by finding out about the problem and geting an idea of what you will make to solve the problem by +A detailed look at cutrent systems 1 Establish the objectives ofthe new system Electron Crafts wants to create a game that wil sell succesfilly, so it needs to see what the market wants to buy and what their current interests are. Iwill gather data ' How previous similar products have sold {market data) 1 What customers ae interested in (questionnaires and interviews) + Whether ithas any cade that could be adapted or reused (internal data) * Feasibility of making any proposed game (is it possible within the time, technical, cost and personne! limits to make the game?) Once it has done its research, it wil eeate a document listing objectives forthe new system. These objectives must be SMART so that we can check ifthe system has been created suceessflly SMART mens Lever, Maier Description Example Not acceptable! “The stem sould be able wo [specie [Make suze hats not ambiguousanditconcemsa part of your system _|dlaplay 5 tp score in ‘My system shouldbe good ‘descending oder [Measurable Is thre anyway that you can easily prove that you vet this ojeve. Te ame shoal Toad in Fest yoyo wie bea ce sure that within the Lime and resources available you will be able to stem will allow the saving | Te system needs fo be A laainble Make ste hat within the tie and lable youve be abet [My stem wallow hesaving HSH eds ‘complete the objective ‘of user preferences within 4 days ‘A receipt wil be printed and |My cashier system wil play ‘emailed to the customer ‘MP3s in the background “The system will involve a completely new game engine and code R_ Relevant Is the objective going to help you meet your user needs? ‘You are limited in the ime you have to complete this project. You must list ‘the deadline in your Analysis somewhere and can you finish each objective intime? Time- ‘bound The system will re-use code from previous products [Blectonic Crafls finds out that football games have sold very well in the past. Ifinds out that witha new football season approaching, customers ate intrested in playing a game with the atest names and kits. The most popular console isthe Super MES, bas ereated previous football games, so it can re-use and adapt some ofthe eode Exercise: Analysis Now we have all the data from Elestronie Crafts we can set the Objectives, remember these must be SMART. Which ofthese are suitable: +The system wail allow users to change player postions and keep track of game results Answer Expand] * The game will have areal world clock displaying the time on the sereen at all times Answe [Expand] + The system completely rebuild the game engine to use cutting edge 3D Answer: [Expand] * The system will calculate and display the player ratings from each game, numberof card, goals ete Answei [Expand] ' The system wil always be online, every game you fo play willbe against people from around the world Answer: [Expand] 1 The system should be really, realy, really good Answer: (Expand) What is main alm of the Analysis Answer: (Expand) ‘Name some methods of carrying out your Analysis Answer: [Expand] ‘What restaints/imits might you have when looking at making anew produet? Answer [Expand] Name the stages of the system lfeeyele in order Answer: Design Once we have setled on what we ae going to make and the objectives forthe system, we need to set about designing the components. Design i important as it allows you to star thinking about how you will make things, and hopefully avoid making mistakes late. The Process involved inthe design of a produc is looking at User interface * Processes + Data storage requirements For Blectronic Crafs they now know we ate making a football game forthe Super MES. ‘This system only has a joypad interface, theyll have to note which buttons should do what, and where everything will appear onthe sereen ‘ypes of put are important fo consider when designing serfs ‘The process design is probably the most complicated part. How will the game work out when someone bias scored, what will the code for playing a game on the internet look like etc. This may be designed using tools such as UML, Data flow diagrams and pseudo code. You don't need to know the specifies for this Unit but they will come in usefil forthe A2 project to wold mistakes later on Finally, Electronic Crafts would need to think about how the game would be delivered to the customer (download vs disc), how games will be saved (On the ‘machine, online or on a memory unit), and how online data would be stored (database details). ‘more and more Ls no longer require pysial medi Why is it important for companies to design products? Answer: [Expand] [Name 3 things that a company should design Answer: [Expand] Tow would you recommend a company distributes the latest computer game and why? Answer: [Expand] Implementation + Programming the software / ereation of hardware * Installation of hardware and software + Preparation of data files Training of users Writing the system documentation And at the same time make sure thatthe system that you build fits in with wht you designed Example: Electronic Crafts Implementation Electronic Cre ts will use the designs and code from previous products to code the game, probably in C+ They wil setup dhe servers to handle the online play, they will write code to install Uhe game automatically on users machines aller paying for it and leiter> Answer: [Expand] +The date for someone's birthday Answer: (Expand) + Someone's baie colour Answer: + Does the following calculation work: 14 * 2 Answer: [Expand] + Number of pages in a book. Answer: (Expand) + Name a date in February Answer: (Expand) Evaluation The final thing you should do is evaluate how it all went. Remember we are talking about a systems development life eyele here, so ifyou made any mistakes or things Jidt’t goto plan its best so make a nove of them. Then next time round you won't make the same mistake. However, the main par of the evaluation sto reflect on how successful the operational system is: + Review to confirm the new system meets the original objectives, + Identity any necessary modifications ‘An example of a Project Evaluation Objective ‘Complete ‘Notes Create 3D models of stadia ‘Yes [These are all complete and imported {Implement amltiplayer imtemet 7 _ingermet multiplayer is laggy and unplayable. We need to spend more time testi iors Ne net multiplayer is lggey and unplayable. We need to spend testing =) nine Compu per at [ves [ALBARN bu drat fer nog cae, et ine we eed ert A Skeleton code The exam questions are very hard to predict and this site is by no Youll st. The most important thing you should do is eam how to program, and leam how to program well ans going to give you everything you need forthe questo: + 2015 Fram + 2014 Exam + 2013 Exam + 2012 Exam + 2011 Exam Footnotes itpHfen wikibooks org/windex phptitle=A-level_Compoting/AQA Print version/Unit_1&oldid=2632260" + This page was last modified on 22 April 2014, at 01:03. + ‘Texts available under the Creative Commons Attribution-ShareAlike License ; additional terms may apply. By using this site, vou agree tothe Terms of Use and Privacy Policy

You might also like