6.096 Problem Set 2: 1 Additional Material

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

6.

096 PROBLEM SET 2


Due: 14 January 12:30:00

For this problem set, you should be able to put all your code for each section into a single
source/text file (though you may have to comment out earlier parts of your solution to test
later parts). Clearly mark each subsection with comments, and submit a .zip file containing
all your source/text files.

1 Additional Material
1.1 Functions
1.1.1 Default Arguments

Say you have a function with 1 argument, but that argument is usually the same. instance, say we
want a function that prints a messagentims, but most of the time it will only need to print it once:

1 void p r i n t N T i m e s ( char * msg , int n ) {


2 for ( int i = 0; i < n ; ++ i ) {
3 cout << msg ;
4 }
5 }

Rather than writingprintNTimes("Some message", 1); every time, C++


allowsde fault argumentsto be defined for a function:
1 void p r i n t N T i m e s ( char * msg , int n = 1) {
2 for ( int i = 0; i < n ; ++ i ) {
3 cout << msg ;
4 }
5 }

Declaring the function argument asint n = 1 allows us to call the function withprintNTimes("Some
message");. The compiler automatically inserts 1 as the second
argument.
You may have multiple default arguments for a function:
1 void p r i n t N T i m e s ( char * msg = " \ n " , int n = 1) {
2 for ( int i = 0; i < n ; ++ i ) {
3 cout << msg ;

1
4 }
5 }

Now, to print one newline, we can simplyprintNTimes();write . However, C++ does


not allow skipping arguments, so we could notknewlinesprint by writingprintNTimes(k);.
To do that, we’d need toprintNTimes("say \n", k);.

1.1.2 Constant Arguments


It’s often useful to specify that arguments to a function should be treated as constants.
with regular variables, we can declare function argumentsconstto : be
1 void print ( const int n ) {
2 cout << n ;
3 }

This is particularly useful when we are passing values by reference to a function, b


don’t want to allow the function to make any changes to the original value:
1 void print ( const long & x ) { // Pass - by - r ef e r en c e avoids overhead
2 // of copying large number
3 cout << x ;
4 }
5
6 int main () {
7 long x = 2 3 4 9 2 3 5 9 2 ;
8 print ( x ) ; // We are g u a r a n t e e d that x
9 // will not be changed by this
10 return 0;
11 }

In general, if you know a value shouldn’t be changing (particularly a function argument),


you should declare constit. That way, the compiler can catch you if you messed up a
tried to change it somewhere.

1.1.3 Random Number Generation Functions


The C++ standard libraries include rand()the function for generating random numbers

between 0 andRAND MAX (an integer constant defined by the compiler). These numbers
are not truly random; they are a random-seeming but deterministic sequence based on
particular “seed” number. To make sure we don’t keep getting the same random-numbe
sequence, we generally use the current time as the seed number. Here is an example
this is done:
1 # include < iostream >
2 # include < cstdlib > // C standard library
3 // defines rand () , srand () , RAND_MAX

2
4 # include < ctime > // C time f un c t io n s - defines time ()
5 int main () {
6 srand ( time (0) ) ; // Set the seed ;
7 // time (0) returns current time as a number
8 int randNum = rand () ;
9 std :: cout << " A random number : " << randNum << endl ;
10 return 0;
11 }

1.2 Pointers
1.2.1 Pointers to Pointers

We can have pointers to any type, including pointers to pointers. This is commonly us in C (and less
commonly in C++) to allow functions to set the values of pointers in their calling functions. For
example:
1 void s et S t ri n g ( char ** strPtr ) {
2 int x ;
3 cin >> x ;
4 if ( x < 0)
5 * strPtr = " Negative ! ";
6 else
7 * strPtr = " N o n n e g a t i v e ! " ;
8 }
9
10 int main () {
11 char * str ;
12 s et S t ri n g (& str ) ;
13 cout << str ; // String has been set by s et S t ri n g
14 return 0;
15 }

1.2.2 Returning Pointers


When you declare a local variable within a function, that variable goes out of scope
the function exits: the memory allocated to it is reclaimed by the operating system,
anything that was stored in that memory may be cleared. It therefore usually genera
runtime error to return a pointer to a local variable:
1 int * g e t R a n d N u m P t r () {
2 int x = rand () ;
3 return & x ;
4 }
5

3
6 int main () {
7 int * r a n d N u m P t r = g e t R a n d N u m P t r ()
8 cout << * r a n d N u m P t r ; // ERROR
9 return 0;
10 }

Line 8 will likely crash the program or print a strange value, since it is trying to memory that is no
longer in x usefrom–getRandNumPtr has been deallocated.

1.3 Arrays and Pointers


1.3.1 Arrays of Pointers
Arrays can contain any type of value, including pointers. One common application of th
is arrays of strings, i.e., arrayscharof* ’s. For instance:
1 const char * su i t Na m e s [] = {" Clubs " , " Diamonds " , " Spades " , " Clubs " };
2 cout << " Enter a suit number (1 -4) : " ;
3 unsigned int suitNum ;
4 cin >> suitNum ;
5 if ( suitNum <= 3)
6 cout << s ui t N am e s [ suitNum - 1];

1.3.2 Pointers to Array Elements


It is important to note that arrays in C++ are pointers to continuous regions in mem
Therefore the following code is valid:
1 const int A RR A Y _L E N = 100;
2 int arr [ A RR A Y _L E N ];
3 int * p = arr ;
4 int * q = & arr [0];

Now p and q point to exactly the same locationarr as(ie. arr[0]), andp, q and arr
can be used interchangeably. You can also make a pointer to some element in the middl
an array (similarly toq):
1 int * z = & arr [10];

1.4 Global Scope


We discussed in lecture how variables can be declaredglobal scopeat or file scope – if a variable is
declared outside of any function, it can be used anywhere in the file. For anything besides global
constants such as error codes or fixed array sizes, this is usually a bad idea; if you need to access
the same variable from multiple functions, most often you should simply

4
pass the variable around as an argument between the functions. Avoid global variables
when you can.

2 A Simple Function
What would the following program print out? (Answer without using a computer.)
1 void f ( const int a = 5)
2 {
3 std :: cout << a *2 << " \ n " ;
4 }
5
6 int a = 123;
7 int main ()
8 {
9 f (1) ;
10 f ( a ) ;
11 int b = 3;
12 f ( b ) ;
13 int a = 4;
14 f ( a ) ;
15 f () ;
16 }

3 Fix the Function


Identify the errors in the following programs, and explain how you would correct them
make them do what they were apparently meant to do.

3.1
1 # include < iostream >
2
3 int main () {
4 printNum (35) ;
5 return 0;
6 }
7
8 void printNum ( int number ) { std :: cout << number ; }

(Give two ways to fix this code.)

5
3.2
1 # include < iostream >
2
3 void printNum () { std :: cout << number ; };
4
5 int main () {
6 int number = 35;
7 printNum ( number ) ;
8 return 0;
9 }

(Give two ways to fix this code. Indicate which is preferable and why.)

3.3
1 # include < iostream >
2
3 void d o u b l e N u m b e r ( int num ) { num = num * 2;}
4
5 int main () {
6 int num = 35;
7 d o u b l e N u m b e r ( num ) ;
8 std :: cout << num ; // Should print 70
9 return 0;
10 }

(Changing the return type doubleNumberof is not a valid solution.)

3.4
1 # include < iostream >
2 # include < cstdlib > // contains some math f un c t io n
s
3
4 int d i f f e r e n c e ( const int x , const int y ) {
5 int diff = abs ( x - y ) ; // abs ( n ) returns absolute
value of n
6 }
7
8 int main () {
9 std :: cout << d i f f e r e n c e (24 , 1238) ;
10 return 0;
11 }

6
3.5
1 # include < iostream >
2
3 int sum ( const int x , const int y ) {
4 return x + y ;
5 }
6
7 int main () {
8 std :: cout << sum (1 , 2 , 3) ; // Should print 6
9 return 0;
10 }

3.6
1 # include < iostream >
2 const int A RR A Y _L E N = 10;
3
4 int main () {
5 int arr [ A R RA Y _ LE N ] = {10};
// Note implicit i n i t i a l i z a t i o n of
6 // other elements
7 int * xPtr = arr , yPtr = arr + A RR A Y _L E N - 1;
8 std :: cout << * xPtr << ’ ’ << * yPtr ; // Should output 10 0
9 return 0;
10 }

4 Sums
Make sure to useconst arguments where appropriate throughout this problem (and all the
others).

4.1
Write a singlesum function that returns the sum of two integers. Also write the equivalent function for
taking the sum ofdoubletwo s.

4.2
Explain why, given your functions from part 1,sum(1, 10.0) is a syntax error(Hint:. Think
about promotion and demotion – the conversion of arguments between types in a functio
call. Remember that the compiler converts between numerical types for you if necessary.) [1
point]

7
4.3
Write 2 more functions such that you can find the sum of anywhere between 2 and 4 integers
by writingsum(num1, num2, ...).

4.4
Now write just one function that, using default arguments, allows you to take the sum of
anywhere between 2 and 4 integers. What would happen if you put both this definition and
your 3-argument function from part 3 into the same file, sum(3,andcalled5,7)? Why?

4.5
Write a singlesum function capable of handling an arbitrary number of integers. It should
take two arguments, include a loop, and return an(Hint:integerWhat. data types can you
use to represent an arbitrarily large set of integers in two arguments?)

4.6
Now rewrite your function from 4.5 to use recursion instead of a loop. The function signature
should not change. Thinking about pointer arithmetic may help you.

5 Calculating π
This problem is a bit tricky, but it’s a good exercise in writing a program that actually does
something neat. It will also familiarize you with using random numbers.
Using a “Monte Carlo” method – that is, a randomized simulation – we can comput
good approximation ofπ. Consider a circle of radius 1, centered on the origin and circum
scribed by a square, like so:

}1
Imagine that this is a dartboard and that you are tossing darts at it randomly. W
enough darts, the ratio of darts in the circle to total darts thrown should be the ratio between
4
the area of the circle (call) itand the area of the square (4): TOTAL DARTS = . We can use
DARTS IN CIRCLE A

