§ 01 — Computer Programming 2
This module preps you for both CP2 major exams. The prelim covers Lessons 1 to 3: Arrays in Depth, Strings and Character Arrays, and Pointers. The final covers Lessons 4 to 7 (Structures, File Handling, Recursion, Searching and Sorting) plus some cumulative review. This section and the two prelim mock exams below focus on Lessons 1 to 3.
Different professors shuffle the weights, but almost every CP2 prelim on arrays, strings, and pointers is built from the same four parts:
| Part | Format | Typical Weight | What It Really Tests |
|---|---|---|---|
| I | Multiple choice / identification | 25-30% | Rules: array parameters, strlen vs sizeof, what strcmp returns, the two meanings of * |
| II | Output tracing | 30-35% | Running loops over 1-D and 2-D arrays, string loops, and pointer arithmetic in your head |
| III | Find the error | 15-20% | Strings compared with ==, a missing '\0', an uninitialized pointer, int m[][] in a parameter |
| IV | Short programming | 20-25% | Writing a small function from memory: a search, a string function, a function with pointer parameters |
Tracing plus programming is usually more than half the exam. You cannot pass by memorizing definitions alone: you have to practice running code on paper and writing small functions without notes.
If you can do all ten of these cold, you are ready:
f(scores, n), and the function can change the caller's array. Mark read-only parameters const.sizeof a gives the size of an address, not the array. sizeof a / sizeof a[0] only works where the array is declared.-1. The return -1 goes after the loop. Up to n comparisons, and the array does not need to be sorted.> keeps the first maximum, >= keeps the last. Reverse in place swaps a[i] with a[n - 1 - i] for only n / 2 passes.t[r][c] sits at position r × COLS + c. A parameter may leave out the rows but must state the columns: int m[][COLS].char array ending in '\0'. n characters need n + 1 slots. strlen counts the characters before '\0'; sizeof gives the whole array.= or == on strings. Copy with strcpy, join with strcat, compare with strcmp(a, b) == 0. strcmp returns 0 for equal, negative if the first comes first, positive if it comes second.'7' - '0' is the number 7, and value = value * 10 + (c - '0') builds a number from digit characters. <ctype.h> tests (isdigit, isalpha, isupper...) return non-zero for true.&x is the address of x, int *p = &x; makes p point to x, and *p = 25; changes x. Pass addresses (swap(&x, &y)) to let a function change the caller's variables or return more than one result.p + 1 moves one element, not one byte. a[i] is exactly *(a + i), and q - p counts the elements between two pointers. An array name cannot be moved (a++ does not compile).return -1; in an else inside the search loop, so only a[0] is ever checked.print_array(scores[], n) or print_array(scores[4], n) instead of print_array(scores, n).'\0' when you copy or build a string one character at a time.if (strcmp(a, b)) for "same text". That is true when the strings are different.*p + 1 (the value plus one) with *(p + 1) (the next element), and *p++ (read, then move p) with (*p)++ (add one to the value).Each day names the exact lesson sections to read. Around 45 to 60 minutes a day is enough.
| Day | Study These Sections | What To Actually Do |
|---|---|---|
| 1 | Lesson 1: Arrays in Depth → Arrays Recap: What Carries Over from CP1, Passing Arrays to Functions | Write print_array and add_bonus from memory. Explain in one sentence why sizeof fails inside a function. |
| 2 | Lesson 1: Arrays in Depth → Linear Search, Common Array Algorithms | Write linear_search and count_matches from memory. Trace the max-position loop once with > and once with >= on an array with a repeated maximum. |
| 3 | Lesson 1: Arrays in Depth → Two-Dimensional Arrays, 2-D Arrays and Functions: Matrix Operations | Compute row totals, column totals, both diagonals, and a transpose by hand. Work out r × COLS + c for five cells. |
| 4 | Lesson 2: Strings and Character Arrays → Strings in C: Character Arrays with a Null Terminator, Reading and Printing Strings, The <string.h> Toolkit | Draw the memory picture of three strings including '\0'. Predict strlen, sizeof, and three strcmp signs before running them. |
| 5 | Lesson 2: Strings and Character Arrays → Character Handling with <ctype.h>, Writing Your Own String Functions, Common String Bugs and How to Avoid Them | Write my_strlen, my_strcpy, and reverse without looking. Find all seven string bugs in the bugs section without reading the fixes first. |
| 6 | Lesson 3: Pointers → Memory Addresses and the & Operator, Pointer Variables and the * Operator, Pointers as Function Parameters | Draw boxes and arrows for x, p, and *p. Write swap and min_max from memory and explain why swap_copy fails. |
| 7 | Lesson 3: Pointers → Pointer Arithmetic, Pointers and Arrays, Common Pointer Mistakes | Trace the *p + 1, *(p + 1), *p++, (*p)++ program by hand. Then take the Free Practice Set below: 30 minutes, no notes. |
After Day 7, take Prelim Mock Exam A under exam conditions, check it with the answer key, re-read the sections behind every miss, then take Prelim Mock Exam B a day or two later.
Fifteen genuine exam-style items sampling all seven lessons, about two per lesson. Do all fifteen before looking at the key, and treat it like the real thing: 30 minutes, no notes. The key tells you which lesson each item came from, so every miss points you to the lesson to review.
1. Given int scores[10]; and the function void show(const int a[], int n);, which call is correct?
show(scores[10], 10);show(scores[], 10);show(scores, 10);show(&scores[], 10);2. Given int x = 5; and int *p = &x;, which statement changes x to 9?
p = 9;*p = 9;&x = 9;p* = 9;3. Given the declarations below, which statement correctly sets the GWA through ps?
typedef struct {
char name[30];
double gwa;
} Student;
Student s;
Student *ps = &s;
ps.gwa = 1.25;ps->gwa = 1.25;*ps.gwa = 1.25;ps->gwa == 1.25;4. Which fopen mode erases the file if it already exists?
"r""a""w"Write exactly what each fragment prints.
5.
int a[6] = {4, 9, 2, 9, 5, 1};
int i, pos = 0;
for (i = 1; i < 6; i++)
if (a[i] >= a[pos])
pos = i;
printf("%d %d", a[pos], pos);
6.
char s[20] = "Davao";
printf("%d %d", (int)strlen(s), (int)sizeof s);
7.
int a[4] = {2, 4, 6, 8};
int *p = a;
p += 2;
*p = *p * 3;
printf("%d %d", *p, *(p - 1));
8.
int f(int n) {
if (n <= 1)
return 1;
return n + f(n - 2);
}
/* in main: */
printf("%d", f(7));
9. Bubble sort, ascending. One pass compares a[0] with a[1], then a[1] with a[2], and so on to the last pair, swapping whenever the left value is bigger. The array is {7, 3, 9, 2, 5}. Write the array after pass 1 and the number of swaps made.
For each one, say what is wrong and write the fix.
10. The user's name really is "Ana", but the program prints Who are you?.
char name[20] = "Ana";
if (name == "Ana")
printf("Welcome, Ana!\n");
else
printf("Who are you?\n");
11. Using the Student type from Item 3:
Student s;
s.name = "Liza";
12. This function is supposed to return 1 + 2 + ... + n.
int sumTo(int n) {
return n + sumTo(n - 1);
}
13. This loop is supposed to print a text file one character at a time. fp was opened correctly.
char ch;
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
14. Binary search for the key 31 in the sorted array {4, 9, 13, 18, 25, 31, 40}, using low = 0, high = 6 and mid = low + (high - low) / 2. List every index that becomes mid, in order, and give the value the search returns.
15. Given int t[4][5];, counting from 0, at what position in memory is t[2][3] stored?
| # | Answer | Lesson | One-Line Why |
|---|---|---|---|
| 1 | C | 1 | Pass an array by its name alone: no brackets and no & in the call. |
| 2 | B | 3 | *p follows the pointer to x, so *p = 9 stores 9 in x. p = 9 would try to store 9 as an address. |
| 3 | B | 4 | Use the arrow with a pointer to a structure. *ps.gwa fails because . binds tighter than *; the long form is (*ps).gwa. |
| 4 | C | 5 | "w" creates the file or erases an existing one. "r" only reads and "a" adds to the end. |
| 5 | 9 3 | 1 | >= keeps the last maximum: 9 appears at index 1 and index 3, so pos ends at 3. With > the answer would be 9 1. |
| 6 | 5 20 | 2 | strlen counts the 5 letters before '\0'; sizeof is the whole 20-slot array. |
| 7 | 18 4 | 3 | p += 2 moves p to a[2] (6), which becomes 6 × 3 = 18. *(p - 1) is a[1], which is 4. |
| 8 | 16 | 6 | f(7) = 7 + f(5) = 7 + 5 + f(3) = 7 + 5 + 3 + f(1) = 7 + 5 + 3 + 1 = 16. |
| 9 | 3 7 2 5 9, 3 swaps | 7 | Swap 7 and 3; 7 and 9 stay; swap 9 and 2; swap 9 and 5. The largest value, 9, ends up last. |
| 10 | Use strcmp(name, "Ana") == 0 | 2 | == compares two addresses, which are never equal, so it is always false even when the text matches. |
| 11 | Use strcpy(s.name, "Liza"); | 4 | name is a char array, and an array cannot be assigned with = (compile error). |
| 12 | Add a base case: if (n == 0) return 0; | 6 | With no base case the calls never stop, and the program crashes with a stack overflow. |
| 13 | Declare int ch; | 5 | fgetc returns an int so EOF can be told apart from every real character. In a char, the loop can stop early on a real character or never stop at all, depending on the compiler. |
| 14 | mid = 3, then 5; returns 5 | 7 | Step 1: a[3] is 18 < 31, so low = 4. Step 2: mid = 4 + (6 - 4) / 2 = 5, and a[5] is 31: found. |
| 15 | 13 | 1 | Row-major order: position = r × COLS + c = 2 × 5 + 3 = 13. |
Scored 12 or better? You are on track. Below that, note which lessons your misses came from and re-read those lessons first. The full mock exams below (two for the prelim, two for the final, each with a complete answer key, trace tables and tested solutions) come with the subject unlock.
Pro8 reviewers locked
Part of this subject's paid reviewers. Not included in this printout.
Done with this module? Track it — your progress shows on the subject list.
Studying with blockmates? Send them this lesson.
End of this subject