Learn IT With Davo
  • Mr Davidson's Blog
  • A Level CS
    • Lessons
    • Unit 3 - Coursework Guidance
  • GCSE CS
    • Lessons
    • Glossary of Terms
    • Unit 1 Revision >
      • 1.1 - Systems Architecture
      • 1.2 - Memory
      • 1.3 - Storage
      • 1.4 - Wired and Wireless Networks
      • 1.5 - Topologies, Protocols and Layers
      • 1.6 - System Security
      • 1.7 - Systems Software
      • 1.8 - Ethics and Law
    • Unit 2 Revision >
      • 2.1 - Computational Thinking
      • 2.1 - Searching and Sorting Algorithms
      • 2.1 and 2.2 - Writing Algorithms/Programming Techniques
      • 2.2 - SQL and Database Structure
      • 2.3. Robust Code
      • 2.4. Logic
      • 2.5. Translators and Facilities
      • 2.6. Data Representation
  • KS3 CS
    • Year 7 - Small Basic
    • Year 9 - VB
  • Exam Technique
    • A Level
    • GCSE
  • About
  • Requests

2.1 and 2.2 - Writing Algorithms/Programming Techniques

In this section we look at how you can write algorithms and learn to use a form of code called "Pseudo Code" which will help you to structure your thinking, produce designs for your coursework and answer exam questions. This section combines all of the knowledge you will need on programming from both sections 2.1 and 2.2

Click to jump:
  • Data Types
  • Pseudo Code
  • Variables 
  • Constants
  • Output
  • Input
  • Making Decisions (IF)
  • Iteration (For, While)
  • String Manipulation
  • Saving to a file
  • Reading from files
  • Procedures
  • Functions
  • DIV and MOD
  • Arrays
  • Casting

Data Types

Picture
Data. You're surrounded by the stuff. It's everywhere and your life is ruled by machines that take data and do weird things to it, to make weird conclusions. Like the time YouTube suggested I subscribe to videos of Nigel Farage. Yeah... Thanks for that.

On it's own, then, data is meaningless. It is just, well, what it is. It's raw, and in the context of data made up of characters:

Data is just a raw stream of characters, symbols or numbers.

But we don't think of data like that. Generally we see data as a piece of text, a date, a quantity of something, for example. So, the best thing to do is to organise all that data by what type it is.

When writing algorithms in pseudo code you've used "variables" which, if you've forgotten, are just boxes that we can stick a piece of data in. Until now, we've not worried at all about what kind of data that is, we've simply done things such as:

Age = 32

and

Fish = "Badger"

It didn't matter whether we were using text or numbers or whatever, the technique in pseudo code is the same - just whack a name down and assign a value to it. But this will no longer do, Watson.

Computers like it when you tell them what kind of data they are dealing with. In fact, if you don't, most programming languages will vomit out error messages all over the place or simply won't even compile your code. When you've looked at the table below I'd suggest you scroll down to the section on "casting" which explains exactly why you need to care about data types in the exam.

Picture
 

Pseudo Code

Picture
Bowling For Soup - they had a song called "almost." They also had one called 1985, which almost made it up the charts once. Maybe they should've called it "pseudo" but then that almost sounds a bit like a made up Phil Collins word...
Pseudo (pronounced "sue-dough" if you were wondering). What an awesome word, meaning "almost," or "something that is an imitation."

When we talk about "Pseudo Code" we mean that we are going to use something which is:
  • Almost like a programming language
  • Not quite plain English, not quite like a real programming language

Which, really, sounds quite pointless, doesn't it? So why do we bother with it?

The reasons for pseudo code are actually quite numerous but mainly:
  • It really helps us write and plan algorithms
  • it's "language agnostic" which means we can use it regardless of what language we go on to actually develop in
  • It really helps you to learn how to program as it's more structured than writing out algorithms in plain English.

Oh and above all else - it's the basis for your entire Unit 2 exam!
​
Deep joy.


You will be using the pseudo code structure that OCR specify and I'll have given you a copy of, but if you can't find it then you can always download a copy by clicking this link.

The good news is that pseudo code isn't too picky - so if you forget how the OCR guide tells you to write a certain construct, you can just write down something which is close enough, for example:
Print("Horse tranquiliser")

​would be just as acceptable as:
Output("Horse tranquiliser") 

