Computer Programming: Fundamentals

Learning to program is difficult and can look overwhelming when you first start working with programming. Unlike the physical side of computing where you can see things and hear things working (and smell if things go really bad) programming is invisible in it’s mechanics making it difficult to see what is going on. But, if you go slowly, look at examples, and practice then you’ll get a better as you go. Remember – it is not easy to get to grips with programming to the point where you can be happy calling yourself a programmer but everyone that is had to start somewhere and they all have covered these fundamentals.

It’s worth remembering that all computers do is take in something, do something with it, and output something like any machine. Let’s get started.

Variables, Constants, Operators, Input, Outputs and Assignments

Computer programs are at their basic form have three parts: inputs, processes, output. Here’s a simple example

name = input("Enter your name:" )
GREETING = "Hello "
print(GREETING + name)

Here the input is whatever the used type in captured in a variable called name. The process is the add that to the word Hello. The output is the result of the addition or “concatenation” of words. For this simple example we already have a few fundamental parts:

  • Input – anything that goes into a process
  • Output – anything that comes out of a process
  • Variable – something to store something variable in e.g. text like a name. Variables normally set and change throughout a program
  • Constants – things that don’t change in the program. You need constants to maintain accuracy, avoid mistakes, and keep things secure e.g. standard greeting “Hello”. Constants are often written in capitals to highlight the they are not variables.
  • Operators (3) – something that does something to a variable or constant.
    • Assignment operator – assigning a value to a variable. Most programs use the equals sign (=). In the example above the typed value was assigned to the variable ‘name’.
    • Arithmetic operator – changing a variable by using an arithmetical operators (basic maths) that we learn at school: addition (+), subtraction (-), multiplication (*), division (/), and three may be new ones: modulus (MOD or % – the remainder to a division), quotient (DIV – the number of whole numbers in a division), and exponential (^ – multiples of the same number). Don’t worry much about what they are if you don’t know as we will cover them.
    • Comparison operator – ability to compare one variable to another: equal to (==), not equal to (!=), less than (<), more than (>), less than or equal to (<=), greater than (>) and greater than or equal to (>=).

These are the very basic things that we build programs from. There are lots of other things to you will learn when you work on different programming languages but it’s the vast majority that we known of. If you do come across things in computer programming that you don’t understand then look around to see what it’s for as it’s not that uncommon for smart people to create something new to solve a problem they are trying to solve.

Three Basic Programming Constructs

With all the components to build a computer program how do we build one? There are three parts to consider when building a program:

  1. Sequence
  2. Selection
  3. Iteration

Sequence

The program you are creating will have a start, some process, and a stop. At its basic level this is the sequence that the program should run in. Clearly programs are more complicate but they all have a designed sequence that start and (should) stop. When the program is all working then everything is good. However, on the odd occasion where the program is not doing what has been programmed then one of the first places to try and work out what is going on is to understand the sequence in which it should work.

The sequence can get very complicated when it needs to solve a complex problem or if it is dynamic by bringing in new sequences depending on the situation of the program. Another thing to consider when looking at the sequence of a program are different start and stop points. Always good to map these out in flowcharts or another method to see clearly where things are. Computational thinking and the three parts help: abstraction. decomposition, algorithmic thinking.

Selection

Throughout the program the program will take in inputs, make logical decisions, and create outputs. How it makes the logical decision are called selections. We can show very simple selection by adding a selection to our code above. This time if the name collected is “Al” then we change the greeting to let them know they have won 5 credits.

