Weekly Quizzes — W09 to W12

10 questions each · ~15 min each · attempt ALL ten before opening the key · ← W05–W08 · Hub · W13–W16 →


W09 — Arrays & vectors (Week 9)

Q1. [Easy] int a[5]; creates…

Q2. [Easy] The first element of int a[4] is…

Q3. [Easy] Which is true about vector<int> compared to a C array?

Q4. [Medium] What does this print?

int a[3] = {10, 20, 30};
cout << a[1] + a[2];

Q5. [Medium] What happens with int a[3]; cout << a[3];?

Q6. [Medium] What does this print?

vector<int> v;
v.push_back(4);
v.push_back(9);
cout << v.size() << " " << v[0];

Q7. [Medium] Which range-based loop prints every element of vector<int> v?

Q8. [Medium] What does this print?

int a[4] = {5, 2, 8, 1};
int m = a[0];
for (int i = 1; i < 4; i++)
    if (a[i] > m) m = a[i];
cout << m;

Q9. [Hard] What does this print?

vector<int> v = {1, 2, 3};
for (int i = 0; i <= v.size(); i++)
    cout << v[i] << " ";

Q10. [Hard] Why do functions receiving C arrays also receive the length — void f(int a[], int n)?

W09 — Answer key

Q1 — b. One object, five same-type elements, indexed 0–4. Declaration size is fixed forever — hence vector later.

Q2 — b. Array indices start at 0; the last of four is a[3].

Q3 — b. vector manages its own dynamic storage — push_back grows it, size() reports it. That management is exactly what C arrays lack.

Q4 — b. a[1] is 20, a[2] is 30 → 50. Index arithmetic before anything else.

Q5 — b. a[3] is past the end. C++ performs no bounds checking on raw arrays — the access compiles and misbehaves at runtime. This is the module’s central safety lesson.

Q6 — a. Two push_backs → size 2; v[0] is the first pushed value, 4.

Q7 — a. for (int x : v) binds x to each element in turn. The syntax in (b) and (c) does not exist; (d) is another language.

Q8 — c. Seed-from-first max scan → 8. The same three-line pattern will become max_element in the STL module.

Q9 — b. i <= v.size() touches v[3] — one past the last valid index (2). Range-for exists precisely so this off-by-one cannot be written.

Q10 — b. Arrays decay to a pointer to their first element when passed; the size is not part of what arrives. Hence the length parameter — the pointer-plus-count convention used across all C-family APIs.


W10 — Searching & sorting (Week 10)

Q1. [Easy] Linear search on n elements examines, worst case,…

Q2. [Easy] Binary search’s essential precondition is…

Q3. [Easy] Which sort repeatedly swaps adjacent out-of-order pairs?

Q4. [Medium] Binary search on a sorted array of 16 elements examines at most…

Q5. [Medium] Searching for 7 in [2, 5, 8, 12, 16], binary search first compares 7 against…

Q6. [Medium] One pass of selection sort on [4, 1, 3, 2] (ascending, select-min) produces…

Q7. [Medium] What does this linear search return for key 9?

int a[5] = {3, 9, 1, 9, 4};
int pos = -1;
for (int i = 0; i < 5; i++)
    if (a[i] == key) { pos = i; break; }

Q8. [Medium] Bubble sort’s early-exit optimization stops when…

Q9. [Hard] What does this binary search print?

int a[5] = {2, 5, 8, 12, 16};
int lo = 0, hi = 4, key = 10;
while (lo <= hi) {
    int mid = (lo + hi) / 2;
    if (a[mid] == key) { cout << "at " << mid; return 0; }
    if (key < a[mid]) hi = mid - 1; else lo = mid + 1;
}
cout << "missing";

Q10. [Hard] Sorting student records by marks descending, then name ascending on ties, needs…

W10 — Answer key

Q1 — b. Linear search stops early only when lucky; the worst case (absent key) examines all n. That linearity is its defining cost.

Q2 — b. Halving the search space is only valid if the middle comparison tells you which half to discard — which requires order. Unsorted input makes binary search silently wrong.

Q3 — b. Bubble sort’s pass compares neighbors and swaps inversions, bubbling the largest to the end each pass.

Q4 — c. Each probe halves the space: 16→8→4→2→1 — at most 5 probes. The logarithm in action; 1,000,000 elements need ≤ 20.

Q5 — c. lo=0, hi=4 → mid=2 → a[2]=8. The first comparison is always against the middle; 7 < 8 discards the right half immediately.

Q6 — a. Pass 1 selects the minimum (1) and swaps it with position 0. One pass fixes one position — that is selection’s contract.

Q7 — b. The break returns the first match. Without the break, pos would end at 3 — the last. Sentinel-initialized to −1 means “absent.”

Q8 — b. Zero swaps in a pass means every adjacent pair is ordered — proof of sortedness. This is bubble’s one adaptive virtue.

