This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING FINAL EXAMINATION, DECEMBER 2002
First Year — Engineering Science
CSC 180H1F — INTRODUCTION TO COMPUTER PROGRAMMING
Exam Type: C
Examiner — T.F. Fairgrieve Aid sheet must be handwritten. No calculators. Student Number: .__ . _ . . Last Name: First Name: Do not turn this page until you are told to start.
Please ﬁll out the identiﬁcation section above.
When you start the exam read the instructions on page ‘2 carefully. Page 1 of 18 pages CONTINUED CSC 180H1F FINAL EXAIVIINATION READ THE FOLLOWING FIRST: This final examination consists of 9 questions on 18 pages (including this page and the cover page). Please make sure that your copy of the examination is
complete. Answer each question directly on the examination
paper, in the space provided. Be aware that concise, well thoughtout armwers will receive more marks than long rambling ones. The last page is blank and may be used for rough
work or in case you need more space for your solutions. THIS EXAlVI IS DOUBLESIDED. Page ‘2 of 18, pages DECEMBER 2002 i # l: _/20
l # 2; j 6
l # 3: __/10
# '1: _/ 4
# 5. ; 8
l # 6: m__,’18i
I # 7': _____/ 5
I # 9: __/1Ui
n ..__l
TOTAL: _____/90
l— _._r,
CONTINUED CSC 180H1F FINAL EXAMINATION DECEMBER 2002 Question 1. [20 MARKS} Part (a) [4 MARKS]
Consider the following function deﬁnition: void f( int n ) {
while ( n > 1 ) {
printf("3d\n”, n);
if(n‘/.2==O){
n=n/2;
} else {
n = 3*n + 1;
}
}
printf(“2d\n”, n);
} Trace through this function carefully and show what. output. is displayed when it is called via the
Statenient: H3); Pass“: 3 0f 18 pages CONTINUED CSC 180H1F FINAL EXAIVIINATION DECEMBER 2002 Part(b) H MARKQ
Given the C program:
#include <stdio.h> #define N 10
int main() {
int aEN] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *p = &a[0], *q = &a[N1], temp, ;;
while ( p < q ) {
temp = *p;
*p = liq;
p++;
*q = temp;
q = 2;
}
for ( i=0; i<N; i++ ) {
printf("ﬂd ", a[i]);
}
printf(”\n");
return 0;
} VVhatoutputischspkqmd when uns(31nngrau1isrun? Page 4 of 18. pages CONTINL'EI‘) CSC 180H1F FINAL EXAMINATION DECEMBER 2002 Part(c) w MARK§
Consider the following C progTam:
#include <stdio.h> #define N 25
int main() {
int i;
char words[3][N];
char V[N], *Set[3] = { wordsEO], uordsfl] };
scan1(”%s“, w);
setEO] = w;
scanf("ZS", W);
setEl] = u;
for ( 1 = 0; i <= 2; i++ ) {
printf(" Ks \n”, set[i] )3
}
return 0;
} If this program is run with the input. data. easy
difficult
impossible what output. is displayed? Page 5 of 18 pages CONTINUED CSC 180H1F FINAL EXAIVIINATION DECEIVIBER. 2002 Part (d) [5 MARKS]
Consider the following C program: #include <stdio.h>
void f( int a, int 1)) {
printﬂ" a = '/.d and b = '/.d \n", a, b 3;
if (b > a ){
int c = (a + b)/2;
f( a. c )5
f(c+1, b);
}
}
int main()
{
f( 1, 5 );
return 0;
} Trace through this C program carefully and Show what output. is dispiayed when it is run. Page 6 of 18 pages COI\“'1‘INLI'ED CSC 180H1F FINAL EXAIVIINATION DECEIVIBER 2002 Part (8) [2 MARKS}
Consider the following C program: #include <stdio .h>
int main() {
float a = 1.23E+10, b=3.21E05, C;
c=(a+b)a;
printf( "c='/.g \n", C);
return 0; } What output is displayed when this C progrzmi is run? Question 2. [6 MARKS] Consider the problcrn'of trying to accurately evaluate the rnathomatical expression — — —+— M using ﬂoatingpoint arithmetic. Assume that .r, is not equal to :1‘ Part (a) [2 MARKS] For what values of :r. is it diﬁicult to accurately evaluate expression (r) using ﬂoutingpoint arith
metic? Assume that the value of :r, is an exact floatingpoint number. Justify your response. Part. (b) {4 MARKS] Give an equivalent formula for expression (t) that, can be evaluated accurately using floutingpoint
arithmetic. Briefly justify your response. Page 7 of 18 pages CON‘llNL'ED CSC 180H1F FINAL EXAIVIINATION DECEMBER 2002 Question 3. [10 MARKS] In this question, your task is to write a simple simulation of a game of golf. Golf is a game that
is played outside. The goal of the game is to mOVe a ball from a starting point (called the “tee")
to a hole in the ground on an ending area (called the “green"). This usually takes several turns.
(Your program will only simulate moving the ball from the tee to the green.) The ball is moved
by hitting it with a sort of stick (called a “club”). Assume that there are 9 different clubs available
to a golfer, numbered 1 through 9. Using a diﬁerent numbered club will send the ball a different
distance, on average, when the ball is hit. To simplify the problem. assume that the game is played only in a single dimension. That is,
the ball never leaves a line drawn from the starting position on the tee through to the hole on the
green. Therefore the only Variable that you need to consider is the distance remaining to the hole.
Your simulation should include the following steps. 1. Pick a random number to represent the distance from the tee to the hole. The distance should
be between 250 and 500 yards. (All distances will have integer values.) ‘2. For each turn, repeat. each of the steps 2(a) — 2(rl) below until the distance from the ball to
the hole is less than ‘25 yards. (a) Display the distance remaining to the hole.
(b) Let the user select a club by typing a number between 1 and 9. (c) Assume that the average distance a ball goes when hit by a club is given by the formula
averagedtstonce = 300 — clubmumber * 30 so that, for example, a #l club hits the ball an average distance of 300 — 1 a: 30 = 270
yards and a #9 club hits the ball an average distance of 300 — 9 * 30 = 30 yards. Once
you have computed the average distance for the selected club you should calculate the
turmdistance by adding a random integer between ~20 and +20, inclusive, to the com
puted averagodtstarice for the club. This change will make the game less predictable. (d) Subtract the turmdtstance computed in step 2(c) from the distance remaining to the
hole. 3. When the distance remaining to the hole is less than 25 yards. tell the user that they have
reached the green, display the number of turns taken, and stop. Write a complete, welldesigned C program that simulates the golf game described above. Your
program should be able to duplicate the output from the following sample run : Let’s play golf! You’re at the tee. You’re 384 yards from the hole. Which club # would you like to select? 1 <enter>
Your shot sent 250 yards. You’re 134 yards from the hole. which club # would you like to select? 6 <en:er>
Your shot went 109 yards. You’re 25 yards from the hole. which club # would you like to select? 9 <enter>
Your shot vent 21 yards. You’re on the green after hitting the ball 3 timeCs). continued at the top of the next page Page 8 of IS pages CONTINUED CSC 180H1F FINAL EXAIVIINATION DECEIVIBER 2002 You may use the function randomlntegerO to generate integer random numbers. This function
has prototype int randomlnteger( int min, int max ) and returns am integer value that, is
between min and max, inclusive. Place your answer to Question 3 here: Page 9 of 18‘ pages CONTINUED CSC 180H1F FINAL EXAIVIINATION DECEMBER 2002 Question 4. [4 MARKS]
The following C function may be used to multiply a m x 71 matrix A by a n x p matrix B and store the result in a m x 'p matrix Q: void matrixMultiply( int ”A, int MB, int HQ, int m, int n, int p ) {
int i, j, k; for(i=0;i<m;i++){
for(j=0;j<p;j++){ int sum = AEi][01*B{0][j] ; for(k=1;k<n;k++) ‘[
sum += Mi] [k]*B[k] [j]:
}
" " QEiJ'fj] = sum; Part (a) [2 MARKS] Give an expression for the number of multiply operations this function requires to compute the
product of a m x 7:. matrix with a n x p matrix. Brieﬂy justify your result. Part (b) [2 MARKS] Give an expression for the number of add operations this function requires to compute the product
of Ft m X 7'2. matrix with a n x 30 matrix. Briefly justify your result Page 10 of 18 pages CONTINUED CSC 180H1F FINAL EXAIVIINATION DECEL’IBER 2002 Question 5. [8 MARKS} Matrices with equal entries along each diagonal arise in many applications and are called Toeplitz matrices. More precisely, an nxn matrix T is a Toeplitz matrix if there exist. numbers 127,41, . . . ,r_1>
11;, T1,... , "711 such that the i,j element of ’1”, Ti}. satisﬁes Ti} = r]_,, for all i,j = 1,23,. .. ,n. Thus T_2 T'_1 To T'!
T‘_3 1"__2 7”_1 To is a 4 x 4 Toeplitz matrix. (Look along the diagonals.) Part (a) {3 MARKS]
Propose an efficient approach for storing an n x n ".l‘oei‘ilitz matrix T that minimizes the number
of values stored and describe how you would implement, your approach in C. Part (b) [2 MARKS]
Where would you store the if element of T. 713'? Recall that in C, all array subscripts are greater
than or equal to 0, Part (C) [3 MARKS] Write a C function that. computes the matrixvector product. 3,1 2 T13; Where T is a n 2: n 'l‘oeplitz
matrix, and :1: and y are vectors with n. elements Assume that T is stored using the efﬁcient
approach that you described in Part (a) and :i: and y are each stored in their own 1Climensional
array. Assume that the i'natrix and vector elements are stored using the C type double Page ll of 18 pages CONTINUED CSC 180H1F FINAL EXAIVIINATION DECEIVIBER 2002 Question 6. [18 MARKS} In this question you are to write a, complete and efﬁcient C function named FindInStringO and
then describe how you would test your function for correctness. Part (a) [10 MARKS] The FindInStringU function locates the ﬁrst complete occurrence of a given string s2 {excluding
the terminating null character) in a given string 81. The index of the start of the string 32 in string
31 is returned by FindInString0. The value —1 is returned if the. string 82 is not found in the string
51. If the string 32 is the empty string, "", the FindInStringr) function returns the value 0. Write an efﬁcient and complete C implementation of the FindlnString() function described
above. Your function prototype should be int FindInString( char sl , char sQEJ ) The only C function that your function may call is strlenO. Example return values from the FindInStringO function: FindInString(“De Do Do Do, De Da Da Da”, "Do") returns 3
FindInString(”Eat a donut and do the dew.”, ”do") returns 6
(the ”do" in ”donut" is matched first)
FindInString(”do the dew and eat a nut", “donut”) returns 1
FindInString(”exam”, “easy") returns 1
FindInString("To be or not to be, that is the question.”, “to”) returns 13
(the case of the characters is significant) Page i3 of 18 pages CONTINUED CSC ISOHIF FINAL EXAINIINATION DECENIBER 2002 Part (b) [8 MARKS] Describe different test cases that you would use to judge the. correctness of the FindInStringO
function that you wrote for Part (9.). Give example values for the parameters 51 and s2 and indicate
the potential algorithm flaws that your cases are designed to test. Exnrnples of 51 and 52 The potential algorithm flaw being tested? test
case ___.__.__,____,__.J_n 7__.ﬂ._,..__w_.__,____ test
case test
case test test ‘
case ~ (You do not need to fill every entry in the above table to earn full Irmrks') Page 13 of 18 pages CONTINUED CSC 180H1F FINAL EXAMINATION DECEIN'IBER 2002 Question 7. [6 MARKS] In C, we use a “structure” (or “record"} variable to gather a. collection of related variables. For
example, a pmgram for keeping track of student grades might use the following collection of vari
ables: struct student {
char name [25+ 1];
int number;
double grade; } ; The later declaration struct student John; creates a structure variable named John This structure
variable could be initialized using the statements: strcpyCJohnhmne, "John Donut");
John.number = 991234567;
John.grade = 98.6; The declaration struct student EngSciOTGEQSO]; would be used to create an array of student
records. ' ' 'Consider the problem ofsorting an array of student records. The student records could be sorted
with respect to any of the structure variables. To assist the sorting task, write a C function with pro
totype int compareStudents( struct student one, struct student two, int field )
that compares two student structures. The variable field indicates which structure variable should
be used to compare student structures. When field has the value 1 or '2‘ the student structures
should be ordered alphabetically by name or numerically by number, respectively. Wl‘ien field has
any other value, the student structures should be ordered numerically by grade. Your function should return the value: 1 if student one should come before student two in the
the sorted list, +1 if student one should come after student two in the sorted list, or 0 if student
one and student two should be considered equal on the basis of the comparison Your C function may call library functions that you know about. Page 14 of 18 pages CON’I‘INIJFD CSC 180H1F FINAL EXAIVIINATION DECEMBER 2002 Question 8. [8 MARKS] In lectures we developed a C function that uses the binary search algorithm to search for a
given key in a. given sorted array. The algorithm was implemented using am iterative style (that is,
using a, loop) and we saw that it was a. little tricky to write the algorithm correctly. Implementing
the binary search algorithm is much easier if you use a recursive style of programming. Write a recursive C function that uses the binary search algorithm to search for a given key in
a given sorted array. If the key is found in the sorted array, your function should return the index
of the key in the sorted array. Otherwise, your function should return the value —1. Your function
should assume that the array elements and the key value are of C type int. Page 1:3 of .18 pages CONTINUED CSC ISOHIF FINAL EXAIV‘IINATION DECEIVIBER 2002 Question 9. {10 MARKS] In this question you are to write a C function that computes the determinant of a given n x n,
matrix A. The determinant of. a n x n matrix A is a single numerical value. The determinant can
be used, for example, in Craruer’s Rule, a method for solving systems of linear algebraic equations. The determinant of an n x in matrix A can be computed by multiplying the elements in any
row (or column) by their cofactors (see below) and adding the resulting products; that is, for each
lgignandlgjgn, det(A} = ClijClj + 023C341 + A  + (1”;an
{a cofactor expansion along the jth column) and equivalently
d0t(.4) = digCI} + (112C12 + ' ‘ ' + (lmCm
(a cofactor expansion along the ilh row) ' The cofactor of element “o‘ of matrix A is denoted by Clj and is deﬁned by Co = Elf“Mg
where JMU is deﬁned to be the determinant. of the submatrix that remains after the 1th row and
jth column are deleted from the matrix A. Write a C function that courputes the determinant of a given Square matrix by using a cofactor
expansion along the ﬁrst row of the matrix. Your function must work for all n x n integer
matrices having n S 10. Your function should have the prototype; int det( int AUG] [10], int n ) Note that this declaration shows that you should assume that the 2dimensional array A has
been declared to hold 10 rows and 10 columns Of course, you can store a matrix with fexver than
10 rows and columns in the array A and indicate the size of the stored matrix by setting n to the
appropriate number of rows / columns. The following main() function shows how your determinant function might be called: #include <stdio.h>
int det( int A[10][10], int n ); /! declare the det function */
int main() {
int A[10][10], n;
n = 3;
MO] [0] = 1; A[0][1] = 2; MO] [2] = 3;
A[1][0] = 2; A[1][1] = 3; M1] [2] = 4;
A[2][O] = 3; At2][1] — 4; A[21[2] = 5;
printf(" det(A) = '/.d \n". det( A, n ) );
return 0; } Your solution is not required to use computer memory efficiently
Write your solution on the next page. Page Hi of 18 pages C(i)N'l"lNL‘ED CSC 180H1F FINAL EXAIVIINATION DECEMBER 2002 Place your answer to Question 9 011 this page. Page 17 01' 18 pages CONTINUED CSC 180H1F FINAL EXAMINATION DECEMBER 2002 This page for rough work and extra. space for solutions. Tmal Marks — 90 Page: 18 of 18 pages END OF E:\'.»\:\:I:<.\.TIO.\‘ ...
View
Full Document
 Fall '08
 SteveEangels

Click to edit the document details