Aller au contenu
Londres, Royaume-Uni · Fondé en 1994
Français

Unit 2: Programming Fundamentals

How problems are turned into algorithms and programs, the building blocks that almost every programming language shares, and how programmers find and fix mistakes.

Unit 2 of 5 · about 54 minutes

2.1 From problems to algorithms and programs

An algorithm is a precise, step-by-step method for solving a problem or completing a task. A recipe, a set of assembly instructions and the procedure for processing a refund are all algorithms in an everyday sense. In computing, an algorithm must be unambiguous enough that a machine with no common sense can follow it exactly. A program is an algorithm written in a programming language so that a computer can carry it out.

Programming therefore involves two distinct skills. The first is problem solving: understanding what is required and designing a method that will work. The second is expressing that method correctly in a particular language. Beginners often focus on the second and struggle because the first has not been done. Experienced programmers spend a great deal of time thinking, sketching and asking questions before they write any code.

Computational thinking

The term computational thinking is often used to describe the habits of mind behind good problem solving. Four ideas are commonly highlighted:

  • Decomposition: breaking a large problem into smaller parts that can be solved separately. "Build an online shop" becomes listing products, managing a basket, taking payment and sending confirmations.
  • Pattern recognition: noticing similarities with problems already solved, so that existing methods can be reused.
  • Abstraction: focusing on the details that matter and ignoring the rest. A route planner treats roads as lines with distances and speeds, not as tarmac and kerbs.
  • Algorithm design: writing out the ordered steps that solve each part.

Writing algorithms in pseudocode

Before writing real code, programmers often describe an algorithm in pseudocode: structured, plain-language steps that are not tied to any one language. Here is pseudocode for working out the total of a shopping basket including a discount:

  1. Set total to 0.
  2. For each item in the basket, add the item's price multiplied by its quantity to total.
  3. If total is greater than 100, reduce total by 10 per cent.
  4. Display total.

This is short, but it already shows the key ingredients of nearly every program: storing values, repeating steps, making decisions and producing output. It also raises questions a careful programmer must answer. Is the threshold "greater than 100" or "100 or more"? Is the discount applied before or after delivery charges? What should happen if the basket is empty? Questions like these, often called edge cases, are where many real defects come from.

Tip: Before coding, test your algorithm by hand with two or three small examples, including an unusual one such as an empty list or a zero value. Many mistakes are easier to spot on paper than on screen.

Programming languages

There are hundreds of programming languages, but a handful dominate everyday work. Python is popular for data analysis, automation and teaching because of its readable style. JavaScript runs in every web browser and is also used on servers. Java and C# are common in large business systems. C and C++ are used where speed and close control of hardware matter, such as operating systems and games. SQL is a specialised language for working with databases.

Languages differ in their rules, called syntax, and in their strengths, but the underlying concepts transfer well. Someone who understands variables, decisions, loops and functions in one language can usually learn another far more quickly than they learned the first.

Common beginner mistakes

  • Starting to code before understanding the problem or the expected output.
  • Trying to write a whole program at once rather than building and testing small pieces.
  • Copying code from the internet without understanding what it does.
  • Ignoring unusual inputs, such as missing values, very large numbers or unexpected text.

In practice

Even if you never become a professional developer, algorithmic thinking is useful at work. Writing out a business process as clear numbered steps, with every decision and exception made explicit, is excellent preparation for automating it or for briefing a developer. If you work alongside a software team, a requirement expressed as precise steps with worked examples and edge cases will save time and reduce misunderstandings. Many spreadsheet formulas and workflow automation tools also use the same ideas of decisions and repetition.

2.2 Variables, decisions, loops and functions

Almost every programming language is built from the same small set of building blocks. Once you understand them, you can read simple code in most languages and follow the logic, even if the exact syntax is unfamiliar. This lesson uses plain pseudocode rather than a specific language.

Variables and data types

A variable is a named place to store a value so that it can be used and changed later. In the statement "set price to 25", price is a variable and 25 is its current value. Good variable names describe what they hold: invoice_total is far clearer than x.

