• No results found

A3)(2 points) int a[ ] = {2,4,6,8,10,12,14,16,18,20};

N/A
N/A
Protected

Academic year: 2020

Share "A3)(2 points) int a[ ] = {2,4,6,8,10,12,14,16,18,20};"

Copied!
14
0
0

Loading.... (view fulltext now)

Full text

(1)

COE2SH4 - PRINCIPLES OF PROGRAMMING

1ST M

IDTERM SOLUTIONS

FALL, 2006

F

ILL IN

T

HE BLANKS

A1) – A4) Evaluate the following expressions, and write the values in the blanks.

A1)(1 point)int x = 4; int y = 10;

(double)(x/y)= 0.0

A2)(1 point) double a=6.0; double b=-3.0;

int c;

c = ( a < 100 ) || ( b > 0);

c = 1

A3)(2 points) int a[ ] = {2,4,6,8,10,12,14,16,18,20}; int *p = &a[5];

*(--p) = 20;

a[4]= 20

A4)(2 points)

int n=(int)(6.2345 * 100)%100;

n = 23

A5) – A6) Complete the function prototype such that it matches the function call.

A5) (2 points)

(2)

double a = 10.8; double b = 4.5; function1( a, &b ) }

A6) (2 points)

int *function2( int array[ ]); or int *function2( int *ptr );

/* parameters names can be omitted */

main{

int n[]= {4, 5, 6}; int *kptr ;

kptr = function2( n ) ; }

C

ORRECT

T

HE

E

RRORS

(3)

B1) (4 points) Function copy_array receives an integer array a and its size length, as parameters. It copies the array a into another integer array b newly created, and returns the address of the new array b.

int *copy_array ( int a[], int length ) {

int i;

int b[length];

for (i =0; i <= length, i++ ) b[i] = a[i];

return b[0]; }

CORRECT:

int *copy_array ( int a[], int length ) {

int i;

int *b = calloc( length, sizeof(int));

/* or int *b = malloc( length * sizeof(int)); */

for (i =0; i < length; i++ ) b[i] = a[i];

return b;

/* or return &b[0] */ }

B2) (3 points) Function count_zeros receives as parameters a pointer aPtr to an integer array, and the size n of the array. It returns the number of array elements equal to 0.

int count_zeros( int *aPtr, int n ) {

int i; int count;

for( i=0; i < n; i++ ) if ( *aPtr + i = 0 )

(4)

CORRECT:

int count_zeros( int *aPtr, int n ) {

int i;

int count = 0;

for( i=0; i < n; i++ ) if ( *(aPtr + i) == 0 )

count++; return count; }

B3)(3 points) Function digits_number receives an integer parameter named number, and returns 1 if number is a positive even two-digit integer, or 0 otherwise. The function is not allowed to call any other function.

int digits_number( int number ) {

return ( sizeof(number) == 2); }

CORRECT:

int digits_number( int number ) {

(5)

B4) (4 points) The following program prints the multiples of 5 between 0 and 20, i.e.: 0 5 10 15 20

#include <stdio.h> main( )

{

int j=0;

while( j < 21 ) {

if ( j%5 == 0 ) continue; else

{ printf(“%d\t”, j); j++;

} } }

CORRECT:

#include <stdio.h> main( )

{

int j=0;

while( j < 21 ) {

if ( j%5 == 0 )

printf(“%d\t”, j); /* else

{ } */ j++; }

}

OTHER CORRECT VARIANT:

#include <stdio.h> main( )

{

int j=0;

(6)

{

if ( j%5 != 0 ) { j++; continue; } else

{ printf(“%d\t”, j); j++;

} } }

W

RITE

T

HE

O

UTPUT

C1) (3 points) Read the following C program and write the output on the screen:

#include <stdio.h> int function1(int x) {

int sum = 0; while( x != 0 ) {

sum += x%10; x = x/10; }

return sum; }

main() {

int data = 1995;

printf("%d", function1(data)); }

ANSWER: 24

(7)

on the screen:

#include <stdio.h>

void function2( char* ptr, char c1, char c2 ) {

while( *ptr != ‘\0’ ) {

if( *ptr == c1 ) {

*ptr = c2; break; }

ptr++; }

}

main( ) {

char string[]="McMaster University"; function2( string, 't', 'T' );

printf( “%s”, string ); }

ANSWER: McMasTer University

P

ROGRAMMING

