Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views6 pages

CMPT125 Practice Final

C and C++ practice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

CMPT125 Practice Final

C and C++ practice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

CMPT 125 — Practice Final (Extended)

Answer everything on paper — no IDE, no compiler.


Time: 3 hours | Total: 100 points

Question 1 — Memory layout + List class (fill in the blanks) (10 pts)
We model grades with a Grade class and a List container that mixes a small static buffer plus a heap
buffer.
// List.h
class List {
private:
static const int INITIAL_SIZE = 5;
Grade elements1[INITIAL_SIZE];
Grade* elements2 = nullptr;
unsigned int elementCount = 0;
unsigned int capacity = INITIAL_SIZE; // when we spill to heap, capacity tracks heap s
public:
~List(); // dtor
void insert(const Grade& g); // append at the end
// ... other methods ...
};

List.cpp — fill the blanks _____ :


List::~List() {
delete [] elements_____; // (a)
}

void List::insert(const Grade& g) {


if (elementCount < INITIAL_SIZE) { // still in stack buffer
elements1[elementCount++] = g;
return;
}
// move/allocate on heap
if (elementCount == INITIAL_SIZE) {
capacity = std::max(2*INITIAL_SIZE, INITIAL_SIZE+1);
elements_____ = new(std::nothrow) Grade[capacity]; // (b)
if (elements_____ == nullptr) return; // (c) out of memory
for (unsigned i=0; i<INITIAL_SIZE; ++i) elements2[i] = elements1[i];
}
if (elementCount == capacity) {
unsigned int newCap = capacity * 2;
Grade* tmp = new(std::nothrow) Grade[newCap];
if (tmp == nullptr) return; // (d)
for (unsigned i=0; i<capacity; ++i) tmp[i] = elements2[i];
delete [] elements2;
elements2 = tmp; capacity = newCap;
}
elements_____[elementCount++ - INITIAL_SIZE] = g; // (e)
}

// Write what each blank must be (e.g., “(a) elements2”) and justify briefly.
Question 2 — Draw an empty DHSL List object (6 pts)
Draw the memory diagram for an empty Doubly-Headed Singly-Linked list (DHSL): show the List
object, its head/tail pointers, and their (null) values. Label heap vs stack.

Question 3 — Recursion: star pattern (10 pts)


Write a recursive C function that prints a pattern of '*' given two integers a and b (inclusive). Examples:

• Input: 1 6 prints 1..6 stars on separate lines.

• Input: 0 5 prints nothing.

• Input: 3 10 prints lines of 3..10 stars.


State the base case and recursive step clearly.

Question 4 — ADT selection (6 pts)


Name a concrete problem solvable by each ADT and justify briefly:

• (a) List

• (b) Stack (not palindrome)

• (c) Queue

Question 5 — Box trace a recursion (10 pts)


Hand-trace the following program. Draw one box per call showing parameter values. Mark with an
arrow where each callee returns to in the caller. Finally, write the printed output.
void rec(int n){
if(n<=0){ printf("X"); return; }
printf("%d", n%3);
rec(n-2);
printf(".");
}
int main(){ rec(5); return 0; }
Question 6 — Palindrome (8 pts)
Write a C function that returns 1 if a null-terminated string is a palindrome and 0 otherwise. You may
ignore case and non-letters if you wish; state your assumption. Follow good programming style (clear
names, comments, no magic numbers).

Question 7 — Queue on DHSL: place front/back (6 pts)


Given a DHSL list diagram with head and tail, mark where the Queue’s front and back should be and
explain (enqueue/dequeue costs must be O(1)).

Question 8 — 2D image in 1D array (right neighbour) (6 pts)


img is uint8_t* with size rows*cols. Write the function below. It prints the value of the right neighbour if it
exists; otherwise prints "no right neighbour". Check bounds carefully.
void print_right_pixel(const uint8_t img[],
unsigned cols, unsigned rows,
unsigned x, unsigned y);

Question 9 — Brightness scaling with rounding + clipping (6 pts)


Write the function below. Multiply every pixel by scale, round to nearest (0.5 up), and clip to [0,255].
Use a wider temporary type before storing back to uint8_t.
void scale_brightness(uint8_t img[],
unsigned cols, unsigned rows,
double scale);

Question 10 — SHSL / DHSL core ops (12 pts)


typedef struct Node { int data; struct Node* next; } Node;

• (a) Node* findMin(Node* head) — return pointer to node with minimum value; NULL if empty. (4)

• (b) Node* reverse(Node* head) — iterative, in-place, return new head. (4)

• (c) For a DHSL list with Node* head, *tail: implement push_back in O(1); update invariants for
empty/singleton. (4)
Question 11 — Arrays & two-pointer filter (6 pts)
Given int a[] of length n, remove all negative numbers in-place while preserving order. Return the new
logical length. Write the loop and state the loop invariant for indices i/j.

Question 12 — Complexity quick hits (6 pts)


Give tight Big-O (time) for each:

• (a) linear search

• (b) binary search

• (c) insert at head of a singly linked list

• (d) push_back in SHSL

• (e) push_back in DHSL

• (f) reversing a list iteratively

Question 13 — Dynamic memory: merge two sorted arrays (8 pts)


Write:
int* merge_sorted(const int* a, int na,
const int* b, int nb,
int* out_n);

Allocate with malloc, return merged ascending array; write *out_n. Caller will free. Handle empty inputs
cleanly.

Question 14 — Files: binary I/O with structs (8 pts)


typedef struct { char name[16]; uint8_t value; } Rec;

• (a) Save an array Rec arr[N] to "data.bin" using fopen/fwrite/fclose (check errors).

• (b) Load back into Rec out[N] and print all value fields. Mention correct modes ("wb", "rb") and what
binary vs text means.

Question 15 — C++ ADT: Queue class on DHSL (10 pts)


Design a templated Queue using DHSL nodes:

• private: struct Node { T data; Node* next; }; Node* head, *tail;

• push(const T&) and pop() are O(1); front(), empty();

• destructor frees all nodes; throw on pop()/front() if empty.

Question 16 — Pointer arithmetic & off-by-one (6 pts)


uint8_t *p = img; // rows*cols image
unsigned idx = y*cols + x; // assume in range
// (i) What does *(p + idx) read?
// (ii) Under what condition is the right neighbour in-bounds?
// (iii) Write the single expression that indexes the bottom neighbour.

Question 17 — Debugging (5 pts)


Find five distinct bugs or style violations in the snippet (each must be real and explainable):
uint8_t brighten(uint8_t px, double s){
uint8_t r = (uint8_t)round(px*s);
if (r > 255) r = 255;
return r;
}
Question 18 — Short recursion proof idea (5 pts)
State briefly (loop invariant or induction) why your reverse from Q10(b) is correct.

Optional Extra Credit — Stable remove (4 pts)


Given int a[] and n, remove every other duplicate (keep first occurrences). In-place, stable; O(n^2)
worst-case allowed. Provide code or high-level pseudocode.

You might also like