Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

APSC 160

SAMPLE FINAL EXAM QUESTIONS

Q1. For each of the multiple choice questions below, circle the one best answer.

Q1A. What does a C language compiler do?

a)   translate from C into machine language

b)   verify correctness of a program

c)   process directives like #include and #define before running the program

d)   organize all the C program files in a directory

Q1B. Which is the correct way to declare a variable s containing the string foo?

a)   char s = 'foo';

b)   char s = "foo";

c)   char s[] = "foo";

d)   char s[] = foo\0;

Q1C. Which of the following expressions is always TRUE? Assume p is an int variable.

a)   p || !p

b)   p && !p

c)    !p || !p

d)   p && p

Q1D. A global variable

a)   is accessible to any function that wants to use it

b)   is initialized every time a function is called

c)   can not be changed

d)   allows faster access than a normal variable

Q1E. Character variables in C are passed to functions

a)   by name

b)   by reference

c)   by value

d)   as strings

Q2. Write a function in C that computes and returns (as a double value) the sum of the following series of numbers:

1 + x + x2 + x3 + x4 + … + xN- 1 + xN

where the integer N and the double x are passed to the function as  parameters.  Here are some examples:

N x value returned explanation

1

4

1.75

Note that your function is not expected to print the explanation this has been provided only to help you understand what the function is supposed to do. For full marks on this question, do not use the pow math library function or any function that you write yourselfthat computes one       number raised to the power of another. Note that arrays are not needed in this question and must not be used.

Q3. Explain in plain English the purpose of the following function:

/*

* Param: data an array of integers

* Param: numVals the number of entries in the array

* Param: checkValue a threshold value

*/

int procList( int data[], int numVals, int checkValue ) {

int count = 0;

int index;

for( index = 0; index < numVals; index++ ) {

if( data[ index ] > checkValue )

count++;

}

return count;

}

Q4. Explain in plain English the purpose of the following function.  Assume that TRUE, FALSE and

SIZE are symbolic constants defined with appropriate values.

/*

* Param: data  - a two dimensional array with SIZE rows

*                  and SIZE columns

* Param: nRows - a value representing a number of rows in

*                  the array data such that 1 <= nRows <= SIZE

*/

int checkArray( int data[SIZE][SIZE], int nRows ) {

int isSomething = TRUE;

int row;

for( row = 0; row < nRows; row++ ) {

int col;

for( col = row + 1; col < nRows; col++ ) {

if( data[row][col] != data[col][row] )

isSomething = FALSE;

}

}

return isSomething;

}

Q5. Assume that the following function has already been written and is available for you to use in

this question:

/*

* Draws a character a specified number of times in a row

* Param: numChars - the number of times to print the character

* Param: printChar - the character to print

*/

void printChars( int numChars, char printChar );

Write a function named drawRamp that:

.    takes a positive integer representing a number of rows as its only parameter

.    draws a ramp of *'s having the given number of rows.

Your function must make use of the printChars function described above. Here are some examples:

number of rows:          1            2            3

ramp drawn:                *            *            *

***          ***

*****

Q6.

Assume we have a text file that contains an unknown number of rows of data. On each row there are three integer values, each separated from the next by a space. Write a function that takes a      pointer to the file as its only parameter. The function must determine whether or not the entries   on every row of the file are in decreasing order. If all rows of data have entries in decreasing        order, the function must return TRUE otherwise it must return FALSE. Do not process more rows of data than necessary. Assume that the file has already been opened for reading. Further            assume that TRUE and FALSE are symbolic constants defined with appropriate values.

Sample file: Sample file:

3 2 1                     3 2 1

3 0 -2                         3 0 -2

5 3 3                      5 3 4

8 4 0                      8 4 0

Function produces TRUE as entries on            Function produces FALSE as at least one row (the

every row are in decreasing order.                   3rd) does not have its entries in decreasing order.

/*

* Determines whether all the rows of a file have their entries

* in decreasing order .

*

* Param:   inFile pointer to file that contains the integer values,

*                      already opened for reading

* Returns: TRUE if the data on every row of the file is in

*           decreasing order, FALSE otherwise .

*/

