Pseudocode and flowcharts
What you’ll learn
- How to write pseudocode
- How to draw a flowchart
- How to turn either one into real code
Pseudocode
Pseudocode is code-like plain English. It isn’t a real language, so there’s no syntax to get wrong; it’s for thinking.
forever: read distance if distance < 20 cm: turn left else: drive forwardFlowcharts
| Shape | Meaning |
|---|---|
| Rounded box (oval) | Start / end |
| Rectangle | An action: “drive forward” |
| Diamond | A decision with yes/no arrows: “distance < 20?” |
| Parallelogram | Input or output: “read sensor”, “print” |
| Arrows | The order of steps |
(Start) │ [Read distance] ◄──────────┐ │ │ <dist < 20?> ─yes─► [Turn left] ─┤ │ no │ [Drive forward] ──────────────────┘Why plan first?
Bugs are much cheaper to fix on paper. Walking through a plan with a few example values (“what if the distance is 15? 50?”) catches mistakes before you write a line of code.
Example: pseudocode to code
Pseudocode:
forever: if both line sensors see white: go straight else if left sees black: turn left else if right sees black: turn rightRobot simulator code:
function loop() { if (!lineLeft() && !lineRight()) motors(50, 50); else if (lineLeft()) motors(10, 60); else if (lineRight()) motors(60, 10);}Example: tracing with values
| distance | Decision | Action |
|---|---|---|
| 80 | 80 < 20? no | drive forward |
| 25 | 25 < 20? no | drive forward |
| 15 | 15 < 20? yes | turn left |
Try it
Turn this pseudocode into working code: forever: if distance < 30 turn right, otherwise drive forward slowly.
Robot commands
motors(left, right): wheel power, −100 to 100lineLeft(),lineRight():trueover the black linedistance(): cm to the nearest thing ahead (max 200)distanceLeft(),distanceRight(): cm to the sideslinePosition(): where the line is, −1 (left) to 1 (right), ornullmillis(): milliseconds since Runprint(value): show a message belowsetup()runs once;loop()runs 50 times a second
Write the codeEasy
Implement the pseudocode above in the simulator.
if (distance() < 30) motors(50, -50); else motors(35, 35);
Draw the flowchartMedium
Draw a flowchart for a night light: read the light level; if it’s dark, LED on; otherwise LED off; repeat.
Plan a parking robotHard
Write pseudocode for a robot that drives forward, slows down below 50 cm, stops at 10 cm, beeps three times and then waits.
Show an answer
forever: d = read distance if d > 50: drive fast else if d > 10: drive slow else: stop repeat 3 times: beep wait foreverQuick check
Finished this lesson?