Docsity

Sample Problems with Solutions - C++ Functions | CSCI 261, Study notes of Computer Science

Toggle sidebar
bg1
CSCI261 Lecture Questions C++ Functions
This worksheet is for your use during and after lecture. It will not be collected or graded, but I think you will find it a
useful tool as you learn C++ and study for the exams. Explain all false answers for the “True or False” questions; in
general, show enough work and provide enough explanation so that this sheet is a useful pre-exam review. I will be
happy to review your answers with you during office-hours, via Email, or instant messaging.
1. True or False:
Calc%O2
is a valid C++ function name. If false, state why.
Solution: False, function names follow the rules for C++ variable names, also called identifiers.
%
cannot be
used in C++ identifiers.
2. True or False: You have not written any user-defined functions in Labs 1 through 5. If false, name the function or
functions.
Solution: False, in each lab, at least one
int main()
function was written.
3. Write the function definition for a function that returns the sum of
int
and
double
arguments as a double value.
Call the function
silly_sum
.
Solution:
double silly_sum( int a, double b )
{
re t u rn a + b ;
}
4. True o r False: The comp iler must encounter every function’s prototype or definition b efore it is used in a program
listing. If false, cite a counter example.
Solution: True.
5. True or False: Every user-defined function must have a prototype in the same source file as its function definition.
If false, cite a counter example.
Solution: False. Pr ototypes may be provided in files used with
#include
statements. Consider, for instance,
that the library function protoype
double sqrt( double x );
is provided this way via
#include <cmath>
.
6. (a) Write a function prototype for your answer to question 3.
Solution:
double silly_sum( int a, float b );
(b) Can you write another, equally correct, function prototype for question 3?
Solution:
double silly_sum( int, float );
Omitting argument names from prototypes is generally considered a poor programming practice.
7. What is a
void
function?
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Sample Problems with Solutions - C++ Functions | CSCI 261 and more Study notes Computer Science in PDF only on Docsity!

This worksheet is for your use during and after lecture. It will not be collected or graded, but I think you will find it a

useful tool as you learn C++ and study for the exams. Explain all false answers for the “True or False” questions; in

general, show enough work and provide enough explanation so that this sheet is a useful pre-exam review. I will be

happy to review your answers with you during office-hours, via Email, or instant messaging.

1. True or False: Calc%O2 is a valid C++ function name. If false, state why.

Solution: False, function names follow the rules for C++ variable names, also called identifiers. % cannot be

used in C++ identifiers.

2. True or False: You have not written any user-defined functions in Labs 1 through 5. If false, name the function or

functions.

Solution: False, in each lab, at least one int main() function was written.

3. Write the function definition for a function that returns the sum of int and double arguments as a double value.

Call the function silly_sum.

Solution:

double silly_sum ( int a , double b ) { return a + b ; }

4. True or False: The compiler must encounter every function’s prototype or definition before it is used in a program

listing. If false, cite a counter example.

Solution: True.

5. True or False: Every user-defined function must have a prototype in the same source file as its function definition.

If false, cite a counter example.

Solution: False. Prototypes may be provided in files used with #include statements. Consider, for instance,

that the library function protoype double sqrt( double x ); is provided this way via #include .

6. (a) Write a function prototype for your answer to question 3.

Solution: double silly_sum( int a, float b );

(b) Can you write another, equally correct, function prototype for question 3?

Solution: double silly_sum( int, float );

Omitting argument names from prototypes is generally considered a poor programming practice.

7. What is a void function?

Solution: A void function does have a return value or return type. It is useful only for its side-effects.

8. Write the function definition for a void function that does not accept arguments and does nothing.

(a) Call the function Super_Void.

Solution:

void Super_Void ( void ) { return ; }

(b) Now, write a different function definition for the same void function that differs by one word.

Solution:

void Super_Void ( ) { return ; }

void Super_Void ( void ) { }

void Super_Void ( ) { }

Either of the first two will work (since the question specifies only one word to be different). In general,

these are the 4 ways to write the function definition described. The answer to part a and these three

variations.

9. True or False: There are two different techniques for a programmer to show that a function does not return a value.

Solution: False. The only way to declare a void function is to use the void keyword before the function

name in its prototype or definition.

10. Write the prototype for a function that returns a Boolean value and does not accept any arguments. Call the

function DecisionMaker.

Solution:

bool DecisionMaker(); or bool DecisionMaker(void);

13. Explain in detail the difference between the two function prototypes below, and what they mean to the program-

mer using these functions.