this ratio to calculate, from which we can thenπ =find .

We can simplify the math by only considering the first quadrant, calculating the ratio of
the top right square’s area to the area of the single quadrant. Thus, we wA4i,ll actually fi
A
4

and then computeπ = 4 × 2 .


R

We’ll build a function step by step to do all this.

8
5.1
Define variables to store xtheand y coordinates of a particular dart throw. Initialize them
to randomdoubles in the range [0, 1] (simulating one dart throw)(Hint:. remember that
value in the range [0, RAND MAX]; we just want to convert that value to
RAND() returns a
some value in [0, 1].)

5.2
Place your x and y declarations in a loop to simulate multiple dart throws. Assume you have
a variablen indicating how many throws to simulate. Maintain a count (declared outside
the loop) of how many darts have ended up inside the circle. (You can check whether a
2 2 2
is within a given radius with the Euclidean distance formula,d= x + y ; you may find the
sqrt function from the<cmath> header useful.)

5.3
Now use your loop to build π-calculating function. The function should take one argument
specifying the number of dart throws to runfrom( part 2). It should return the decimal
value of pi, using the technique outlined above. Be sure to name your function appropriately.
Don’t forget to initialize the random number generator with a seed. You should get pre
good results for around 5,000,000 dart throws.

6 Array Operations
6.1
Write a functionprintArray to print the contents of an integer array with ",the " string
between elements (but not after the last element). Your function should return nothing.