int allRowsDecreasing( FILE* inFile ) {

Q7. A quality control engineer must ensure that ball bearings manufactured by her company conform

to the advertised standards. She has a file called ballBearings.dat that contains information   about a sample of ball bearings.  Each row of the file contains data about one ball bearing.  Data is organized into two columns of non-integer values separated by a space. The first column        contains a diameter in mm and the second a weight in grams. There is no other data in the file.   The number of lines of data in the file is not known but you can assume that there is at least one line of data.

A ball bearing is considered to be within accepted standards if ( 9.95 < diameter < 10.02 ), otherwise it is rejected. We want to write a program that reads the file ballBearings.dat described above and determines the percentage of ball bearings that meet accepted standards and the percentage that are rejected. The program must display these percentages on the screen to 1 decimal place along with appropriate labels.

The partially completed program appears below and on the following pages.  To complete it you must implement the functions:  doQualityControl and  printReport.

Carefully read through all of the provided code, including comment statements, before writing any code!

#include 

#include 

#define SOURCE "ballBearings.dat"

#define MIN_DIAM 9.95

#define MAX_DIAM 10.02

void doQualityControl( FILE* );

void printReport( int, int );

int main( void ) {

FILE* inFile;

inFile = fopen( SOURCE, "r" );

if( inFile == NULL ) {

printf( "Error opening input file, program terminating .\n" );

}

else {

doQualityControl( inFile );

fclose( inFile );

}

system( "PAUSE" );

return 0;

}

/*

* Performs quality control on ball bearing data. *

* (Hint: calls printReport to print final report on screen) *

* Param: inFile - points to file containing ball bearing data */

void doQualityControl( FILE* inFile ) {

/*

* Prints a report showing the percentage of ball bearings that are

* accepted and rejected. *

* Param: numAccept - number of ball bearings that are accepted

* Param: numReject - number of ball bearings that are rejected */

void printReport( int numAccept, int numReject ) {

Q8. Be sure to read the entire question before you write any code!

In this question you will write a program in C that will allow a user to convert currencies. When  the program starts up an introduction message is displayed which tells the user what the code       numbers for the supported currencies are. The user is then prompted to input the currency type to convert from (the user enters an integer here), the amount to convert (the user enters the amount), and the currency type to convert to (also represented by an integer). When this data has been        entered the program displays the converted amount with two decimal points accuracy. After the   conversion the program asks the user if another conversion is wanted. If so the steps listed above (including the introduction message) are executed again. If not the program terminates

Here is a sample run. User input is in bold type:

> Welcome to CConvert 1.0.

> 1=USD, 2=CAD,3=EUR,4=ITL,5=DEM,6=NLG,7=FRF,8=CHF

> Enter currency to convert: 2

> Enter the amount to convert: 120.15

> Enter currency to convert to: 1

> 120.15 CA$ equals 106.46 US$

> Do you wish to convert again? (Y/N): Y

> 1=USD, 2=CAD,3=EUR,4=ITL,5=DEM,6=NLG,7=FRF,8=CHF

> Enter currency to convert: 6

> Enter the amount to convert: 20.65

> Enter currency to convert to: 5

> 20.65 Dutch Guilder equals 18.34 DM

> Do you wish to convert again? (Y/N): N

> Bye!

The following diagram is a modular structure chart to represent the design of the program that   you will write.  Assume that the functions in white boxes have been given to you, you do not     have to write them, just use them. A description of each function appears below in the prototype section of the code.

main


doAgain

getUSValue


In the questions that follow, you may assume that the following code has already been inserted at the top of the file:

#include 

#include 

#define TRUE 1

#define FALSE 0

/* Given functions (you can use them, but dont have to write them) */

/* print to screen (without newline) the name of currency with code c

*/

void printName(int c);

/* prompt the user for Y or N, returns FALSE if user entered N, TRUE if Y

*/

int doAgain(void);

/* Get the US$ value of 1 unit of specified currency with code c

*/

double getUSValue(int c);

/* print to screen the help message with the currency codes . In the example

above this was:

1=USD, 2=CAD,3=EUR,4=ITL,5=DEM,6=NLG,7=FRF,8=CHF

*/

void printHelpMessage(void);

/* Functions you will have to write */

/* convert amount from currency fromCode to currency toCode and return

converted amount

*/

double convertCurrency(double amount,int fromCode,int toCode);

/* print to screen the result of the conversion in precisely the format

given in the example run above . For example “12 .12 US$ equals 13.68 CA$

*/

void printResult(double convertedAmount,double fromAmount,

int fromCode,int toCode);

/* main function and function implementations follow below this */


a) Complete missing parts of the function main. You don’t have to check the user input for correctness.

int main(void) {

int fromCode,toCode;

double fromAmount,convertedAmount;

printf("Welcome to CConvert 1 .0 .\n");

do {


convertedAmount = convertCurrency(fromAmount,fromCode,toCode);

printResult(convertedAmount,fromAmount,fromCode,toCode);

} while(                                               );

printf("Bye!\n");

return 0;

}


b) Write the complete implementation of the function convertCurrency.

c) Write the complete implementation of the function printResult. Hint: look at the modular structure chart to see if you can use one of the provided functions.