Q

UESTIONS

D1)(10 points) Write a function reverse to print a string on the screen backwards. The function prototype should be

void reverse( char *str );

For example, after the function call reverse( “Student” );

The output on the screen should be tnedutS↓

where ↓ is the newline character.

(8)

void reverse( char *str ){

int length=0; /* string length */

/*find length by incrementing the pointer until end of string*/

while( *str != '\0') { length++;

str++; }

/*print backwards by decrementing pointer until beginning of string*/

while( length > 0 ) {

str--;

printf("%c", *str ); length--;

}

printf("\n" ); }/*end function*/

D2)(10 points) Write a function array_max with the following prototype

void array_max( int c[ ][N], int m , int d[ ] );

Its parameters are a double subscripted array c with N columns and m rows, an integer m specifying the number of rows of array

c, and a single subscripted array d with N elements.

The function should do the following: for each column j of the 2D array c, find its maximum element and store it in d[j]. You may assume that all values stored in c are larger than -100.

For example if N=3 and the array c passed to the function is -3 9 7

5 0 12 1 -6 4 10 5 -1

(9)

void array_max( int c[ ][N], int m , int d[ ] ){

int i; /* row index for array c */

int j; /* column index for array c */

for(j=0; j<N; j++) { d[j]=-100;

/*for each column j find maximum*/ for(i=0; i<m; i++)

{

if( c[i][j] > d[j]) d[j]=c[i][j]; }/* end inner for */ }/* end outer for */ }/*end function */

D3)(15 points) Consider the following system of n simultaneous linear equations with n unknowns:

a(1,1)x(1) = b(1)

a(2,1)x(1) + a(2,2)x(2) = b(2)

a(3,1)x(1) + a(3,2)x(2) + a(3,3)x(3) = b(3)

a(4,1)x(1) + a(4,2)x(2) + a(4,3)x(3) + a(4,4)x(4) = b(4) ...

a(n,1)x(1) + a(n,2)x(2) + a(n,3)x(3) + .... + a(n,n)x(n) = b(n)

where x(1), x(2), …, x(n) denote the unknowns, b(1), … ,b(n) , and a(1,1), …, a(n,n) are known values.

Note that the matrix A of coefficients (whose elements are a(i,j) ) is lower triangular, i.e., all the elements above the main diagonal are 0. A solution to this system is a set of n values, one value for x(1), one for x(2), one for x(3), and so on, one for x(n), such that by replacing each x(i) with its value all the above equalities to hold.

The determinant of the matrix A, denoted by det(A), is just the product of the elements on the main diagonal

det(A) = a(1,1)*a(2,2)*a(3,3)*…*a(n,n).

(10)

a unique set of values, one for each x(i) ) and this solution can be easily found as follows. Find the value of x(1) from the first equation. Then replace the value found for x(1) in the second equation and find the value of x(2). Then replace the value for x(1) and the value for x(2) in the third equation and find x(3). Proceed like these and find x(4), x(5), …, x(n).

Write a function solve to find the solution of a system of linear equations as above. Its prototype should be

double *solve( double a[ ][N], double b[ ])

Its parameters are: a 2D array a with N rows and N columns (storing the matrix coefficients a(i,j)), a 1D array b of size N, storing the known values b(1), b(2),.., b(n). Assume N=n.

This function should first check if the determinant of the matrix is zero. Do this by checking that

fabs(det(A)< TOL )

where fabs() is a function declared in math.h, which returns the absolute value of its argument. Assume TOL is a defined constant which specifies the precision accepted. det(A) should be computed.

If the above condition holds then the function should return a pointer to NULL and print the message:

The system is singular.

(11)

double *solve( double a[ ][N], double b[ ]){

double det=1;/*matrix determinant*/

int i,j;

double *x=NULL;/* pointer initialized to NULL */ /* find determinant */

for( i=0; i<N; i++) det *= a[i][i];

if( fabs(det) < TOL )

printf("The system is singular.\n");

else

{

x=malloc( N*sizeof(double) );/* allocate dynamically memory for solution array*/

for(i=0;i<N;i++)

{/*compute x[i]; x[j] are elements of x[ ] used to compute x[i]*/

x[i]=b[i];

for(j=0;j<i;j++)

x[i] -= a[i][j]*x[j]; x[i] /= a[i][i];

}/* end outer for */ }/* end else */

return x; /* return x in both cases*/ }/* end function */