6.2
Write areverse function that takes an integer array and its length as arguments. Your function
should reverse the contents of the array, leaving the reversed values in the origi array, and return
nothing.

6.3
Assume the existence of two constantsWIDTH and LENGTH. Write a function with the
following signature:
void t ra n s po s e ( const int input [][ LENGTH ] , int output
[][ WIDTH ]) ;

9
Your function should transpose WIDTHthe × LENGTH matrix ininput, placing theLENGTH ×
WIDTH transposed matrix intooutput. (See http://en.wikipedia.org/wiki/Transpose#Examples
for examples of what it means to transpose a matrix.)

6.4
What would happen if, instead of havingoutput be an “out argument,” we simply declared a
new array withintranspose and returned that array?

6.5
Rewrite your function from part 2 to use pointer-offset notation instead of array-subscript notation.

7 Pointers and Strings


7.1
Write a function that returns the length of charstring*), excluding( the final NULL character. It should
not use any standard-library functions. You may use arithmetic and dereference operators, but not
the indexing operator[])(.

7.2
Write a function that swaps two integer values using call-by-reference.

7.3
Rewrite your function from part 2 to use pointers instead of references.

7.4
Write a function similar to the one in part 3, but instead of swapping two values, it
two pointers to point to each other’s values. Your function should work correctly for t
following example invocation:
1 int x = 5 , y = 6;
2 int * ptr1 = &x , * ptr2 = & y ;
3 swap (& ptr1 , & ptr2 ) ;
4 cout << * ptr1 << ’ ’ << * ptr2 ; // Prints "6 5"

10
7.5
Assume that the following variable declaration has already been made:
1 char * od d O rE v e n = " Never odd or even " ;

Write a single statement to accomplish each of the following tasks (assuming for each one
that the previous ones have already been run). Make sure you understand what happens
each of them.

1. Create a pointer tochar value namednthCharPtr pointing to the 6th character of


oddOrEven (remember that the first item has index 0). Use the indexing operator.

2. Using pointer arithmetic, update nthCharPtr to point to the 4th character inoddOrEven.

3. Print the value currently pointed tonthCharPtrby.

4. Create a new pointer to a pointerchar (a** ) namedpointerPtr that points to nthCharPtr.

5. Print the value storedpointerPtr.


6. Using pointerPtr, print the value pointed tonthCharPtrby.

7. Update nthCharPtr to point to the next characteroddOrEvenin (i.e. one character


past the location it currently points to).

8. Using pointer arithmetic, print out how far away from the character currently pointed
to bynthCharPtr is from the start of the string.

11
MIT OpenCourseWare
http://ocw.mit.edu

6.096 Introduction to C++


January (IAP) 2011

For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

You might also like