π
STUDENT NOTES Β· C & C++ WEEK 2 OF 8
Loops & Functions, C Style π
The logic you know from Python β wearing C's armor: brackets, braces and types everywhere.
1The C for loop β three instructions in one line
βοΈ
Chip: for (start; keep-going-while; step) β where the counter begins, when to stop, how to move. All the loop's rules up front.
2Loops doing real work
3while β repeat until the test fails
π
Bugly: Forget count-- and the countdown never ends. Some traps are universal. Hehehe.
4Functions β with type name tags
π¦
Professor Hoot: int add(...) promises: this function returns an int. C checks that promise at compile time β no surprises later.
5Recursion β the function that calls itself
βοΈ
Chip: fact(4) = 4 Γ fact(3) = 4 Γ 3 Γ 2 Γ 1 = 24. It dives down to the base case (n <= 1), then multiplies its way back up.
6Quick quiz! π§
for (int i = 0; i < 3; i++) β how many times does the body run?
π‘ i takes 0, 1, 2 β three rounds. Stops when i < 3 fails.
void as a return type meansβ¦
π‘ void = "expect nothing back". Like Python functions without returnβ¦ but declared honestly up front.
7Your mission π
Mission 1: Print the table of any number using a for loop.
Mission 2: Write int square(int x) and print square(9).
Mission 3: Write a countdown from 10 that ends with "LIFTOFF!" β using while.
Week 2 complete β loop commander! π
Next: arrays and strings β and C's famous missing seatbelts.
Go to Week 3: Arrays & Strings β