What an algorithm is
In this topic you write an algorithm as pseudocode and as a flowchart, then write your first C program. What to install, the course plan with its hours and how you are assessed are on the course start page.
Algorithm
A computer does not understand "roughly". An algorithm is a finite, unambiguous sequence of steps that turns input data into a result.
- Finite: the steps end at some point. "Repeat until it works" with no stopping condition is not an algorithm.
- Unambiguous: every step can be read only one way. "Take the bigger number" is clear; "take a suitable number" is not.
Pseudocode
Before writing code, it helps to write the algorithm as pseudocode: short sentences, without the rules of any programming language. Over the course you build a gradebook program, so the first example is the average of grades:
1. sum ← 0, count ← 0
2. While there are grades left:
2.1. sum ← sum + grade
2.2. count ← count + 1
3. If count > 0:
3.1. Print sum / count.
Otherwise:
3.2. Print "No grades".
The arrow ← means "remember": sum ← sum + grade – add the grade to the sum and remember the new sum.
Three blocks
Any algorithm can be built from just three blocks:
- Sequence: steps one after another (step 1, then 2, then 3).
- Selection: a condition picks one of two paths (step 3: if count > 0).
- Repetition: do the same thing while a condition holds (step 2: while there are grades left).
That is structured programming: a program built from these three blocks, nested inside each other, with no jumping to arbitrary places.
Flowchart
The same algorithm can be drawn as a flowchart. Every shape has its own meaning:
| Shape | Meaning |
|---|---|
| oval | start or end |
| rectangle | an action, e.g. sum ← 0 |
| diamond | a condition with two exits: yes and no |
| parallelogram | input or output |
In the homework you write the flowchart as text, in the Mermaid language, and GitHub draws it for you. The average algorithm in Mermaid looks like this:
flowchart TD
start([Start]) --> init[sum = 0, count = 0]
init --> more{Grades left?}
more -- yes --> add[sum = sum + grade<br>count = count + 1]
add --> more
more -- no --> any{count > 0?}
any -- yes --> avg[/Print the average/]
any -- no --> none[/Print: no grades/]
avg --> stop([End])
none --> stop
([...]) is an oval, [...] a rectangle, {...} a diamond, [/.../] a parallelogram, and --> an arrow.
This topic's C programs are only a sequence: statements run one after another, top to bottom. You write selection and repetition in C in topic 3, but you write them as pseudocode and a flowchart already now.