Q9. Complete the program provided below so that it prompts the user for a series of positive integers.

The user enters the value - 1 to indicate that there is no more data to enter.  The function must       print the smallest and largest of the integer values entered by the user (excluding the value - 1).  If the first value entered by the user is - 1 (in other words, no positive integers are entered), your       program must print an error message and terminate. Here are a couple of sample runs:

Sample run #1

Enter a series of positive integers,

terminated by -1:

-1

ERROR: no data entered!

Press any key to continue . . .

Sample run #2

Enter a series of positive integers,

terminated by -1:

4

2

10

3

-1

Minimum value: 2, maximum value: 10

Press any key to continue . . .


#include 

#include 

#define SENTINEL -1

int main( void ) {


Q10. Write a function countZerosInCols that takes a two dimensional array of integers and the

number of rows in that array as parameters.  The function takes a third parameter zerosInCol that is a one dimensional array whose size matches the number of columns in the two                  dimensional array.  After a call to this function is made, zerosInCol[i] contains the number of entries in the ith column of the two dimensional array that are zero.   We assume that NROWS and NCOLS are symbolic constants that have been defined to be the number of rows and number of columns in the two dimensional array, respectively.

So, for example, suppose we declare the following arrays:

int data[][NCOLS] = { { 2, 4, 5, 1 }, { 3, 0, 2, 1 }, { 2, 4, 5, 1 },

{ 3, 0, 2, 7 }, { 4, 3, 0, 6 } };

int zerosInCol[NCOLS];

and then make the function call:

countZerosInCols( data, NROWS, zerosInCol );

After this call ends, zerosInCol will have the values { 0, 2, 1, 0 }.  Note that there are no zeros in the first column of data, 2 zeros in the second column, 1 in the third, etc.

Note: in the interests of time, it is not necessary to write any comment statements.

Q11. Write a function that takes two input parameters.  The first input parameter is a string (a char array), and the second parameter is a single character (char).  The function counts how many  times the given character appears in the string and returns this result.  Your function must NOT use any of the functions in the string library (e.g. strlen), or any other functions.

Q12. In this question you will develop a program that generates elementary math problems for kids.   The program creates random problems using one of the operators '+', '-' and '*'.  The operands    (the numbers to operate on) are integers between 0 and 9 (including 0 and 9).  Ten questions are generated and the user gets a maximum of 3 attempts at each question.  The percentage of          questions answered correctly is reported to the user before the program quits.

Here is part of a sample run showing interaction with the user for questions 2 and 3 only, as well as the final report printed after all questions have been attempted (recall that a total of 10              questions is asked each time the program is run).  The reported score in this example assumes      that the user came up with the right answer, within the maximum number of attempts, on 9 of the 10 questions asked.  Study this output carefully.

<>

Question #2:

4 - 3 = ?

You have 3 attempts remaining.  Enter your answer...

2

Your answer is not correct .

You have 2 attempts remaining .  Enter your answer . . .

1

Correct!

Question #3:

7 * 4 = ?

You have 3 attempts remaining.  Enter your answer...

24

Your answer is not correct .

You have 2 attempts remaining .  Enter your answer . . .

7

Your answer is not correct .

You have 1 attempts remaining .  Enter your answer . . .

4

You have no more attempts remaining .

The correct answer is 28

< #10 omitted>>

Your score is 90.0 percent.

Your task is to complete the program presented on the following pages.  To do this you must:

- insert code into the two underlined blank spaces provided in main

- complete the function generateQuestion by inserting code to determine the correct answer to the question and return it

- complete the function getUserAnswer

- complete the function processUserAnswers

It is recommended that you carefully read the documentation for all functions before you attempt to write any code.