Values have data types, which determine what operations make sense. Common types include:

  • Integers, whole numbers such as 42.
  • Floating-point numbers, numbers with fractional parts such as 3.75.
  • Strings, pieces of text such as "London".
  • Booleans, which are either true or false.
  • Collections, such as lists of values, which are covered in the next unit.

Mixing types carelessly causes errors. Adding the number 5 to the text "5" might produce an error, the number 10 or the text "55", depending on the language. Data read from forms and files often arrives as text and must be converted before calculations.

Decisions

Programs make choices using conditional statements, usually written with if, else if and else. For example: if the customer's age is under 18, refuse the purchase; else if the item is on the restricted list, ask for confirmation; else continue. Conditions are built from comparisons (equal to, greater than, less than) and combined with logical operators: and (both must be true), or (at least one must be true) and not (reverses true and false). Getting these combinations right is a frequent source of bugs, so it helps to write out a small truth table for complicated conditions.

Loops

A loop repeats a block of instructions. There are two main kinds:

  • A count-controlled loop repeats a known number of times or once for each item in a collection: "for each order in today's orders, print a label".
  • A condition-controlled loop repeats while something remains true: "while the user has not entered a valid password and fewer than three attempts have been made, ask again".

A classic mistake is the infinite loop, where the condition never becomes false, so the program never finishes. Another is the off-by-one error, where a loop runs one time too many or too few, often because of confusion about whether counting starts at 0 or 1. Many languages number the positions in a list starting from 0.

Functions

A function (also called a procedure or method) is a named, reusable block of code that performs one task. It can take inputs, called parameters, and can return an output. For example, a function calculate_vat(amount, rate) could return the tax due on any amount at any rate. Functions bring three major benefits:

  1. Reuse: the logic is written once and called wherever it is needed.
  2. Readability: a well-named function explains what a block of code does.
  3. Maintainability: if the rule changes, it is updated in one place.

Variables created inside a function usually exist only inside it. This idea, called scope, prevents different parts of a program from accidentally changing each other's data.

Remember: A good function does one clear job and has a name that says what that job is. If you struggle to name a function, it may be doing too much.

Putting it together

Consider a simple payroll check. A function receives a list of employees. For each employee, it reads the hours worked. If the hours are more than 40, it calculates overtime at a higher rate; otherwise it calculates standard pay. It adds each payment to a running total and returns the total at the end. In a few lines, this uses variables, types, a loop, a decision and a function.

In practice

These building blocks appear far beyond traditional programming. Spreadsheet formulas use conditions; workflow tools ask you to define triggers, conditions and repeated actions; data tools use functions. Recognising the patterns makes such tools easier to learn. If you are starting to code, practise by writing small functions that solve real tasks from your work, such as cleaning a list of email addresses or summarising a column of figures.

2.3 Debugging, testing and reading code

Every programmer writes code that does not work first time. Professional skill lies less in avoiding mistakes entirely than in finding and fixing them efficiently, and in preventing the same mistakes from reaching users. A fault in a program is commonly called a bug, and the process of finding and fixing it is called debugging.

Three kinds of error

TypeWhat it meansExample
Syntax errorThe code breaks the language's rules and cannot runA missing bracket or misspelled keyword
Runtime errorThe code runs but fails part way throughDividing by zero or opening a file that does not exist
Logic errorThe code runs to completion but gives the wrong resultApplying a discount to orders of 100 when it should apply only above 100

Syntax errors are usually the easiest to fix because the language tells you where they are. Logic errors are the hardest, because nothing appears to go wrong until someone notices an incorrect result.

A systematic approach to debugging

  1. Reproduce the problem. Find the exact inputs and steps that cause it. A bug you cannot reproduce is very hard to fix with confidence.
  2. Read the error message carefully. It often names the line and the type of problem. Beginners frequently skip this step.
  3. Form a hypothesis. Decide what you think is wrong and why.
  4. Test the hypothesis. Print the values of variables at key points, or use a debugger, a tool that lets you pause a program and step through it line by line while watching values change.
  5. Narrow it down. Divide the program in half and check which half contains the problem, repeating until you find it.
  6. Fix and confirm. Make the smallest change that addresses the cause, then check that the original problem is gone and nothing else has broken.