int a( int i, string& s ); int b( int& i, string& s );

Solution: In the function a, the first arguement is provide by value, changes to i within the statements of a

does not change the value of i in the caller. The function b passes i by reference, so changes to i within the

statements of b will be seen by the caller.

14. (a) What limitation does the return value have for a (non-void) function that must communicate values back to

its caller?

Solution: A return statement can communicate only one value back to the caller.

(b) What mechanism may be used by a function that must communicate more than one data value back to its

caller?

Solution: Declare (non const) parameters passed by reference, and place extra “return values” in these.

15. (a) Write a function called CircleMeasures that is called with the radius of a circle (as a double) and calculates the

diameter, circumference, and area for the caller.

Solution:

include < cmath >

using namespace std ; / ∗ ∗∗ ∗ r e t u r n s t h e area , v a l u e s d i a m e t e r and c i r c ∗ / double CircleMeasures ( double r , double & diameter , double & circ ) { const double PI ( acos ( -1)); diameter = 2* r ; circ = diameter * PI ; / / or , 2 ( p i ) r i f y ou l i k e return PI * pow (r ,2); / / a r e a i s p i ∗ r }

(b) In what ways might your classmates’ answer differ from yours yet still be correct?

Solution: They may choose to write a void function and return all three measurements through reference

parameters, or they might return a different measurement than my solution, and provide the other two through

reference parameters.

16. Consider the code snippet below to answer the questions at the right.

4 int add_two ( int a , int & b ) 5 { 6 b -= 1; 7 a += 1; 8 return a + b; 9 } 10 11 int add_three ( int a , int & b , int c ) 12 { 13 return add_two ( add_two ( a , b ) , c ); 14 } 15 16 int main () 17 { 18 int a = 10; 19 int b = 20; 20 int c = 0; 21 22 cout << add_three ( a , b , c ) << " " ; 23 cout << a << " " << b << " " << c ; 24 cout << endl ; 25 26 return 0; 27 }

(a) Does this snippet represent function composition? On

which lines?

Solution: Yes, at line 13. The argument of the

outermost add_two comes from the return value

of an add_two call.

(b) How many times is line 8 traversed by the CPU? What

are the values of a and b each time?

Solution: See below.

(c) What is printed by main()?

Solution:

Solution: On the next page, I go through this solution in rather fine detail, attempting to explain every step by

the compiler and CPU. Once you become comfortable with functions and the passing of variables by value and

reference, this much detailed analysis is rarely needed. By the time Exam 1 arrives, you should be able to work

this problem out in about 5 minutes.

17. Which of the following will the compiler use to distinguish functions by their signatures.

A. Function return type

B. const-ness of function return type

C. The const-ness of a user-defined class’ member function

D. The user-defined class containing a member function

E. The argument types

F. The order of argument types

G. The argument names

H. The order of argument names

I. The const-ness of function arguments

Solution: C, D, E, F, I.

18. Consider the following snippet of code:

3 void f( int x , double y ); 4 int f ( const string & s , int x ); 5 double f ( string & s , int x ); 6 double f ( string & s , double y ); 7 8 int main () 9 { 10 const string greeting ( " hello " ); 11 string farewell ( " good - bye " ); 12 int i ( f( greeting , 3 )); 13 f ( i , f ( farewell , 3.0 )); 14 return 0; 15 }

For the following line numbers, determine which functions

are called, and in what order (identify a function by its pro-

totype’s line number).

(a) Line 12.

Solution: f on line 4 (the only f that takes a

const string as first argument).

(b) Line 13.

Solution: First f on line 6 , then its result is pro-

vided as the second argument to f on line 3.

19. Consider the following snippet of code:

3 void f( int & x ); 4 void f( const int & ) const ; 5 bool f( int & ); 6 bool f( double y ); 7 bool f( int ); 8 bool f( double x ); 9 void f( int x ); 10 void f ();

Find the two pairs of functions prototypes with matching

signatures that will cause a compiler error.

Solution: The pair on lines 3 and 5. The pair on lines

9 and 7. The pair on lines 6 and 8 won’t cause an error

because they are prototypes for the same function sig-

nature (recall that argument names are ignored). The

compiler does not raise an error when it sees the same

prototype twice.

20. Below is a snippet of C++ source from a file named oops.cxx, and below that is an error listing generated during

a build attempt. Use the space at the right to explain how the code may be changed to resolve each error message.