So, what we need to do now is look at the building blocks of our programs and flow charts and see how these translate directly in to pseudo code. This is one small step for me, one giant leap for your understanding of how to make programs (yes, I just did that. I went there. You can't teach puns like that, it's something you're born with)
 

Variables

Picture
I Googled "constant" and this came up. The original caption was "Des, panicking in a helicopter."
I needed to search no more at that point.
Definition: A variable is an area of memory, which has an associated name, used to store program data. 

The name variable is a big give away as to how they behave - their contents can vary. This is what makes them useful. 

Why do we use variables?
  • We need to be able to store information
  • We need to be able to manipulate information in our programs
  • It makes life a LOT easier when we give data a NAME that we understand.

If you were sat in Maths and your teacher gave you the question "If x=5, what is 2x?" you would instantly say 10. Algebra is the exact same concept as variables - we are storing values and giving them a label, such as x!
​

Variables are even better than algebra because instead of using single letters like x, t, y, n etc we can actually use descriptive names. So, for example, instead of x we could have "number_of_penguins" which is far more obvious, right?

Imagine, then, a variable as just a big old box with a name on the side.

There are some rules for variables:
  • You can call them anything, but no spaces are allowed. For example, trousers, fish_brackets and custardDigger are all valid names. "Chunder Jacket" would not - because it has a space.
  • You can store more than just numbers in a variable - Text, true or false and so on.
  • You put something IN a variable using the = sign (meaning assign - you 'assign' a value to a variable.) For example, cheese = "brie"
  • You can only put ONE thing in a variable at any one time. So if we had the following three lines of code:
    • Cheese = "brie"
    • Cheese = "cheddar"
    • Cheese = "gouda"
    • What is the final value of Cheese? It's "Gouda" because that was the last thing we assigned to the variable. Geddit?​

Constants

There are times in our programs where we will use a value that never, ever changes no matter what. Here are some examples:

Number_of_cm_in_a_M = 100
Number_of_pence_in_a_Pound = 100
PI = 3.141


There are other times when we may have a value in our programs that is unlikely to change, but might do in the future. We might want to use this value a lot in our code, but we never want to let the user, or any of our code change it. For example:

MrDavidsonsPreferredBribeAmount = 50000

If you were making a program that used these values, you'd be tempted to just use the numbers - why not? They never change so what's the point in giving them a name, let alone going to the hassle of creating a variable for them?

The answer is:
  • It makes our code much easier for others to understand
  • If we use this value lots and it changes, we have a problem finding all the places we used it
  • it makes our code much easier for others to understand
  • We can ensure that the correct value is used in our code and it is never, ever changed by code or the user
  • it makes our code much easier for others to understand

Now that's clear, how do we declare these variables? Just like any other, right? 

Nope.

In pseudo code, use the key word CONST:

CONST Number_of_pence_in_a_Pound = 100

Now this value can be used anywhere in your code but you know it won't change. You also know you'll never accidentally use the wrong amount.

Programming Constructs and How to Use Them

This is like your toolkit. You don't need much to make really useful programs and we are going to look at only four concepts and, trust me, by combining these you can make any program.

The worst thing you can do when writing an algorithm is just sit there and write nothing. Considering you only have a choice of four different things to use, and two of them are so obvious it's painful (input and output) start gambling - pick a construct and see if it fits your problem! You will learn nothing if you do nothing. Just saying.

IMPORTANT EXAM POINT

These programming constructs are templates and you should learn them as such. When you answer an exam question you can still get plenty of marks without actually understanding the question. All you need to do is:
  • If a question says anything like "asks the user..." "gets ... from the user" or anything similar - write out an INPUT template with a sensible variable name,
  • If you are asked to output anything or tell the user anything - write an OUTPUT template
  • If the question has the word "IF" in it then... use an IF template. Don't worry if you can't think of the rule, just put it in!
  • If the question obviously repeats the same actions over and over, or uses an array, you are 99% likely to need to use a FOR LOOP template.
  • If the question has anything that involves reading and writing to files - use the FILE INPUT/OUTPUT template
  • If the question asks you for a Function or Procedure then you're laughing - write out the template for either using a sensible name and try to get the parameters right.

Seriously, even if you are just guessing, you can break questions down like this and just write in the right statement and you'll get some of the marks without trying. It's a god send if they ask you to write a function because you'll get marks for simply writing the word function, return and some sensible variable names.
 

Output

Use it when: You need to write some text on the screen, tell the user something or show the value of a variable

What it looks like:
 PRINT ("Maths stands for: Mathematical Anti-Telharsic Harfatum Septomin")

​Different ways of using it:
PRINT (Score)

If score had a value of 5 then simply the number 5 would be output on the screen.

PRINT ("Your score is ", Score)

This would output:

Your score is 5

Things you should know:
  • Anything in quotes "like this" is called a 'String Literal' and basically this means whatever you put in quotes WILL be written to the screen exactly as you wrote it.
  • If you intended to output the value of a variable, do NOT put it in quotes or you'll get strange things happening. Actually you won't, it'll just print the variable name on the screen and your users will simply scratch their heads and close your program.
  • Finally, as in the example above, you can put together string literals and variables to make lovely, formatted output that makes more sense than just a number or word being printed to the screen. This technique is called "concatenation" and you'll learn all about it during programming lessons.
 

Input

Use it when: You need to ask the user to enter some information, or you need to get information from another source such as a file.

What it looks like:
Badgers = INPUT("What is your very favourite amount of Badgers?")

Things you should know:
  • You MUST always assign input to a variable. You should always follow the format Variable = Input("message to display to the user")
  • If you don't assign input to a variable... that input will literally be forgotten about. Not exactly useful!
  • The string literal (bit in quotes after the INPUT) is a message that is displayed to the user. It is NOT the input, it isn't what will be stored in the variable - it is what will appear on screen, so should be a nice question.
 

Making Decisions - IF... THEN... ELSE...

Use it when: You need to make decisions in your program, when you only want it to do something in certain circumstances

What it looks like:
Example 1
IF jamesBond = "Sean Connery" then
    PRINT("Why yesh, Mish Money Penny.")
END IF
Example 2
IF jamesBond = "Sean Connery" then
    PRINT("Why yesh, Mish Money Penny.")
ELSEIF jamesBond = "Daniel Craig" then
    PRINT("The best films in the series by far.")
END IF
Example 3
IF jamesBond = "Sean Connery" then
    PRINT("Why yesh, Mish Money Penny.")
ELSEIF jamesBond = "Daniel Craig" then
    PRINT("The best films in the series by far.")
ELSE
    PRINT("Not a fantastic Bond.")
END IF
Things you should know:
  • You must complete all IF statements with an END IF - it's really important to show where the IF statement ends!
  • Example 1 shows the simplest use - one rule. If the outcome of the rule is true, then the code prints a message, otherwise it is simply jumped over and ignored.
  • Example 2 shows how to use ELSEIF to have an alternative rule, or how to check a second condition before moving on. This is particularly useful if you have a number of things to check and act upon.
  • Example 3 shows how to use the ELSE statement - ELSE is really useful when you want to have something happen when none of the other IF rules are true. It's kind of a "if it's not anything else, then do this" statement.
 

Going Round in Circles - FOR... NEXT / WHILE... END WHILE

Use it when: There are not many programs you will ever write where there isn't a need to do things repeatedly. Any time you see repetition in a program, any time you find yourself doing something similar (even with small changes from before) then you need a loop.

There are two types of loop we need to know about, the FOR loop and the WHILE loop. Let's have a look:


What it looks like:

FOR A=1 to 20
    PRINT("The counter is ", A)
NEXT A


WHILE rock != "quit"
    rock = INPUT("Please enter your favourite type of rock.")
    PRINT(rock, " is a nice bit of rock, that.")
END WHILE


How does it work - FOR loop:

Key rule - Use a FOR loop when you know EXACTLY the number of times you want to do something.


Lets look at the example, line by line:

FOR A=1 to 20

This line sets the loop up. First a variable is created, in this case we called it A. 

A is our loop counter and it's very, very, very useful. It has two main purposes:
  1. To count how many times the loop has gone round, so we know when to stop
  2. So we can use it as a counter which can be output or used when searching for things.

Every time the loop goes round, this line checks to see if A has reached 20, if it has, the loop stops. If it hasn't, the loop goes round again.

Next line:
    PRINT("The counter is ", A)

This line is just to demonstrate what you could do inside the loop. In this case we simply write out the same thing each line and include the loop counter so it counts up from 1 to 20. The output would look like this:

The counter is 1
The counter is 2
The counter is 3
...
...
The counter is 20


Final line:
NEXT A

This line is really simple, when we get to NEXT A, the value of A is increased by 1 and the computer then goes back to the FOR... line and begins the loop again. It's important to remember the NEXT key word or we won't know where the loop ends!​
How does it work - WHILE loop:

Key rule - Use a WHILE loop when you don't know how many times you need to go round doing something - for example, letting a player play a game until they lose all of their lives, adding numbers to a total until the user enters -1 and so on...


Lets look at the example, line by line:

WHILE rock != "quit"

In this loop we have a variable called rock. The loop will go round and round until the contents of rock is the word "quit"

It's useful to be able to set loops up like this because it means we can make programs that are totally flexible. One time the user may enter 100 things before they type "quit" another time they may type "quit" immediately. Both are totally acceptable and our code can handle this and any other scenario.

     rock = INPUT("Please enter your favourite type of rock.")     
    PRINT(rock, " is a nice bit of rock, that.")


These lines just show an example of how the loop might work - it also gives the user an opportunity to type "quit" so the loop would end. Note that if the user never types "quit" then the loop never ends!

END WHILE

This is simple - we must show where the loop ends. At this point, if the user has not typed in "quit" the program would go back to the start of the loop.

Loading and Saving Files

myFile = openRead(“sample.txt”)
x = myFile.readLine()
myFile.close()

endOfFile()

myFile = openRead(“sample.txt”)
hile NOT myFile.endOfFile()
print(myFile.readLine())
endwhile myFile.close()

 myFile = openWrite(“sample.txt”)
myFile.writeLine(“Hello World”)
​myFile.close()

Arrays

Picture" 'Arry!... 'Arry!... Oi, 'Arry!"
"Roy, it's an Array, not 'Arry..."
"What's going on?!"
More often than not, in programming you want to store a lot of similar data. In most of our examples so far, you've stored a single value - "name" or "age" for example. But in reality, think of any software that you use that only stores one piece of information. The list isn't very long is it?

Before we move on, please understand that this is about storing similar data, not identical data. One example may be a list of high scores in a game - the data is similar, but not the same. The same would be true for a list of names - we're storing the same kind of things, but everyone's name will likely be different.

When might you want to store lots of similar data?  Imagine you're making a program which stores information about people (Facebook, anyone?)

When someone new signs up, they enter their personal details. If we programmed this using our current knowledge we might have something like this:

name = INPUT("What is your name?")

that's fine for one name, right? But what about when we add the next person? If we do the same again, remember the rules of variables - the old piece of data is overwritten. Hmmm.

What about this?

name1 = INPUT("What is your name?")

This solves one problem, we don't overwrite the previous data, but it does create another problem - how do we know which variable name to use?! How many people will be entered in to the system?! It's all kinds of bad.

One step towards a solution here is to use an Array.

An array, according to the gospel that is OCR, is something which:
  • Allows multiple items of data to be stored …
  •  ….. under one identifier/name

It's good because:
  •  It can be used to you can store data in a table structure 
  •  Reduces need for multiple variables (stops you having lots and lots of variables for the same thing)

An array is nothing more than a variable with brackets after it. If you understand a variable, then you understand an array, trust me.

What does it look like?

In pseudo code:

ARRAY names[4] 

Which would create an array (variable) which can now hold FIVE pieces of information. Why five? Because we count from zero, so  there are five spaces in our array. 

How is an array used? Just like a variable, but you just have to say which slot in the array you want to use:

names[0] = INPUT("What is your name?")
names[1] = INPUT("What is your name?")
...
...


or we could simply assign values like this:

names[0] = "John"
names[1] = "Tom"
names[2] = "Trevor"
...
names[4]="Archibald"


so if you write:

PRINT(names[2])

What is the ouput going to be? It's clearly "Trevor"

See, it's not so bad is it?

Casting

Exam Definition: Changing a variable from one data type to another

Let's say we have the following pseudo code:

Amount_of_Crazy = "45"

This is clearly a string, right? Notice the quotes.

If we then tried to do this, it would be all kinds of wrong:

Probability_of_Death = Amount_of_Crazy * 35

Because you can't multiply text by 35, can you?

To cast, then we use the following statements:
  • STR(number)    - converts whatever number is in the brackets in to a string
  • INT(string or char)    - converts whatever is in the brackets in to an integer value
  • FLOAT(string)    - converts whatever is in the brackets in to a decimal value

Any time you need to use a value that is the wrong data type, you need to cast it. Let's try that example again:

Amount_of_Crazy = "45"
Probability_of_Death = INT(Amount_of_Crazy) * 35

This now works perfectly because we have cast the string to the integer data type.

Powered by Create your own unique website with customizable templates.
  • Mr Davidson's Blog
  • A Level CS
    • Lessons
    • Unit 3 - Coursework Guidance
  • GCSE CS
    • Lessons
    • Glossary of Terms
    • Unit 1 Revision >
      • 1.1 - Systems Architecture
      • 1.2 - Memory
      • 1.3 - Storage
      • 1.4 - Wired and Wireless Networks
      • 1.5 - Topologies, Protocols and Layers
      • 1.6 - System Security
      • 1.7 - Systems Software
      • 1.8 - Ethics and Law
    • Unit 2 Revision >
      • 2.1 - Computational Thinking
      • 2.1 - Searching and Sorting Algorithms
      • 2.1 and 2.2 - Writing Algorithms/Programming Techniques
      • 2.2 - SQL and Database Structure
      • 2.3. Robust Code
      • 2.4. Logic
      • 2.5. Translators and Facilities
      • 2.6. Data Representation
  • KS3 CS
    • Year 7 - Small Basic
    • Year 9 - VB
  • Exam Technique
    • A Level
    • GCSE
  • About
  • Requests