41039 · Programming 1
Weeks 2 & 3 · 41039 Programming 1

Choosing and Repeating

Week 1 gave you state — a program that runs top to bottom and does the same thing every time. These two weeks add the other two tools: branching, so a program can choose, and repetition, so it can do something a thousand times without you typing it a thousand times. Then the structures worth repeating over: arrays, lists, dicts, sets and tuples.

Labs start · Week 2 11 Ed lessons · ~4 hours Lecture slides (PDF) Java Python
Weeks 2 & 3 · Interactive

The lecture, then the practice

Choose a section from the list to open it — or use the arrow keys once the list has focus. Code blocks are live: edit them, run them, and break them on purpose. Several of them below are meant to fail — read what the compiler says before you fix them.

01Types, booleans and expressions

1.1Java is strongly, statically typed

Variables have types, data has types, and those types must be compatible and known at compile time. Week 1 showed you one kind of type error. There are others, and they all arrive before the program ever runs.

Two errors from one run. That is normal — the compiler reports everything it can find, so always start reading at the first one.

1.2It is not only variables that have a type

  • Methods have a return type. That void in public static void main means “returns nothing”.
  • Expressions have a type — the type of the value they evaluate to. The expression 10 + 3 has type int.

So int i = 10 + 3; is fine and boolean b = 10 + 3; is not. Run it and read the two types the error names.

Why this matters later

Because expressions have types, you can use one anywhere a value of that type is expected. That sounds obvious. It is the reason a whole comparison can be handed straight to an if, stored in a variable, or returned from a method.

1.3boolean is its own type

Java has a boolean type for every true/false value, and it is not compatible with the numeric types. Other languages disagree. This is valid C++:

bool b = true;
int i = 10 + b;   // i is 11 — fine in C++

The Java equivalent will not compile at all.

xkcd comic: a REPL in an invented language returning absurd results for expressions that mix types
xkcd 1537, Types (2015) — Randall Munroe, CC BY-NC 2.5
A trade, not a flaw

C++ lets you write shorter code and lets a typo compile. Java refuses the shortcut and catches the typo. Neither is “right” — but you should know which one you are typing into.

Did you know?

The type is named after a person. George Boole published An Investigation of the Laws of Thought in 1854, arguing that logic could be done as algebra — with values that are only ever true or false. There were no computers to apply it to. Eighty-three years later a 21-year-old master’s student, Claude Shannon, noticed in his 1937 MIT thesis that Boole’s algebra described exactly what a circuit of relay switches does — and the two halves of your boolean finally met. Source: Wikipedia — A Symbolic Analysis of Relay and Switching Circuits.

Engraved portrait of George Boole, the mathematician who devised Boolean algebra
Portrait: Unknown author, 1864 · public domain

1.4The operators that produce a boolean

A lone boolean is dull. They become useful as the type of a whole expression, built with these:

OperatorMeansTakes
< <= > >=less / less-or-equal / greater / greater-or-equaltwo numbers
==equal to — note the two equals signstwo of any type, though only some pairings are useful
!=not equal toas above
&&and — true only when both sides are truetwo booleans
||or — true when either side is truetwo booleans
!not — flips true and falseone boolean
xkcd comic: a driver takes a conditional statement absolutely literally
xkcd 1033, Formal Logic (2012) — Randall Munroe, CC BY-NC 2.5
The classic typo

= assigns. == compares. In Java, writing if (x = 5) is usually caught, because the assignment’s type is int and an if needs a boolean — the type system saving you again. In C the same line compiles and has ruined many afternoons.

These combine, as long as the types line up. Enter 15, then try 7:

03 · These two weeks

What to actually do

On Ed, work through the eleven Week 2 and 3 lessons. They interleave the two languages deliberately — this order matches the sections above:

  1. Booleans and Conditional Statements — Or — How to Choose in Java
  2. Conditional Statements in Python
  3. Loops in Java 1 — while, for, for-each, do-while
  4. Loops in Java 2 — nesting, break, continue
  5. Loops in Python 2 — break, continue, loop-else
  6. Arrays in Java
  7. Lists in Python
  8. Dictionaries, Sets and Tuples in Python
  9. Bundling Data Together in Java — your first taste of a class
  10. Java Trivia, Tidbits and Tables — reference, skim it
  11. A Python Miscellany — reference, skim it
The last two are not readings

They are operator tables. Skim them once so you know what is in them, then come back when you meet a symbol you do not recognise. Both are reproduced in M1 on this page, side by side.

Labs have started

Assessed lab exercises are due 11:55pm the Monday of the following week, with unlimited attempts — but you must pass all test cases in an exercise to get its marks. Canvas → Assignments is authoritative for what is due and when; where this page differs, Canvas and the announcements win.

If you only do one thing

Predict the output of every runnable block on this page before you press Run. Being wrong and finding out immediately is the fastest form of learning available to you, and it is free.

Coming up in Week 4: methods, functions and records — plus the first code comprehension check.

Sources

Everything cited on this page

The lecture content comes from the Week 2 and 3 lessons on Ed. The links below are for the claims this page adds around them — checking a source yourself is a better habit than trusting any lecture slide, including ours.