1 # include < string > 2 # include < cmath > 3 using namespace std ; 4 5 int f ( int a ); 6 7 string g ( double f ); 8 9 void h ( int m , string & n ) 10 { 11 return ; 12 } 13 14 int main () 15 { 16 double product = j (); 17 string text ( " abc " ); 18 int result ; 19 double product_string ; 20 21 product_string = g( product ); 22 23 result = h ( f ( ’A ’ )+ h (0 , text ) , " xyz " ); 24 25 return 0; 26 } 27 28 double j ( void ) 29 { 30 return acos ( -1)* exp (1); 31 } 32 33 double f ( int a ) 34 { 35 return j () + a ; 36 }

Solution:

Line 16

A prototype for function j is not provided before j is

used in main. Add a protoype for j or place its entire

definition before the function main.

Line 21

product_string is declared as a double, and its

value is set to the return value of g. But the pro-

toype of g says it returns a string, not a double.

The compiler can automatically convert between dif-

ferent integer types, and integer types to doubles, but

it won’t automatically convert a double to a sequence

of ASCII characters.

Line 23

The function h is a void function — it doesn’t return

a value. But we are attempting to store its “return

value” in result. Remove the assignment of result

to correct this line of code.

Line 33

The prototype for function f does not match its func-

tion definition. Change the return types of f so that

they match.

undefined reference

This is a linking error. A prototype for function g is

provided, but the function definition, or implementa-

tion, has not been provided. Providing the definition

for string g( double ) corrects this.

ERROR LISTING

oops.cxx: 16 : error: ’j’ was not declared in this scope

oops.cxx: 21 : error: cannot convert string to double

oops.cxx: 23 : error: void value not ignored as it ought to be

oops.cxx: 33 : error: new declaration ’double f(int)’ ambiguates old declaration

undefined reference: string ::g( double )

21. In statistics, the mean or average value of a set of n data points is the defined by:

x ¯ =

n

n

i = 1

xi

Write a C++ function, named average, that accepts two arguments: a const array of doubles, and an integer

representing the number of elements in the double array. The function should return ¯ x.

22. Write a void function that accepts six arguments: a const int array of data, an const int size argument for

the array, an int argument named value, and two ints passed by reference named near and far. The function

should place into the near and far the element offset of the array value nearest value, and the element offset of

the value farthest from value.

For instance: if the argument is passed an array { 1, 13, 5, 8, 21, 2, 13, 3 } with value 6, it should place

into near the element offset of the element value 5, and into far the element offset of the element value 21.

23. The Fibonacci sequence is given by:

a 1 = a 2 = 1 , ai = ai − 1 + ai − 2

This sequence of numbers has a long history of study in both the mathematical^1 and biological world.^2 Now it’s

time to study them in wonderful world of C++ arrays. Write a function, aptly named fibonacci that accepts an

array of integers and an argument specifying the size of the array. fibonacci should initialize the array with as

many terms of the Fibonacci sequence as it will hold.

24. Recall from Calculus II that all our favorite trigonometric functions have associated ∞-series (remember the names

MacLaurin and Taylor?), for instance:

sin x = x −

x^3

x^5

x^7

∞

n = 0

(− 1 ) n^

x^2 n +^1

( 2 n + 1 )!

(a) Write a void function named sine_terms that accepts a non-const double array (call it terms), a size

argument for the array, and a double variable named x. The function should place into terms the first size

terms of the MacLaurin series of sin x.

(b) Calculus II also introduced the n th partial sum Sn of an ∞-series ∑∞ i = 1 ai as simply the sum of the first n terms:

Sn =

n

i = 1

ai

Now write the function sine_sums that accepts all the same arguments as in part a as well as a second non-

const double array named sums. sine_sums should first call sine_terms, and then calculate the partial

sums of the terms and place their values into sums. sine_sums should return the S size partial sum.

(^1) It is connected to the golden ratio in an incredibly elegant way. (^2) The minimal packing pattern of sunflower seeds, the turns and ridges of sea shells,...

Solution: A simple main() routine is provided on my course website for testing your code. When I run it

against my own solution, I get the following output:

