Lesson 1.2: Algorithms and pseudocode
Before writing code you need to know which steps to take. That is an algorithm, and pseudocode is how you write it down.
The idea
An algorithm is the list of steps that solves a problem. It's what you think through before writing code.
Pseudocode is a way to write that algorithm with plain words and a few rules. It doesn't run: it lets you think without fighting a programming language.
The first words
| Pseudocode | What it does |
|---|---|
Algorithm … EndAlgorithm | Marks the start and the end |
Write | Shows something on screen |
Read | Asks the user for a value and keeps it |
Example
A program that says hello:
Algorithm Greet
Write "What's your name?"
Read name
Write "Hello, ", name
EndAlgorithm
If you type "Ana":
What's your name?
Ana
Hello, Ana
Line by line:
- It writes the question.
- It waits for you to type something and keeps it under the name
name. - It writes "Hello, " followed by what it kept.
What goes in quotes is written as it is. What goes without quotes is a name, and the program swaps it for what it kept.
Try it
Write an algorithm that asks for a name and a city, and answers, for example, "Ana lives in Seville".
Show the solution
Algorithm WhereYouLive
Write "What's your name?"
Read name
Write "Which city do you live in?"
Read city
Write name, " lives in ", city
EndAlgorithm
Summary
- An algorithm is the steps that solve a problem.
- Pseudocode writes it with plain words and a few rules.
Writeshows;Readasks and keeps the answer.