Q9 — b. Trace: mid=2 (8<10→lo=3), mid=3 (12>10→hi=2), lo>hi → exit → missing. The loop terminates because the window shrinks every pass.

Q10 — b. Composite comparisons — primary key, tie-breaker — on records: one swap moves all fields together. Sorting parallel arrays separately destroys the record alignment.


W11 — Strings & text processing (Week 11)

Q1. [Easy] Which reads a full line including spaces?

Q2. [Easy] For string s = "Hello";, s.size() is…

Q3. [Easy] s[0] for s = "Hello" is…

Q4. [Medium] What does this print?

string a = "data", b = "base";
cout << a + b;

Q5. [Medium] What does this print?

string s = "banana";
cout << s.substr(1, 3);

Q6. [Medium] Comparing strings with == compares…

Q7. [Medium] What does this print?

string s = "hello";
s[0] = 'H';
cout << s;

Q8. [Medium] Which counts vowels in s (lowercase input)?

Q9. [Hard] What does this print?

string s = "abc";
for (size_t i = 0; i < s.size(); i++)
    cout << (char)toupper(s[i]);
cout << "|" << s;

Q10. [Hard] After int n; cin >> n; getline(cin, line); with input 42 then hello world, line is…

W11 — Answer key

Q1 — b. getline reads to the newline and consumes it. >> stops at the first space.

Q2 — b. Five characters. size() returns the count; the last valid index is 4.

Q3 — a. Indexing yields a char — single quotes in the answer, and the first index is 0.

Q4 — b. + concatenates: no space is inserted unless you write one.

Q5 — a. substr(1, 3) = 3 characters starting at index 1: a, n, a. The second argument is a length, not an end index — the standard confusion.

Q6 — b. std::string’s == is value equality — the content. (C-style char* comparison compares pointers — a Week-11 contrast.)

Q7 — b. std::string is mutable: writing s[0] replaces the character.

Q8 — b. Each comparison must name s[i]. Option (a) parses as (s[i] == 'a') || 'e' || ... — 'e' is truthy, so every character “counts.” The most reused bug in student text-processing code.

Q9 — a. toupper(s[i]) returns a transformed value; unless it is assigned back, s is untouched. Transform-to-output vs modify-in-place are different programs.

Q10 — b. The mixing trap, third appearance: >> leaves the newline, getline is satisfied by it instantly. One cin.ignore() between them fixes it — now by reflex, one hopes.


W12 — File I/O (Week 12)

Q1. [Easy] Which opens a file for reading?

Q2. [Easy] ofstream out("log.txt", ios::app); means…

Q3. [Easy] After opening a file, the first thing to check is…

Q4. [Medium] The read loop while (in >> x) { ... } stops when…

Q5. [Medium] What does getline(in, line) return as a loop condition?

Q6. [Medium] Writing with out << 42 << "\n"; produces…

Q7. [Medium] marks.txt holds Ayesha 88\nBilal 72\n. What does this print?

ifstream in("marks.txt");
string name; int m;
while (in >> name >> m)
    cout << name << "-" << m << " ";

Q8. [Medium] A program should read scores.txt, compute the average, then overwrite the file with the average. The safe sequence is…

Q9. [Hard] ifstream in("ghost.txt"); if (!in) { ... } — the check exists because…

Q10. [Hard] A CSV line Ali Raza,88 is read with getline(in, line). Extracting the marks requires…

W12 — Answer key

Q1 — b. ifstream = input file stream (reading); ofstream = output (writing). The names are the mnemonic.

Q2 — b. ios::app positions every write at the end, preserving prior content. Plain ofstream out("f") truncates — the data-loss footgun.

Q3 — b. Stream state after construction tells you whether the open worked. The missing-file program that “runs” is the silent failure this check prevents.

Q4 — b. The extraction operator converts into a boolean: success. Failure — EOF or garbage — ends the loop. Read-until-fail is the file twin of the sentinel loop.

Q5 — b. getline returns the stream reference; in a condition it converts to success/failure. The line itself arrives in the second argument.

Q6 — a. Output streams format values to text exactly as cout does — the same operators, different destination.

Q7 — a. >> skips whitespace including newlines, so name/marks pairs read across line boundaries until the data ends.

Q8 — b. Read-then-close-then-rewrite: one mode at a time, with the data safely in memory before the destructive truncating open. Interleaved read/write on the same stream is an advanced, error-prone pattern.

Q9 — b. C++ streams fail quietly. The if (!in) guard converts “no file” from silent-empty into an explicit, handled event.

Q10 — b. Fields with spaces force line-grain reading and explicit splitting. stoi converts the marks substring; finding one comma when names contain commas is the stated extension (hint: rfind).


Next: W13–W16 — Memory, OOP, capstone → · Hub