D4)(15 points) Since the matrix A in the previous exercise is lower triangular, it can be stored in efficient format by skipping the zeros above the diagonal. Therefore, only an 1D array with N(N+1)/2 elements can be used to store the elements of A, row by row skipping the zeros above the diagonal, i.e.:

a(1,1) a(2,1) a(2,2) a(3,1) a(3,2) a(3,3) a(4,1) a(4,2) …. a(n,n)

Write a function solve_efficient to solve the same system of equations as in the previous exercise by using the efficient format of the matrix A. Its prototype should be

double *solve_efficient( double effA[ ], int n, double b[ ] ) ;

(12)

b is a 1D array of size n, storing the known values b(1), b(2),.., b(n). The function is not allowed to restore in memory the whole matrix A.

double *solve_efficient( double effA[ ], int n, double b[ ] ) {

double det=1;

int i=0,j,k=0;

double *x=NULL;

/*compute det; i is index in effA[ ]; first: i=0; then i=i+2; then i=i+3; then i=i+4;... last: i=i+n*/

for(j=1; j<=n; j++, i = i+j ) det *= effA[i];

if( fabs(det) < TOL )

printf("The system is singular.\n"); else

{

x=malloc( n*sizeof(double) );

/*compute solution: 1st operation uses effA[0]; 2nd operation uses effA[1]; 3rd op uses effA[2] and so on; after each operation index k of array effA[ ] is incremented by 1;

i is index in solution array x[ ]; j is index for elements of x[ ] used to compute x[i] */

for(i=0,k=0;i<n;i++) {

x[i]=b[i];

for(j=0;j<i;j++) {

x[i] -= effA[k]*x[j]; k++;

} /* end inner for */ x[i] /= effA[k];

k++;

} /*end outer for*/ } /* end else*/

(13)

D5)(20 points ) Write a function

int eff_min ( int *array, int n );

The argument passed to this function is a pointer to an array of integers which has the following property. It has a unique minimum element. Moreover, its elements from the beginning of the array until the minimum element are in strictly decreasing order, and from the minimum element until the end of the array are in strictly increasing order. An example of such an array is the following; 34 20 9 -2 -1 4 7 89 100

The function should find the minimum element stored in this array

efficiently by using the method of binary search, and return its array index. For the above example the function should return the value 3.

Note: In this problem we do not have a key to search for. However, because the array has the property described above, the idea of binary search can be used here to find the minimum array element efficiently.

We assume that neither the first, nor the last element of the array can be the minimum.

int eff_min ( int *array, int n ){

int low=0, high=n-1, middle;

while( low<=high )/* current array is not empty */ {

middle = (low + high)/2;

/* if element in the middle is min */

if ( ( array[middle] < array[middle - 1] ) && ( array[middle] < array[middle + 1] ))

return middle;

else /* i.e., middle element is not minimum */ /* if min is to the right of middle element */ if( array[middle] > array[middle + 1] )

low = middle; /*resume search in half to the right; by including the element previously checked in the new array we ensure that the array preserves the property outlined in bold above*/

(14)

high = middle; /*resume search in half to the left*/ }/* end while loop */

References

Related documents

Violation: Unfit or incompetent by reason of negligence, habits or other cause; and guilty of unprofessional conduct, to wit: failure to maintain a record for each patient which

Although total labor earnings increase with the unskilled unions’ bargaining power, we can say nothing when the increase in production is due to stronger skilled unions, since

2 2.17 LOSA Voluntary Program Not Requiring FAA Approval, Acceptance or Monitoring 2 2.17 LOSA Helps Provide Feedback of Safety Related Events To Management or Employees 1

Some traces of this influence &amp;ve seen even in the Ionic inscriptions of the fifth century, especially in the islands, and in the fourth century the majority of inscriptions show

0% 2% 4% 6% 8% 10% 12% 14% 16% 18% 20% Industrials Materials Consumer Staples Financials Health Care Energy Consumer Discretionary Information Technology Utilities

The key feature of customs crime is that it implies carrying goods over the customs line while avoiding customs inspection for the purpose of evading customs control and thereby

AQUILA intra-domain QoS analysis and monitoring is aimed at collection of QoS measurement information characterising QoS properties of traffic flows and their aggregation in

If the return result to an operation is an array, the array storage is dynamically allocated by the stub; a pointer to the array is returned as the value of the client stub