A surprisingly effective technique is rubber duck debugging: explaining the code line by line to someone else, or even to an object on your desk. Describing what each line should do often reveals where it does something different.

Tip: Fix the cause, not the symptom. If a total is wrong because one value is stored as text, converting that single value hides the problem; fixing how the data is read solves it.

Testing

Testing is the planned checking of software against expected behaviour. Good tests include:

  • Normal cases: typical inputs that should work.
  • Boundary cases: values at the edge of a rule, such as exactly 100 when the rule is "over 100".
  • Invalid cases: missing, wrong-type or extreme inputs that the program should reject politely.

Developers increasingly write automated tests: small programs that call parts of the main program with known inputs and check the outputs. A unit test checks one function; an integration test checks that several parts work together. Automated tests can be run every time the code changes, catching regressions, which are bugs introduced into features that previously worked. Some teams write tests before writing the code itself, an approach known as test-driven development.

Reading other people's code

Most professional programming involves working with existing code rather than writing from scratch. Useful habits include starting from the entry point and following the main path first, reading function names and comments to build a mental map, running the code with simple inputs to observe it, and changing one thing at a time. Clear names, consistent formatting and short comments explaining why, not just what, make code much easier for the next person to understand.

AI coding assistants

AI assistants can now suggest code, explain errors and propose tests. They can save time, but they can also produce code that looks plausible and is subtly wrong or insecure. Treat their suggestions as a draft from a fast but unreliable colleague: read and understand the code, test it properly and never paste confidential code or data into tools your organisation has not approved.

In practice

When reporting a bug to a development team, give them what they need to reproduce it: what you did, what you expected, what actually happened, any error message, and the date, time and data involved. A clear bug report can turn hours of investigation into minutes.

Case study: A discount bug at an online bookshop

Larkspur Books, a fictional independent online bookshop, offered free delivery on orders over 30 pounds. Shortly after a website update, customers began complaining that orders of exactly 30 pounds were not being charged delivery, while a few orders slightly above 30 pounds were.

The developer, Amira, started by reproducing the problem with test baskets worth 29.99, 30.00 and 30.01 pounds. The first two behaved incorrectly in different ways. Printing the values at each step showed two separate faults. The condition had been changed from "greater than 30" to "greater than or equal to 30" during the update, a boundary error. Separately, prices were being added as floating-point numbers, so some totals came out a tiny fraction below the true figure.

Amira corrected the condition, changed the program to calculate money in whole pence, and added automated tests for baskets just below, exactly at and just above the threshold. Those tests now run every time the site's code changes, and similar boundary tests were added to the shop's other pricing rules.

Activity

Choose a simple rule from your workplace or daily life, such as a discount, an approval limit or a late-fee policy. Write it as pseudocode using at least one variable, one decision and one loop. Then list five test cases, including at least one boundary case and one invalid input, with the result you would expect for each.

Compare with a model answer

A strong answer chooses a clear rule, for example: expense claims above 250 pounds need manager approval. The pseudocode sets an approval list to empty, loops through each claim, and if the amount is greater than 250, adds the claim to the approval list; otherwise it marks the claim as approved. It ends by displaying the approval list.

The test cases include a normal claim (100 pounds, approved automatically), a high claim (400 pounds, needs approval), boundary claims at exactly 250 and 250.01 pounds with the expected outcome stated clearly, and an invalid input such as a negative amount or a missing value, which should be rejected with a helpful message. The best answers notice an ambiguity in the original rule, such as whether 250 itself needs approval, and state an assumption.

Key takeaways

  • An algorithm is a precise sequence of steps; good programming starts with understanding the problem and designing the method.
  • Variables, data types, decisions, loops and functions are the core building blocks shared by almost every language.
  • Functions make code reusable, readable and easier to maintain, especially when each does one clear job.
  • Debugging works best as a systematic process: reproduce, read the error, hypothesise, test, narrow down and fix the cause.
  • Testing normal, boundary and invalid cases, ideally with automated tests, prevents many defects from reaching users.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 1 Unit 3 →
WhatsApp