The average of 1 and 0 zeros is 1 The average of 1 and 1 zeros is 0. The average of 1 and 2 zeros is 0. The average of 1 and 3 zeros is 0. The average of 1 and 4 zeros is 0. The average of 1 and 5 zeros is 0. The average of 1 and 6 zeros is 0. The average of 1 and 7 zeros is 0. The average The average of 1 andof 1 and 8 zeros9 zeros is 0.111111is 0. The average of 1 and 10 zeros is 0. The average of 1 and 11 zeros is 0. The average of 1 and 12 zeros is 0. The average of 1 and 13 zeros is 0. The average of 1 and 14 zeros is 0. The average of 1 and 15 zeros is 0. The average of 1 and 16 zeros is 0. The average of 1 and 17 zeros is 0. The average of 1 and 18 zeros is 0. The average of 1 and 19 zeros is 0. The first 20 Fibonacci terms are 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 Fib term 1 is closest to - Fib term 6765 is farthest from - Fib term 6765 is closest to 10000 Fib term 1 is farthest from 10000 Fib term 4181 is closest to 4184 Fib term 1 is farthest from 4184 Fib term 2584 is closest to 2585 Fib term 6765 is farthest from 2585 Fib term 5 is closest to 6 Fib term 6765 is farthest from 6 sin(3/2 * PI) = -1 (should be -1) sin(1) = 0.841471 (should be 0.84147...)

Here are my solutions for the programming problems:

2 ∗ C a l c u l a t e an a v e r a g e 3 ∗ / 4 double average ( const double data [] , const int size ) 5 { 6 double sum (0); 7 for ( int i (0); i < size ; i ++ ) { 8 sum += data [i ]; 9 } 10 11 return sum / size ; 12 } 13 14 / ∗ ∗∗ 15 ∗ F i b o n a c c i 16 ∗ / 17 void fibonacci ( int fib [] , const int size ) 18 { 19 / / 1 , 1 , 2 , 3 , 5 , 8 , 1 3 ,... 20 if ( size >= 1 ) { 21 fib [0] = 1; 22 } 23 if ( size >= 2 ) { 24 fib [1] = 1; 25 } 26 / / f i l l i n t h e r e s t 27 for ( int i (2); i < size ; i ++ ) { 28 fib [ i ] = fib [i -2] + fib [i -1]; 29 } 30 } 31 32

79 ∗ s i n e t e r m s 80 ∗ / 81 void sine_terms ( double terms [] , const int size , double x ) 82 { 83 / / be s a f e 84 if (! size ) return ; 85 86 / / t h e f a c t o r i a l t e r m 87 int factterm (1); 88 / / t h e d e n o m i n a t o r f a c t o r i a l v a l u e 89 double fact (1); / / f a c t o r i a l o f d e n o m i n a t o r 90 / / t r a c k s t h e s i g n o f eac h t e r m 91 double neg (1); / / f i r s t t e r m i s p o s i t i v e 92 / / t h e c u r r e n t pow er o f x 93 double powx ( x ); 94 / / pow ers o f x i n c r e a s e by x s q u a r e d 95 double xsquared (x * x ); 96 97 / ∗ ∗∗∗ 98 ∗ N ot e t h a t neg , powx , and f a c t a r e a l r e a d y i n i t i a l i z e d 99 ∗ f o r t h e f i r s t t e r m 100 ∗ / 101 102 for ( int i (0); i < size ; i ++ ) { 103 / / f i l l i n t h e t e r m 104 terms [i ] = ( neg * powx )/ fact ; 105 / ∗ ∗∗∗ 106 ∗ c a l c u l a t e d f a c t o r s f o r t h e n e x t t e r m 107 ∗ / 108 / / s i g n c hange 109 neg = - neg ; 110 / / n u m e r a t o r = n u m e r a t o r ∗ x ∗ x 111 powx *= xsquared ; 112 / / f a c t o r i a l i n c r e a s e s by t w o i n t e g e r v a l u e s 113 fact *= ++ factterm ; 114 fact *= ++ factterm ; 115 } 116 } 117 118

120 ∗ s i n e s u m s 121 ∗ / 122 double sine_sums ( double terms [] , const int size , double x , double sums [] ) 123 { 124 / / g e t t h e t e r m s 125 sine_terms ( terms , size , x ); 126 127 / / c a l c u l a t e p a r t i a l sums 128 double s (0); 129 for ( int i (0); i < size ; i ++ ) { 130 s += terms [ i ]; 131 sums [ i] = s ; 132 } 133 134 / / r e t u r n t h e p a r t i a l sum o f t h e f i r s t s i z e t e r m s 135 return sums [ size -1]; 136 }

Solution:

25 void Ax ( const double A [ MAXP ][ MAXP ] , const double x [] , 26 double product [] , const int p ) 27 { 28 / / f o r eac h row o f t h e m a t r i x A 29 for ( int arow (0); arow < p ; arow ++ ) { 30 double sum (0); 31 / / f o r eac h c om ponent o f t h e v e c t o r 32 for ( int xrow (0); xrow