name = input("Enter your name:" )
GREETING = "Hello "
if name == "Al" then:
    print(GREETING + name + " . You have won 5 credits!)
else:
    print(GREETING + name)

Selections are done when the program checks the value of a variable and then does something depending on the state or value of that variable. Selection can be found in many places including If statements and loops or iterations.

Iteration (count- and condition-controlled loops)

The last basic construct for programming it what computers are good at – check- do- repeat. Anything that repeats until a condition is met is called a loop and there are three main types: For, While and Do While. The difference between them do not matter here as we’ll cover them later. For now here is a little example of a simple loop which will print Hello and then the first letter of the name entered.

name = input("Enter your name:" )
GREETING = "Hello "
for i in (name):
    print(GREETING + i)

Common Arithmetic Operators

Computers are good at mathematics specifically arithmetic which is the study of numbers (the other section of mathematics is Boolean Logic which we will explore is right after this one. Arithmetic operators change the value of a variable by the function of the operator and any additional variables. These are the standard arithmetic operators that you will use to change the value of a variable.

OperatorSymbolExample
Addition+x + y | 3 + 2 | 5
Subtractionx – y | 3 – 2 | 1
Multiplication*x + y | 3 * 2 | 6
Division/x + y | 3 / 2 | 1.5
Modulus% or MODx + y | 3 % 2 | 1
Exponentiation** or ^x + y | 3 ** 2 | 9
Floor division// (round up x + y | 3 // 2 | 1

These are not the only ways to change a variable as computers can make shortcuts to save on the typing and shorter the code. Another operator is an assignment where a value of a variable is assigned done with an equal sign (=). The assignment and the arithmetic operators can be combined like this …

age = 5
age = age + 5
# or ...
age += 5

All the arithmetic operators can be used this way which is helpful when using loops.

Comparison Operators

Comparison operators check one (compare) variable against another one. There are six comparison operators that check to see if the statement is true of false

OperatorSymbolExample
Equal to==x == x | 3 == 2 | FALSE
Not Equal to!=x !+ y | 3 != 2 | TRUE
Less than<x < y. | 3 < 2 | FALSE
Greater than>x > y | 3 > 2 | TRUE
Less than OR equal to<=x <= y | 3 <= 2 | FALSE
Greater than OR equal to>=x >= y | 3 >= 2 | TRUE

The comparison operator is used when we want to make a decision and branch the process depending on that condition. A simple example would be checking the time and displaying a different greeting depending on if it is morning or afternoon. The next common example is security where the user name and the password must be equal to what is stored. The crucial thing to remember with comparison operators is knowing what there are two results – one where the condition is TRUE e.g. password entered is true and FALSE e.g. password is incorrect. You have to write code to cope with both options.

Common Boolean operators: AND, OR, NOT

The last operators are the ones that check the status of a variable as being True or False, or 1 or 0, or On or Off. We have a whole page on Boolean Logic which explains the detail and we have seen how True and False condition result from a comparison operator. Boolean operators add another option as they can bring together multiple conditional operators to create greater options for a program. There are many boolean operators but to start with these are the key three.

OperatorSymbolExample
NOTNOTif TRUE change to FALSE
if FALSE change to TRUE
ORorif x or y equal 3 then TRUE
ANDandif x and y equal 3 then TRUE

Boolean operators are really seen at the electronic levels as a set of gates that change the output depending on the input. Back to our security example earlier to enter a website both the user name and password have to be correct (TRUE) for the output to also be TRUE. If either is not correct then the output is false and you can not enter the site.

One thing to point out is the NOT Boolean operator. It’s not really an operator like the ones mention before as those check a value and then do something. The NOT boolean inverts or makes opposite what ever is coming in. It’s the same as multiplying a number by minus one (-1). Don’t worry too much about Boolean operators for the time being but do be aware they are a fundamental way to way programs run through resolving the flow of the programs (computers only deal with True and False to process information).

Data Types

Imagine you want to make a salad. What would you put in it? Depends on the salad but it would normally be lettuce, cucumbers, tomatoes, perhaps some nuts if you get fancy. Now imagine you want something sweet to eat: you could choose chocolate or ice cream or may fruit. In both of these case you had different type of ingredients (vegetables, fruit, chocolate, etc).

Finally now imagine you want have a challenge to transport some water. One challenge is to transport a cup full and another is to transport truck full. For the first challenge you’d probably use a flask or even a bag – something small and cheap, For the truck you could not use the flask as it wouldn’t fit – you would need something big enough to handle that volume.

Great – so ingredients and water carrying – what does this have to do with computer programming? To create a program you need to take in certain inputs and then do something with them to create outputs. The computer needs to know what type of input, process, and output are so that it can work with them. For example if we were to make a salad and we added metal or paper it wouldn’t work – we need to use food that we can eat. For the water carrying example the computer needs to know what size of data it is working with. The speed of a computer is defined in part my how fast we can move things in memory in and out of the CPU. It is faster to move smaller things in and out so when we need to carry small amounts we use small containers but there are times when the thing we are working on is big so we use a bigger container. If we try and fit a small thing into a big container it doesn’t matter but it is not efficient. If we try and fit a big thing into a small container it just won’t work and the program will fail.

There are times when the program works for some occasions but fails on others. The main one being when there is a division involved. Things can be fine when the division creates a whole number but things get tricky when it creates a fraction as we can express that in different ways: 12 divided by 5 can be expressed as a decimal – 2.4 or as a remainder or modulus – 2 remainder 2 (2r2). The computer needs to be able to cope with these outputs otherwise it will fail and that is super frustrating as it can be difficult to see until it happens. Data types size or memory allocation is measured in bits (one bit can store two values 0 or 1) or bytes which is 8 bits (00000000 which can store 2^8 values – 256 values).

To ensure the computer the doesn’t choke on processing the inputs there are defined data types for each programming language. These are the ones you will find in all programming languages.

Integer – whole numbers

Whole numbers used for counting and other arithmetic. Both positive and negative and zero (we are definitely saying zero is a number!). Not fractions. Memory allocation – 2 or 4 bytes depending on how big the number you want to use.

Real or float – whole numbers and fractions

Large set of numbers from integers as decimal places are allowed. As a number after the whole number is allowed in generally takes up twice the memory of an integer. Commonly used in arithmetic where pure fractions (1/3) or decimal parts £10.75 or 0.25 being 25%.

Boolean

The simplest data type used in decision making holding either 0 or 1, or No or Yes, or False or True. Commonly used to store a state or a record e.g. has checked terms and conditions or is over 18.

Character (char) and String

Char will store one letter whilst string will store as many as you like. Char values can be used to store abbreviations of a whole word e.g. Male = M, Female = F. If you want to store more than one character then you will need a string of characters or string.

Casting

Sometimes you have to change the data type from one type to another to make the program work. For example when you ask for a number from someone this will be entered as a string as it will be coming from a text box or a dropdown. We know the number 1 when added to the number 2 we get the number 3 but in the heart of the computer all three numbers are encoded as text not numbers as the computer can’t tell as it will treat them as the data type they have come in as.

Additional Programming Techniques

Basic String Manipulation

So far we have looked at how numbers are changed through arithmetic – adding numbers, running a loop through a number. Whilst computers are really good with arithmetic we humans are better with words or strings of characters (char is single character, string is multiple chars).

There are many ways that strings are manipulated in programming. These can be classified into two sets:

  1. Structure: the string is changed with respect to to length and contents
  2. Format: changing the character or string to an upper or lower case

Structure changes included adding strings together which we call concatenation (chain things together) to differentiate from adding which is only for numbers. Common concatenation is to take an input and then add to another strong e.g. greeting = “Hello ” + name + “. How are you today?”. Other structural changes including “trimming” where you take a specific length of the string from either end. Splitting is exactly what it says

Basic File Manipulation

Open

Read

Write

Close

Records to Store data

SQL to Search for data

Arrays: 1D (lists) and 2D (arrays)

Sub Programs

Random Number Generation

Previous: Algorithms < | Programming Fundamentals | > Next: Robust Programming