Documentation

Quotations

Every quotation on this page was checked against a primary source — the original paper, book or message, not a quotation website.

Used inSource
2.2, 6.3Brian W. Kernighan & P. J. Plauger, The Elements of Programming Style, 2nd ed., McGraw-Hill, 1978 — “Take care to branch the right way on equality” (ch. 6), “Write clearly — don’t be too clever” (the book’s first rule), “Let the machine do the dirty work”
5.1, 6.1Ada Lovelace, Note E of the Translator’s Notes to L. F. Menabrea, Sketch of the Analytical Engine, Scientific Memoirs vol. III, 1843, p. 716
5.5Alfred North Whitehead, An Introduction to Mathematics, 1911, ch. V
8.2, 8.7, M3.2C. A. R. Hoare, The Emperor’s Old Clothes, 1980 ACM Turing Award Lecture, Communications of the ACM 24(2), February 1981, pp. 75–83
8.2Jon Bentley, Programming Pearls: Writing Correct Programs, Communications of the ACM 26(12), December 1983, pp. 1040–1045
10.1Rob Pike, Notes on Programming in C, Rule 5, 21 February 1989
11.3Linus Torvalds, message to the git mailing list, 27 July 2006

Comics

All by Randall Munroe, xkcd.com, used under CC BY-NC 2.5: 292, 676, 710, 1033, 1185, 1195, 1205, 1411, 1537, 1652, 2200, 2248, 3062.

Photographs

From Wikimedia Commons, reused under the licence each one names. Author and licence come from the Commons API rather than from anyone’s memory — see media/fetch-photo.py.

ImageSource
ascii-chartUSASCII code chart — An unknown officer or employee of the United States Government, 1967 · public domain
corrado-bohmCorradoBoemETAPS2013 2013-03-22 0.33.36 — Carbonem, 2013 · CC BY-SA 4.0
joshua-blochJoshua Bloch at JavaOne 2005 (cropped) — Billy Bob Bain, 2005 · CC BY 2.0
athletics-lanesAthletics track start line numbers 1, 2, 3 — Santeri Viinamäki, 2016 · CC BY-SA 4.0
card-catalogWooden Card Catalog Furniture — MarkBuckawicki, 2018 · CC0
conveyorConveyor system in a factory — falco, 2015 · CC0
fence-postsPost and rail fence, Bishopstone - geograph.org.uk - 1009517 — Trish Steel, 2008 · CC BY-SA 2.0
george-booleGeorge Boole color — Unknown author, 1864 · public domain
po-boxesPO boxes at the historic Chico Post Office (2024)-L1005460 — Frank Schulenburg, 2024 · CC BY-SA 4.0
railway-turnoutTreskensväxel vid Jenny — Mikael Johansson, 2006 · CC BY-SA 3.0
tally-counterHand tally and knitting row counter 007 — Storye book, 2010 · CC BY 3.0
bentleyJon Bentley informaticien — Wikimedia Commons, 2013 · CC BY-SA 4.0
dijkstraEdsger Wybe Dijkstra — Hamilton Richards, 2002 · CC BY-SA 3.0
hoareSir Tony Hoare IMG 5125 — Rama, 2011 · CC BY-SA 2.0 fr
kernighanBrian Kernighan in 2012 at Bell Labs 1(cropped) — Ben Lowe, 2012 · CC BY 2.0
lovelaceAda Lovelace daguerreotype by Antoine Claudet 1843 - cropped — Antoine Claudet, 1843 · public domain
pikeRob-pike-oscon — Kevin Shockey, 2010 · CC BY 2.0
torvaldsLinuxCon Europe Linus Torvalds 03 (cropped) — Krd (photo) Von Sprat (crop/extraction), 2014 · CC BY-SA 4.0
whiteheadANWhitehead — unknown, 1923 · public domain

Articles, papers and notes

Used inSource
5Alan J. Perlis, Epigrams on Programming, ACM SIGPLAN Notices 17(9), September 1982
6.3The International Obfuscated C Code Contest, running since 1984
1.3Claude E. Shannon, A Symbolic Analysis of Relay and Switching Circuits, MIT master’s thesis, 1937 — and George Boole, An Investigation of the Laws of Thought, 1854
2.2Fortran — the three-way arithmetic IF, and the logical IF in FORTRAN IV (1962)
3.1ASCII (history) — the 1963 decision to place the cases one bit apart
5.1The structured program theorem — Corrado Böhm & Giuseppe Jacopini, 1966
8.2Joshua Bloch, Extra, Extra — Read All About It: Nearly All Binary Searches and Mergesorts are Broken, Google Research blog, 2 June 2006
10.2What’s New In Python 3.7 — dict insertion order becomes part of the language spec
M2.1E. W. Dijkstra, Why numbering should start at zero (EWD 831), 11 August 1982
M2.2Duff’s device — Tom Duff, Lucasfilm, 1983
M3.1E. W. Dijkstra, Go To Statement Considered Harmful, Communications of the ACM 11(3), March 1968, pp. 147–148