CS U111 · Mid-sem prep · Breadth
Lectures 1–10, the breadth checklist
For each lecture: the facts and terms worth being able to say out loud, a link to the page that teaches each one, and two or three multiple-choice self-tests. All of it comes from the lecture decks themselves.
The syllabus, as posted: "Lectures: Until recursion, except slide number 21 in the recursion deck. Labsheets: Until labsheet 5a. Conceptual and breadth coverage is expected for the lecture portion, and depth coverage is expected for the labsheets portion."
So this page is the lecture half: breadth, which mostly means multiple-choice questions. Lecture 10 is recursion, and its slide 21 (Recursion on Arrays, the sumArrayHelper example) is excluded. The depth half is labs 1–5a: Lab 4, Lab 5a and the write-a-program routine.
Lectures 1–4 are where nobody has an advantage. The material on computational thinking, input → process → output, flowcharts and pseudocode is this course's own. A JEE background doesn't cover it, and none of the past papers on the site asked about it, because they come from the old course. That's why those four lectures get the fullest treatment below. Reading them once carefully is enough.
From the instructors' slides, Important Instructions for the Mid-Semester Examination. They warn that "failure to follow the instructions will lead to non-evaluation":
- Two parts. Part I is MCQ on an OMR sheet. Part II is written answers on a separate answer sheet. Both sheets are attached at the end of the booklet, so detach them carefully without tearing them.
- ID on both sheets, as 8 digits: the 8 digits in the BITS ID with the letters dropped (2026A7PS1234H → 20261234). Mark each digit with a cross (×) in its box. Don't tick or shade.
- To change an MCQ answer, completely fill the old box, then cross the new one. Make no stray marks anywhere: the sheets are scanned by machine.
- A rough-work booklet is provided and is not evaluated. At the end, hand in the OMR sheet, the Part II sheet and the rough booklet. You keep the question paper.
- The marks split and any negative marking aren't stated. Read the cover of the paper before guessing. Past papers in this course family used −25% and −0.5 per wrong answer.
- 1 · Computational thinking
- 2 · Algorithms → C
- 3 · Bits & number systems
- 4 · Flowcharts
- 5 · Conditionals
- 6 · Loops
- 7 · Functions
- 8 · Arrays
- 9 · Strings
- 10 · Recursion
- Slide corrections
How to use it (about 60–75 minutes in total). For each lecture, read the checklist and tick a box only if you could explain that point to a friend without looking. Then do the self-tests before opening them. Only open the linked page for the points you couldn't tick. If time is short, do lectures 1–4 and 10 first: those are the parts with no other page to rely on.
Lecture 1 · Computation & computational thinking
Deck: 20 slides · reading Beecher ch. 2–3 · no other page on this site covers this lecture, so everything you need is below
- Computational problem: a problem stated as input, a relationship between input and output, and output. The slide's example: input = names, relationship = alphabetical ordering, output = sorted names.
- Not every real-world task is immediately a computational problem. "Sorting marks" and "finding the shortest route" have a precise input→output relationship. "Choosing a birthday gift" or "making tea" don't, until someone makes them precise.
- Every computational problem has structure, the IPOS model: Input, Process, Output, Storage. ATM example: input = card, PIN, amount; process = authenticate, check balance, deduct, dispense; output = cash, receipt; storage = updated balance, transaction history.
- Computational thinking (adapted from Jeannette Wing): "the thought process involved in formulating problems and expressing their solutions so that they can be effectively carried out." It's about thinking, not just programming, and it transfers to any field.
- The four pillars: Decomposition (e.g. organising a college festival), Pattern recognition (spam detection), Abstraction (Google Maps), Algorithm design (a cooking recipe). Learn the slide's example for each pillar, because MCQs like to ask that pairing.
- The pipeline: real-world problem → computational problem → algorithm → program → software. Programming is only one step of this. The slide marks the program step as where AI can help, and says AI is most useful after the problem is understood.
- AI's role, according to the course: AI can write code, explain syntax, suggest algorithms and debug simple errors. You still define the problem, decide what to build, judge whether a solution fits, and think critically. "AI can accelerate, but not entirely replace."
Check yourself (1 of 3)
In the IPOS model of an online food order, "order history and delivery records" belong to which part?
- Input
- Process
- Output
- Storage
(d) Storage. They're kept for later, not shown to the user right now. The slide lists restaurant, items and address as input; search, estimate, assign rider and payment as process; and confirmation and ETA as output.
Check yourself (2 of 3)
Spam detection in Gmail is the slide's everyday example of which pillar?
- Decomposition
- Pattern recognition
- Abstraction
- Algorithm design
(b) Pattern recognition. Spam shares recognisable features. Keep the slide's pairs straight: festival → decomposition, Google Maps → abstraction (it shows roads and hides everything else), recipe → algorithm design.
Check yourself (3 of 3)
Which statement matches the course's view of where programming sits?
- Programming is the first step: write code, then understand the problem
- Programming is one step in a pipeline that starts with turning a real-world problem into a computational one
- With AI, the algorithm step is no longer needed
- Software and algorithms are the same thing
(b). The pipeline is real-world problem → computational problem → algorithm → program → software. In the course's words, "programming is a means of expressing computational solutions, not an end in itself."
Lecture 2 · From algorithms to C programs
Deck: 29 slides · taught on this site in the operators & I/O lesson and the Mac setup guide (compile-run loop)
- The compiler translates; the CPU executes. The CPU can't run C directly. It runs machine instructions, which the compiler produces from your C program. setup guide
- What the compiler does, according to the slide: lexical analysis → syntax checking → code generation → executable. It checks that the program follows C's rules before making an executable.
- The Linux workflow:
nano hello.c(edit) →gcc hello.c -o hello(compile) →./hello(execute). Creating a program and running it are separate steps, and programming is a write–compile–run–fix loop. - The parts of a first program:
#include <stdio.h>(the standard I/O library),main()(the entry point),printf(output),return 0;(successful completion). - The three error kinds on the slide: a syntax error breaks C's rules (a missing semicolon). A compilation error means it can't be compiled (an undeclared variable). A runtime error compiles but fails while running (division by zero). Syntax errors are caught at compile time too.
- A variable is a named location in memory. A declaration (
int age;) reserves the memory and fixes the type. The four basic types areint,float,char,double. =is assignment, not mathematical equality.age = 20;replaces the old value. operators lesson §1- Precedence:
( )first, then* / %, then+ -. So2 + 3 * 4= 14 and(2 + 3) * 4= 20. - Integer division drops the fraction:
5 / 2= 2 and5 % 2= 1, but5.0 / 2=5 / 2.0= 2.5. That's why the temperature program uses9.0 * c / 5, and why(float)a / bkeeps the fraction. operators lesson §2 scanf("%d", &age):%dmeans an integer, and&agemeans "store it inage".printf("Age = %d\n", age)displays it.
Check yourself (1 of 3)
The slide's end-of-lecture activity, with int a = 10, b = 3;. What do printf("%d\n", a / b); printf("%d\n", a % b); printf("%.2f\n", (float)a / b); print?
- 3.33, 1, 3.33
- 3, 1, 3.33
- 3, 0, 3.00
- 3, 1, 3.00
(b) 3, 1, 3.33 (compiled to check). (float)a converts a to 10.0 before the division, so the fraction is kept. Compare (float)(a / b), which divides first and gives 3.00.
Check yourself (2 of 3)
A program compiles cleanly, then stops partway through with a division by zero. According to the lecture, that is a…
- syntax error
- compilation error
- runtime error
- logic error caught by the compiler
(c) runtime error. It compiles and fails during execution. A missing semicolon is the slide's syntax-error example, and an undeclared variable is its compilation-error example.
Check yourself (3 of 3)
Which command produces an executable called hello from hello.c?
./hello.cgcc hello.c -o hellonano hellogcc hello -o hello.c
(b). -o names the output file. Then ./hello runs it, and nano just edits a file. Option (d) has the names backwards and would try to overwrite your source file.
Lecture 3 · Bits, bytes & number systems
Deck: 28 slides · reading Hanly & Koffman ch. 1 · the conversions are drilled on the number systems drill (methods 1–5)
- Why binary: hardware can reliably tell two states apart (off/on). With 10 voltage levels, noise blurs neighbouring levels together. Binary needs more digits but gets the widest safety margin per digit.
- A bit is one binary digit. A byte is 8 bits. The slide's scale is kB = 210 bytes = 1024, MB = 210 kB, GB = 210 MB (see the note on kB).
- Binary → decimal: add up the place values (128, 64, …, 2, 1) wherever there's a 1. 01011001 = 64+16+8+1 = 89. After the point, the place values are ½, ¼, ⅛: 101.101 = 5.625. method 3
- Decimal → binary: divide by 2 repeatedly and read the remainders bottom → top. For a fraction, multiply by 2 repeatedly and read the integer parts top → bottom. Some decimals, such as 0.1, never end in binary. That's why floating-point results can look slightly off. methods 1–2
- Binary arithmetic: 1 + 1 = 10 (carry 1), e.g. 1011 + 0110 = 10001 (11 + 6 = 17). Subtraction borrows. Multiplication is just shifting and adding.
- One's complement flips every bit (−5 = 11111010), but it has two zeros (00000000 and 11111111). Two's complement flips every bit, then adds 1 (−5 = 11111011). It has one zero, and it's what hardware actually uses. method 5
- Subtraction becomes addition: A − B = A + (two's complement of B), and any carry out of the 8th bit is thrown away. Example: 12 − 5 → 00001100 + 11111011 = 1 00000111 → 7. So hardware needs only an adder.
- Hexadecimal: each 4-bit group (a "nibble") is one hex digit, so 0101 1001 = 0x59 = 89. Hex is for human convenience only. The machine still stores binary. method 4
- ASCII: characters are stored as numbers by agreement. 'A' = 65, 'a' = 97, '0' = 48, space = 32, so "Hi!" is stored as 72, 105, 33. operators lesson §7
- Signed vs unsigned 8-bit: unsigned holds 0 to 255, and signed holds −128 to 127. Overflow wraps around silently: an
unsigned charholding 255, plus 1, becomes 0. Sizes on the slide:char1,int4,float4,double8 bytes (system-dependent, so check withsizeof). Floats use the IEEE 754 standard (you only need the name).
Check yourself (1 of 3)
What is −5 in 8-bit two's complement?
- 10000101
- 11111010
- 11111011
- 00000101
(c) 11111011. 5 = 00000101. Flipping the bits gives 11111010, and adding 1 gives 11111011. Option (b) is the one's complement, which is the trap. (a) is "sign bit + magnitude", a scheme the lecture doesn't use.
Check yourself (2 of 3)
The slide's activity: an unsigned char holds 250. What does it show after adding 10?
- 260
- 4
- 255
- a compile error
(b) 4 (compiled to check). It can hold only 0–255, so 260 wraps around to 260 − 256 = 4. C doesn't stop you or warn you: "overflow wraps silently."
Check yourself (3 of 3)
The other activity questions: what is 200 in binary, and what is 11001 in decimal?
- 11001000 and 25
- 11000100 and 25
- 11001000 and 19
- 10011000 and 26
(a). 200 = 128 + 64 + 8 = 11001000, and 11001 = 16 + 8 + 1 = 25. From slide 16, for practice: 11010 = 26, 100101 = 37, 37 = 100101, 58 = 111010.
Lecture 4 · Flowcharts & algorithmic thinking
Deck: 15 slides · reading Beecher ch. 2–3 · no other page covers flowcharts or pseudocode, so the figures below are the reference
- An algorithm is a precise, step-by-step procedure with four properties: finite (it terminates), precise (each step is unambiguous), effective (each step can actually be carried out), and it has input & output. The slide's everyday examples are a recipe, driving directions and a knitting pattern.
- Decomposition, applied: computing a final grade splits into read scores → compute weighted average → determine letter grade → display result. Each piece is small enough to design on its own. In Lecture 7 each box becomes a function.
- Abstraction, applied:
sqrt()keeps the name, what goes in, and what comes out, and hides how the root is computed. You can use it without knowing its internals. - Pattern recognition gets no lecture of its own. The slide says it "will keep coming up naturally."
- The four flowchart symbols (figure below): oval = start/end, rectangle = process, diamond = decision (yes/no), parallelogram = input/output. Arrows (flow lines) connect them. Only the diamond creates branches.
- Sequence vs selection: in a sequence every step runs, one after another. In selection only one path runs, depending on the answer. (Lecture 6 adds the third shape: the loop, the first flow that goes backward.)
- The leap-year rule becomes three yes/no questions in order: divisible by 4? by 100? by 400? That's three diamonds.
- Pseudocode conventions:
BEGIN … END,INPUT x,OUTPUT x,x ← value(assignment),IF … THEN … ELSE … END IF, with indentation showing what's inside. A flowchart and pseudocode are two representations of the same algorithm. - Boundary thinking starts here: in the grade activity, is exactly 90 an A or a B? The rule has to say so, not the programmer's guess.
The same algorithm in the slide's pseudocode. The slide merges the first two diamonds into one compound condition:
BEGIN
INPUT year
IF year % 4 == 0 AND year % 100 != 0 THEN
OUTPUT "Leap Year"
ELSE IF year % 400 == 0 THEN
OUTPUT "Leap Year"
ELSE
OUTPUT "Not a Leap Year"
END IF
END
Check yourself (1 of 3)
In a flowchart, "Read the student's marks" goes in which symbol?
- Rectangle
- Diamond
- Parallelogram
- Oval
(c) Parallelogram. Reading a value in and displaying one out are both input/output. A calculation such as "compute the average" is a rectangle.
Check yourself (2 of 3)
The grade activity has five grades: A ≥ 90, B 80–89, C 70–79, D 60–69, F < 60. What is the fewest decision diamonds needed?
- 3
- 4
- 5
- 9
(b) 4. Ask ≥ 90?, ≥ 80?, ≥ 70?, ≥ 60? in order. The last "No" is F, with no question needed. In general, n outcomes need n − 1 questions. In C this is the else if ladder in Lecture 5, where F is the final else.
Check yourself (3 of 3)
"Keep asking until the instructions say stop, and if they never do, go on forever." Which algorithm property does this break?
- Finite
- Precise
- Effective
- Has output
(a) Finite. An algorithm must terminate after a finite number of steps. "Precise" means every step is unambiguous, and "effective" means every step can actually be done (for example, "list every real number" can't be).
Lecture 5 · Conditional statements in C
Deck: 22 slides · taught in depth on the operators & selection lesson and notes (Labs 1–3 depth)
- Relational operators (
== != > < >= <=) produce true or false. In C that's theint1 or 0. lesson §3 if/else: exactly one path runs, never both and never neither. A plainifjust skips its block when the condition is false.- Logical operators and truth tables:
&&needs both sides true.||needs at least one, so it's false only when both are false.!flips the value. short-circuit stepper - An
else ifladder checks conditions top to bottom and stops at the first true one. It compiles to the same decisions as a nestedif; it's just flatter. - Boundary cases:
score >= 90andscore > 90differ only at 90. Always ask what happens at the exact boundary value. - Default case: without a final
else, unmatched input silently does nothing. For example, with onlyif (score >= 60) grade = 'D';, a score of 40 leavesgradeunset. =vs==:if (x = 5)assigns 5 tox, and the condition is the value 5, which is nonzero and so true. clang warns: "using the result of an assignment as a condition without parentheses." (The slide says an assignment is "always true". It isn't: see the corrections.)- Dangling
else: anelsebelongs to the nearest unmatchedif, whatever the indentation suggests. The fix is to always use braces. notes trap table switchis for discrete exact values, not ranges.defaultis its catch-all. Withoutbreak, execution falls through into the next case: with grade 'A', the slide's code prints "Excellent" and "Good".
Check yourself (1 of 3)
With int a = -1, b = 5;, what does this print?
if (a > 0)
if (b > 0)
printf("both positive\n");
else
printf("a is not positive\n");
- a is not positive
- both positive
- nothing
- compile error
(c) nothing (compiled to check, and clang warns "add explicit braces to avoid dangling else"). The else belongs to if (b > 0). Since a > 0 is false, the whole inner if-else is skipped.
Check yourself (2 of 3)
Which is the best tool for "price depends on whether age < 12, age ≥ 65, or otherwise"?
switch (age)with three cases- an
if / else if / elseladder - three separate
switches - a
do-while
(b). These are ranges, and switch matches only exact values. That's the Lecture 5 rule: if-else for ranges and compound conditions, switch for discrete values.
Check yourself (3 of 3)
P || Q is false when…
- P is false
- exactly one of P and Q is false
- both P and Q are false
- both P and Q are true
(c). Only one row of the truth table makes || false: the one where both are false.
Lecture 6 · Repetition: loops in C
Deck: 23 slides · taught on the loops lesson and notes, with Lab 4 worked (depth) and the loops drill
- The loop is the first flowchart shape that goes backward: the body runs, then control goes back up to re-check the condition. The "false" exit is the only way out.
whilechecks first, so its body may run zero times.do-whilechecks last, so its body runs at least once. Note the semicolon in} while (cond);. loops lesson- The natural use for
do-whileis input validation: you have to ask at least once before you can check the answer. - In
for (init; condition; update): the init runs once, the condition is checked before every iteration, and the update runs after every iteration. for-stepper - Which loop to choose:
forwhen you know roughly how many times,whilewhen the count depends on a condition,do-whilewhen the body must run at least once. Any of them can solve the same problem. - Nested loops: the inner loop runs to completion for every outer iteration. 3 × 3 gives 9 stars, and a 5 × 5 table gives 25 products.
- Infinite loop: forget the update (
i++) and the condition never becomes false. - Off-by-one:
i < 5from 0 runs 5 times, buti <= 5runs 6 times. Check both ends. breakleaves the loop entirely.continueskips the rest of this iteration only. So the slide's loop thatcontinues on eveniprints 1 3 5 7 9.
Check yourself (1 of 3)
With int i = 10;, what does do { printf("%d\n", i); } while (i <= 5); print?
- nothing
- 10, once
- 10 forever
- 5 6 7 8 9 10
(b) 10, once. The body runs before the first check, and then 10 <= 5 is false. The same code as a while loop prints nothing. (It isn't an infinite loop, because the condition is false on the first check.)
Check yourself (2 of 3)
How many times does printf("*") run in for (r = 1; r <= 4; r++) for (c = 1; c <= r; c++) printf("*");?
- 4
- 8
- 10
- 16
(c) 10, which is 1 + 2 + 3 + 4, because the inner loop's limit depends on r. That's the staircase pattern, a past-paper favourite. Only when the inner limit is fixed is the count rows × columns.
Check yourself (3 of 3)
Which statement about continue is true?
- It exits the loop immediately
- It skips the rest of the current iteration, and the loop goes on
- It restarts the loop from its first iteration
- It only works inside
switch
(b). (a) describes break. In a for loop, continue still runs the update before re-checking the condition.
Lecture 7 · Functions in C
Deck: 21 slides · taught on the functions lesson and notes · Lab 5a (depth): every problem worked
- A function is a black box: arguments go in, a return value comes out, and the inside is hidden. That's abstraction from Lecture 4. Writing a formula once and calling it many times means there's only one place to fix it.
- Top-down design: each decomposition box from Lecture 4 becomes a function, so
main()reads as a summary of the whole program. - Anatomy: return type, name, parameter list, body, and
return. Example:int add(int a, int b) { … return sum; }. lesson - Calling a function: the caller pauses, control jumps to the function with the parameters set, the body runs,
returnhands the value back, and the caller resumes where it left off. Nothing runs in parallel. call-stepper returnboth sends a value and ends the function. Code after it is "dead code" that never runs. (clang with-Wall -Wextradoesn't warn about it, just as the slide says.)- Declaration (prototype) vs definition: the prototype
int add(int a, int b);ends in a semicolon and has no body. It promises the compiler that the function exists. Without it, calling a function defined belowmainis an error in clang: "call to undeclared function." voidfunctions perform an action and return no value. They don't needreturn, thoughreturn;can exit one early.- Pass by value: the function gets a photocopy of the argument. So in
modifyValue(a), settingx = 100leavesaat 10. C has no pass-by-reference: the workaround is pointers, which come later. - Scope: local variables live only inside their own function, so two functions can each have their own
x. Globals are visible everywhere but dangerous: they make debugging hard, a local with the same name shadows them, and they break modularity. Use them only for true constants. - No nested function definitions in standard C. clang reports "function definition is not allowed here". GCC allows them as a non-standard extension.
Check yourself (1 of 3)
What does main print?
void modifyValue(int x) { x = 100; }
int main(void) { int a = 10; modifyValue(a); printf("%d\n", a); }
- 100
- 10
- 0
- garbage
(b) 10. x is a separate copy, and changing the copy never touches a. That's pass by value, the photocopy analogy.
Check yourself (2 of 3)
Which line is a function declaration (prototype)?
int add(int a, int b) { return a + b; }int add(int a, int b);add(5, 3);int r = add(5, 3);
(b). It has a semicolon and no body. (a) is the definition, and (c) and (d) are calls.
Check yourself (3 of 3)
A global int count = 5; exists, and inside f() you write int count = 0; count++;. After f() returns, what is the global count?
- 6
- 1
- 5
- 0
(c) 5. The local count shadows the global, so count++ changes only the local, which is destroyed when f returns. This is the "variable shadowing" danger from slide 18.
Lecture 8 · Arrays in C
Deck: 30 slides · taught on the arrays lesson and notes and the arrays ladder (this lecture is breadth only: Lab 6 is not in the mid-sem)
- An array is one name for many values of the same type.
int marks[5];gives 5 contiguous boxes, indexed 0–4. There is nomarks[5]. - C never checks bounds.
marks[5]compiles and runs, but reads whatever memory lies past the array. That's undefined behaviour, not a caught error. The usual cause isi <= sizewherei < sizewas meant. - Initialising:
int n[] = {10,20,30,40};sets the size to 4 for you.int z[100] = {0};makes every element 0.int n[];without an initializer is an error. - The traversal pattern:
for (i = 0; i < size; i++). Sum starts at 0, and min starts ata[0]with the loop fromi = 1. For the slide's marks, the sum is 393 and the average 78.60 (a(double)cast is needed, or the integer division gives 78). - The
sizeoftrick:sizeof(marks) / sizeof(marks[0])= 20 / 4 = 5 elements. (Inside a function it gives the wrong answer; see the notes.) - Linear search checks each element in turn, with
breakon a match and −1 for "not found". Binary search halves the range each step, but only on sorted data. It usesmid = left + (right − left) / 2, which avoids overflow. lesson - Frequency counting: a counter array
counts[5] = {0}with onecounts[k]++per element. - Bubble sort swaps out-of-order neighbours, so the largest value "bubbles" to the end each pass. Selection sort finds the minimum and swaps it to the front, with at most one swap per pass. sort-stepper
- 2D arrays:
grid[3][4]has 3 rows, 4 columns and 12 elements, written row index first. Traverse it with nested loops. A transpose isT[j][i] = A[i][j]. Matrix multiplication needs A's column count to equal B's row count, and uses three nested loops.
Check yourself (1 of 3)
Binary search for 85 in the sorted array {68, 72, 77, 85, 91}. Which index is checked first?
- 0
- 2
- 3
- 4
(b) 2, because mid = 0 + (4 − 0) / 2 = 2, which holds 77. Since 77 < 85, the search moves right: left = 3, mid = 3 holds 85, found. That's 2 steps.
Check yourself (2 of 3)
int marks[5] = {72, 85, 91, 68, 77}; printf("%d", marks[5]);: what happens?
- a compile error: index out of range
- it prints 77
- undefined behaviour: it compiles, and prints whatever is in that memory
- it prints 0
(c). C does no bounds checking. (clang does warn for a constant index like this one, but it still compiles.) The valid indices are 0–4.
Check yourself (3 of 3)
int grid[3][4]; has how many elements, and what does grid[1][2] mean?
- 7 elements, column 1 row 2
- 12 elements, row 1 column 2
- 12 elements, row 2 column 1
- 20 elements, row 1 column 2
(b). 3 × 4 = 12, and the row index always comes first.
Lecture 9 · Strings in C
Deck: 30 slides · taught on the strings lesson (input widget) and notes (four slide corrections) · breadth only
- A string is a
chararray ending in'\0', the null terminator, a byte with value 0. C has no built-in string type."Hi"takes 3 bytes, so size an array for at least length + 1. %sprints from the start up to'\0'.scanf("%s", name)takes no&(the array name is already an address) and stops at the first space. input widget- Reading a full line:
scanf("%[^\n]", s), a scanset meaning "read up to a newline".%[^,]stops at a comma, and%[0-9]takes only digits. After a%d, write" %[^\n]"with a leading space to eat the leftover newline.fgets(s, sizeof(s), stdin)is bounded but keeps the'\n'. - Never use
gets: it can't know the buffer size, it was removed in C11, and this kind of bug caused the 1988 Morris Worm.strcpy/strcatdon't check the destination size either. strlencounts the characters before'\0':strlen("Ada Lovelace")= 12. It returns an unsigned type, so print it with an(int)cast. lessona == bcompares addresses, so two arrays holding "Ada" are "Not equal". Usestrcmp(a, b) == 0. lesson- The
string.htoolkit:strlen,strcpy(dest, src)(copies the'\0'too),strcat(dest, src)(appends),strcmp(0 if equal). Thectype.htoolkit:isalpha,isdigit,toupper,tolower, which work on one character, so you write the loop. - The patterns: loop
for (i = 0; s[i] != '\0'; i++). To reverse in place, swapiwithlen − 1 − ifori < len/2. Count words with an in-word flag.strchr/strstrexist, but their return values need pointers.
Check yourself (1 of 3)
The user types Ada Lovelace. What does char name[20]; scanf("%s", name); printf("[%s]", name); print?
- [Ada Lovelace]
- [Ada]
- [Lovelace]
- [A]
(b) [Ada]. %s stops at the first whitespace. %[^\n] would capture the whole line.
Check yourself (2 of 3)
char g[] = "Hi";: what are sizeof(g) and strlen(g)?
- 2 and 2
- 3 and 2
- 3 and 3
- 2 and 3
(b) 3 and 2 (compiled to check). sizeof counts the '\0' box. strlen counts only the characters before it.
Lecture 10 · Recursion in C
Deck: 23 slides · reading Hanly & Koffman ch. 9 · taught on the recursion lesson and notes · slide 21 (Recursion on Arrays) is excluded from the mid-sem
- Recursion is when a function calls itself to solve a smaller instance of the same problem, as in f(n) = n × f(n − 1): 5! = 5 × 4!. Each call does one small piece and delegates the rest. lesson
- Two parts: the base case is the trivial version, solved directly. The recursive case does a little work and delegates a smaller call. "Always define your base case first."
- The recursive assumption, borrowed from induction: to design, write the base case, then trust that the smaller call works, then build on it. Trace only to debug. Example:
computePower(2, 5)= 32. - The call stack: each call gets its own stack frame with its own
n(pass by value). It doesn't overwrite the earlier one. In the winding phase, frames pile up as each call waits. In unwinding, the base case returns and each paused frame finishes. At the deepest point offactorial(3), 4 frames exist at once. - Three pitfalls: (1) no base case; (2) non-converging arguments, e.g.
n + 1moving away fromn == 0. Both cause a stack overflow (a crash with "Segmentation fault"), recursion's version of an infinite loop. (3) Forgettingreturnin the recursive case. clang warns "expression result unused" and "non-void function does not return a value in all control paths". (GCC's wording on the slide differs; same bug.) - Before vs after the call: code before the recursive call runs while winding, in descending order. Code after it runs while unwinding, in reverse.
confusingPrint(3)prints Winding 3, 2, 1, then Unwinding 1, 2, 3. - Recursion trees: Fibonacci makes two calls each time, so draw a tree. Evaluation goes depth-first, left to right.
fib(4)= 3, and computes fib(2) twice and fib(1) three times (9 calls in all). That redundant recomputation explodes as n grows. notes - Direct vs indirect (mutual) recursion:
isEvencallsisOdd, which callsisEven, and so on. Tail recursion: the recursive call is the very last action, as intailFactorial(n − 1, n * acc). Some compilers then reuse the frame (tail call optimisation). - Recursion vs iteration: iteration uses less memory and is usually faster, and its failure mode is an infinite loop. Recursion is often shorter and closer to the maths, but uses one frame per call, and its failure mode is a stack overflow. Use iteration for counting, totals and simple traversal. Use recursion when the problem is defined by a smaller version of itself (trees, folders, sequences, divide and conquer).
Check yourself (1 of 3)
The slide's in-class activity: what does mystery(5) return?
int mystery(int n) { if (n <= 1) return n; return mystery(n-1) + mystery(n-2); }
- 8
- 5
- 3
- it never stops
(b) 5 (compiled to check). It's Fibonacci: m(0)=0, m(1)=1, m(2)=1, m(3)=2, m(4)=3, m(5)=5. The base case is n <= 1, and both calls make n smaller, so it terminates.
Check yourself (2 of 3)
What does confusingPrint(2) print?
void confusingPrint(int n) {
if (n == 0) { return; }
printf("W%d ", n);
confusingPrint(n - 1);
printf("U%d ", n);
}
- W2 U2 W1 U1
- W2 W1 U1 U2
- W2 W1 U2 U1
- W1 W2 U2 U1
(b) W2 W1 U1 U2. Before the call it prints in descending order, while winding. After the call, it prints in reverse as the frames unwind, innermost first.
Check yourself (3 of 3)
Which function is tail-recursive?
return n * fact(n - 1);return fib(n - 1) + fib(n - 2);return tailFact(n - 1, n * acc);return 1 + count(n / 10);
(c). Nothing is left to do after the call returns, because the multiplication happened before the call. In (a), (b) and (d), a multiply or add is still waiting.
Slide corrections (checked with clang)
Where a slide says something that isn't quite right, here is the correct version, with the evidence. In the exam, give the correct answer. If an MCQ seems to hinge on one of these, write the assumption you made in Part II.
| Slide | Says | Actually |
|---|---|---|
L5 s15 (= vs ==) | "The result of an assignment is always true" | The value of an assignment is the value assigned. if (x = 5) is true because 5 is nonzero, but if (x = 0) is false (compiled: takes the else). The slide's real point, that you assigned when you meant to compare, still holds. |
| L10 s17 (mutual recursion) | "isEven(3) calls isOdd(2), which calls isEven(1), which calls isOdd(0) — true." | isOdd(0) returns false, and that false travels back up, so isEven(3) = false (0), which is right because 3 is odd. Compiled: isEven(3) = 0 and isOdd(3) = 1. Don't read the slide's "— true" as the answer. |
| L3 s5 (sizes) | kB = 210 bytes | That's the course's convention, so use 1024 in this exam. Strictly, the standard (SI) kB is 1000 bytes, and 1024 bytes is a kibibyte (KiB). |
| L3 s24 (type sizes) | char: −128 to 127 | True on her Mac (compiled: CHAR_MIN = −128), but whether plain char is signed is up to the compiler. signed char is −128…127 and unsigned char is 0…255 everywhere. |
| L8 s6 (out of bounds) | "…without ever crashing" | It's undefined behaviour, which can crash, print garbage, or seem to work. (Details in the arrays notes.) |
| L8 s21, s23 (sorting) | "sorted after 3 passes" / "sorted after 3 swaps" | The array's contents are sorted after 3, but the loops as written run 4 bubble passes and 4 selection swaps. The 4th selection swap swaps 85 with itself. If an MCQ asks how many times the code swaps, count what the code does. |
| L9 (four slides) | — | The trailing bytes of char g[6] = "Hi" are 0, not garbage. i <= strlen prints the '\0' and then stops. %s and %[^\n] need a width to be safe. strcmp returns a sign, not just 0. All four are explained in the strings notes. |
Also checked and correct as printed: L2's activity (3, 1, 3.33), L3's 12 − 5 two's-complement sum, 89 ↔ 01011001 ↔ 0x59, the overflow 255 + 1 → 0, L5's dangling else and fall-through outputs, L6's continue output and do-while, L7's clang errors for an undeclared function and a nested definition, L8's sum 393 and average 78.60, and L10's factorial(3) = 6, computePower(2,5) = 32, fib(4) = 3 with call counts fib(2)×2 and fib(1)×3, tailFactorial(3,1) = 6 and digitSum(123) = 6.
Don't read the textbook chapters cover to cover, and don't hunt for "C MCQ" sets online. They're full of pointer and printf-trivia questions this course hasn't reached. Breadth here means the decks, and this page is the decks. Spend any spare time on the depth half: Lab 5a and one past-paper program.