180midterm-sol

# 180midterm-sol - CSC 180H1 F October Midterm 2008 Duration...

This preview shows pages 1–5. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
CSC 180H1 F Midterm October 2008 Question 1. [10 marks] Defne a ±unction find item that returns the position o± the frst occurrence o± an item in an array. I± no such item were ±ound in the array, it returns -1. find item has three parameters: a is array, n is array size, and item is the item to fnd. For example, given the ±ollowing array, int a[] = {0, 1, 1, 8, 0, 1, 0, 1, 8, 0}; find item(a, 10, 8) returns 3. /* return index of item in a, -1 if none */ int find_item(int a[], int n, int item) { int i; for (i = 0; i < n; i++) if (a[i] == item) return i; return -1; } Student #: Page 2 o± 11 cont’d . . .
CSC 180H1 F Midterm October 2008 Question 2. [15 marks] Defne a ±unction find pattern that returns the position o± the frst occurrence o± a pattern in an array. I± no such pattern were ±ound in the array, it returns -1. find pattern has ±our parameters: a is array, n is array size, pattern is pattern array, and m is size o± pattern array. For example, given the ±ollowing two arrays, int a[] = {0, 1, 1, 8, 0, 1, 0, 1, 8, 0}; int b[] = {1, 8, 0}; /* pattern array */ find pattern(a, 10, b, 3) returns 2, the position o± the frst digit o± pattern 180 in array a . a: 0 1 1 8 0 1 0 1 8 0 ^ | position: 2 /* return index of pattern in a, -1 if none */ int find_pattern(int a[], int n, int pattern[], int m) { int i, j, k; for (i = 0; i < n - m + 1; i++) { for (j = i, k = 0; k < m && a[j] == pattern[k]; k++, j++) ; if (k > 0 && k == m) return i; } return -1; } Student #: Page 3 o± 11 cont’d . . .

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
CSC 180H1 F Midterm October 2008 Question 3.
This is the end of the preview. Sign up to access the rest of the document.

## 180midterm-sol - CSC 180H1 F October Midterm 2008 Duration...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online