MCMASTER UNIVERSITY
HAMILTON, ONTARIO, CANADA
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
COE2SH4 - PRINCIPLES OF PROGRAMMING
2ND MIDTERM EXAMINATION - FALL, 2006 Instructions:
1. Write your name, student ID, section number and signature in the spaces indicated below.
2. The examination has 9 pages in total.
3. This is a closed book examination. No reference notes and books are allowed. No calculators are allowed.
4. Return the whole examination book after the exam.
5. Before answering a question, read carefully the question
requirement several times. If you have any doubts regarding the requirements ask the instructor or the TAs.
N a m e ( p l e a s e p r i n t ) : _ _ _ _ _ _ _ _ _ _ _ _ _
S t u d e n t I D : _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
T u t o r i a l S e c t i o n : _ _ _ _ _ _ _ _ _ _ _ _ _
S i g n a t u r e : _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
I A1) - A4),B1),B2) C1), C2)
25 points
II C Programming question D1)
20 points
III C Programming question D2)
20 points
IV Java J1.1)-J1.10) 15 points
V JavaProgramming question
J2)
20
points
VI Bonus question Q)
10 points
Total 100 points
C
P
ROGRAMMING
-
F
ILL IN
T
HE BLANKS(5 points)
A1) – A4) Evaluate the following expressions in C, and write the values in the blanks.
A1)(1 point)int x[5] = {2,4,6,8,10};
x[1] + x[4]/x[0] = 9
A2)(1 point) typedef struct{ int x; int y; }Point; Point p1={ 2, 10 } ;
(p1.y - p1.x)/2 = 4
A3)(1 point) typedef struct{ int x; int y; } Point; Point array[ ] = {{-1,1}, {3,6}, {-2,0}};
array[1].y = 6
A4)(2 points)
int a[20] = {100, 99, 98, 97, 96, 95, 94, 93}; int *p = &a[0];
int **pdouble = &p;
*p + 2 = 102
*(*pdouble+5) = 95
C
P
ROGRAMMING
-
C
ORRECT
T
HE
E
RRORS(10 points)
Each of the following C function definitions has syntax, logic or other kinds of errors. Assume all function headers are correct. Correct each code such that it matches the function description.
B1) (5 points) Function product receives as parameters a
pointer aPtr to an integer array, and the size n of the array. It returns the product of all non-zero array elements.
The code has three errors.
int product( int *aPtr, int n ) {
int i;
int prod=1;
for( i=0; i < n; i++ ) if (aPtr[i] != 0 )
prod *= aPtr[i]; return prod;
}
B2) (5 points) Function factorial is a recursive function to compute the factorial of a positive integer (>0). It receives a positive integer parameter named number (>0), and returns the factorial of that number. (You can assume that the parameter passed to the function in the caller is >0!)
The code has three errors.
int factorial( int number ) {
if( number == 1) return 1; else
C
P
ROGRAMMING
-
W
RITE
T
HE
O
UTPUT(10 points)
C1) (5 points) Read the following C program and write the output on the screen:
#include <stdio.h>
int f( int a, int *bp ); main( ){
int m = 10, n = 20, k = 30; k = f(m, &n);
printf( “m=%d\t”, m); printf( “n=%d\t”, n); printf( “k=%d\t”, k); }/* end main */
int f( int a, int *bp ){ a *= 5;
*bp -=3; return a; }/* end f */
ANSWER: m = 10 n = 17 k = 50
C2) (5 points) Read the following C program and write the output on the screen:
#include <stdio.h> main(){
char *p[4] = {"abc", "def", "ghi", "mnp"}; char *temp;
printf( “%c\n”, p[1][0] ); temp = p[1];
p[1] = p[3]; p[3]=temp;
printf( “%c\n”, p[3][2] ); printf("%s\n", p[1]);
}/* end main */
C
P
ROGRAMMING
Q
UESTIONS
D1)(20 points)
Write a C function with the prototype
double **matrix_average ( double matrixA[ ][15], int n ) ;
The function receives as parameters a 2D array matrixA which represents an n-by-15 matrix, and an integer n which represents the number of matrix rows.
The function computes the average of all elements in matrix matrixA, then it creates a new n-by-15 matrix and initializes all its elements to the average computed previously. The memory for the new matrix should be allocated dynamically (as an array of pointers, each pointer pointing to a matrix row). The function should return the address of the new matrix (i.e. a double pointer).
ANSWER:
double **matrix_average( double matrixA[ ][15], int n ) {
int i,j;
double average=0;
double **matrixB=NULL;
for(i=0; i<n; i++) for(j=0; j<15; j++)
average += matrixA[i][j];
average = average / ( 15 * n );
matrixB= calloc( n , sizeof ( double * ) ); for( i=0; i < n; i++ )
matrixB[i] = calloc( 15 , sizeof( double ) );
for(i=0; i<n; i++) for(j=0; j<15; j++)
matrixB[i][j] =average;
D2)(20 points) Consider the following C structure type definition. struct node{
int id;
struct node *next; };
Write a C function insert_sorted( ) with the prototype
void insert_sorted( struct node *headPtr, struct node* newPtr); Parameters:
a) headPtr is a pointer to a sorted linked list; The nodes of the list are of type struct node, and the list is sorted in decreasing order of member id.
b) newPtr is a pointer to a new node. Assume that no node in the list has the same id as the new node.
The function should insert the new node at its right position in the linked list such that the list remains sorted in decreasing order of id’s.
void insert_sort (struct node *headPtr, struct node *newp ) {
struct node *p=headPtr;
while( p->next != NULL ) /*while current node is not the last*/ { /*check if the next node has smaller id than the node to be inserted*/
if( p->next->id < newp->id )
{/* if yes, insert after current node and exit function */ newp->next = p->next;
p->next = newp; return;
}
/* if not, set p to point to the next node */ p = p ->next;
}
p->next = newp; /* insert at the end */ }
JAVA QUESTIONS
J1) The small Java programs J1.1) – J1.10) use the Java class Student defined below.
public class Student{ private int id; private int grade;
public static int count=0;
public Student( int anId, int someGrade ){ id = anId;
grade = someGrade; count ++;
}
public int getGrade( ){ return grade;
}
public int getId( ){ return this.id; }
public int increaseGrade( int increment ){ if( grade + increment <= 100 )
grade += increment; else
grade = 100; return grade; }
public String toString( ){
return “id=” + id + ”,grade=” + grade; }
public static Student hasHigherGrade( Student s1, Student s2 ){ return (s1.grade > s2.grade ? s1:s2);
}
For each of the questions: J1.1) – J1.10), read the Java application and write the output on the screen or write ERROR if there is any error in the code. The class Student is correct.
J1.1)(1 point) public class Test1{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75); System.out.println( s1.grade );
}//end main
}//end class Test1
ANSWER: ERROR
J1.2)(2 points) public class Test2{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75); System.out.println( s1.getGrade( ) );
}//end main
}//end class Test2
ANSWER: 80
J1.3)(1 points) public class Test3{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75);
System.out.println( s2.increaseGrade( 10 ) );
}//end main
}//end class Test3
J1.4)(2 points) public class Test4{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75); System.out.println( s1.toString( ) );
}//end main
}//end class Test4
ANSWER: id=100,grade=80
J1.5)(1 point) public class Test5{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75); Student s3 = new Student( 70, 98); System.out.println( Student.count );
}//end main
}//end class Test5
ANSWER: 3
J1.6)(2 points) public class Test6{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75); Student s3 = new Student( 70, 98); Student s4 = s1;
System.out.println( s4.count );
}//end main
}//end class Test6
J1.7)(1 points) public class Test7{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75); System.out.println( Student.getId( ) );
}//end main
}//end class Test7
ANSWER: ERROR
J1.8)(2 points) public class Test8{
public static void main( String args[ ] ){ Student s5 = new Student( 107, 83); Student s6 = new Student( 160, 67); s6 = s5;
s6.increaseGrade( 10 );
int n = s5.increaseGrade( 12 ); System.out.println( n );
}//end main
}//end class Test8
ANSWER: 100
J1.9)(1 point) public class Test9{
public static void main( String args[ ] ){ Student s3 = new Student( 90, 72); Student s4 = new Student( );
System.out.println( s4.getId( ) );
}//end main
}//end class Test9
J1.10)(2 points) public class Test10{
public static void main( String args[ ] ){ Student s1 = new Student( 100, 80); Student s2 = new Student( 101, 75);
System.out.println(Student.hasHigherGrade(s1,s2).getId());
}//end main
}//end class Test10
ANSWER: 100
JAVA Programming Question
J2)(20 points )
The Java class Account, whose incomplete definition is written below, is meant to model bank accounts. Each Account object has an id and a balance.
Complete the definition of the methods of class Account according to each method description. Further, complete method main of the class TestAccount according to the requirements in the comments.
public class Account{ private int id;
private double balance;
//initializes id to anId and balance to 0 (1 point) public Account( int anId ){
id=anId; balance=0.0; }
//returns the id of the account on which the method is called (0.5 point)
public int getId( ){ return id;
//returns the balance of the account on which the method is called (0.5 point)
public double getBalance( ){ return balance;
}
//deposits amount into the account on which the method is called //(i.e., balance is increased by the quantity specified by amount); //the method first checks if amount is larger than 0; if yes it //deposits; if no it does nothing. (2 points)
public void deposit( double amount ){ balance += amount>0 ? amount : 0; }
//withdraws amount from the account on which the method is called //(i.e., the balance is decreased accordingly); precisely the //method does the following: if amount is larger or equal to 0 and //smaller or equal to balance it withdraws,if amount is negative, //it does nothing; if amount is larger than balance it prints the //message: Insufficient funds. (3 points)
public void withdraw( double amount ){ if(amount <= balance )
{ if( amount >= 0 ) balance -= amount; }
else
System.out.println( "Insufficient funds.") }
}//end class Account
public class TestAccount{
public static void main( String args[ ] ){
//create account1(object of the class Account) with id 100 (1 point)
Account account1 = new Account( 100 );
account1.deposit( 1500 );
System.out.println( account1.getBalance( ) );
//an array of 10 accounts is created; the id's are all integers between //1 and 10
Account array[ ] = new Account[ 10]; for(int i=0; i<10; i++)
array[i] = new Account( i+1 );
//assume all these accounts are yours; assume money have been //deposited into these account, so they are not empty; you need to //withdraw 4000 dollars; write below the code to check if this amount //is covered by the total in your accounts; if not print
//the message "Amount not covered"; if yes withdraw this amount (not //less, not more); you may need to clear some accounts (10 points)
//4 points
double total=0;
for(int i=0; i<10; i++)
total += array[ i ].getBalance( );
if( total < 4000 )
System.out.println( "Amount not covered." ); else//6 points
{
double amount=4000, temp=0; for(int i=0; i<10; i++ )
{
temp= amount <= array[i].getBalance( ) ? amount:
array[i].getBalance( );
array[i].withdraw( temp );
amount -= temp;
}
}
}//end main
Q)(10 points) Bonus Question:
Consider the following structure type definition in C: typedef struct{
double x; double y; } Point;
The structure type Point models points in the plane. Member x corresponds to the x coordinate and member y corresponds to the y coordinate of a point (in an orthogonal system of coordinates).
Write a C function isClockwise( ) with the following prototype
int isClockwise( Point a, Point b, Point c);
The parameters received by the function represent three points A, B and C in the plane. The function should return 1 if the points A, B and C are in clockwise order, and it should return 0 otherwise. You may assume that the points A, B and C are not situated on the same line.
int isClockwise( Point a, Point b, Point c){
return (b.y-a.y)*(c.x-a.x)-(c.y-a.y)*(b.x-a.x)>0; }
NOTE: It was realized after the midterm that the formulation of this problem has led to multiple interpretations. The original intended meaning of the fact that the three points A, B and C are in clockwise order was the following: assume the three points are on a circle(we can always draw a circle to pass through any three points). Then starting from point A and going around the circle in clockwise sense we first encounter point B and after that point C (not conversely).
The second interpretation which some students considered (or were advised to consider) is the following: the points A, B and C are in clockwise order if the semi-lines OA, OB and OC are in clockwise order around the origin.
Both interpretations will be considered correct.