Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
For any help regarding CPP Homework Help
Visit :- https://www.cpphomeworkhelp.com/ ,
Email :- info@cpphomeworkhelp.com or
Call us at :- +1 678 648 4277
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. Functions
1. Default Arguments
Say you have a function with 1 argument, but that argument is usually the same. For
instance, say we want a function that prints a message n times, but most of the time it will
only need to print it once:
1 voi d pr i nt NTi mes ( char * msg , i nt n) {
f or ( i nt i = 0; i < n;
++i ) { cout << msg;
}
2
3
4
5 }
Rather than writing printNTimes("Some message", 1); every time, C + + allows de
fault arguments to be defined for a function:
1 void printNTimes ( char * msg , int n = 1) {
f or ( i nt i = 0; i < n;
++i ) { cout << msg ;
}
2
3
4
5 }
Solution
cpphomeworkhelp.com
Declaring the function argument as int n = 1 allows us to call the function with
printNTimes("Some message");. The compiler automatically inserts 1 as the second
argument. You may have multiple default arguments for a function:
1 void printNTimes ( char * msg = "  n", int n = 1) {
2 for ( int i = 0; i < n ; ++ i ) {
3 cout << msg ;
4
5
}
}
Now, to print one newline, we can simply write printNTimes();. However, C + + does not
allow skipping arguments, so we could not print k newlines by writing printNTimes(k);.
To do that, we’d need to say printNTimes("n", k);.
1.1.2Constant Arguments
It’s often useful to specify that arguments to a function should be treated as constants.
As with regular variables, we can declare function arguments to be const:
1void print( const int n) {
2 cout << n;
3 }
This is particularly useful when we are passing values by reference to a function, but
don’t want to allow the function to make any changes to the original value:
1 void print( const long & x) { // Pass - by - reference avoids overhead
cpphomeworkhelp.com
// of copying large number
cout << x;
2
3
4 }
5
6 i nt mai n ( ) {
7 l ong x = 234923592 ;
8 pr i nt ( x) ; // W
e are guarant eed t hat 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 it const. That way, the compiler can catch you if you messed up and tried to
change it somewhere.
1.1.3Random Number Generation Functions
The C + + standard libraries include the rand() function for generating random numbers
between 0 and RAND MAX (an integer constant defined by the compiler). These numbers are
not truly random; they are a random-seeming but deterministic sequence based on a particular
“seed” number. To make sure we don’t keep getting the same random-number sequence, we
generally use the current time as the seed number. Here is an example of how this is done:
1# i ncl ude
2# i ncl ude
3
<iostream >
<cstdlib > // C standard library
// def i nes rand ( ) , srand ( ) , RAND_MAX
cpphomeworkhelp.com
4 # i ncl ude <ct i me >// C t i me f unct i ons - def i nes t i me ( )
5 int
6
main ()
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: " << rand Num << endl;
10 return 0;
11 }
2. Pointers
1. Pointers to Pointers
We can have pointers to any type, including pointers to pointers. This is commonly used in
C (and less commonly in C++) to allow functions to set the values of pointers in their calling
functions. For example:
1 voi d set St r i ng ( char ** st r Pt r ) {
int x; cin
>> x; i f ( x <
0)
*st r Pt r = " Negat i ve ! ";
else
*st r Pt r = " Nonnegat i ve
! ";
2
3
4
5
6
7
8 }
9
1 0 i nt mai n ( ) {
11 char * st r ;
cpphomeworkhelp.com
10 set St r i ng ( &st r ) ;
11 cout << s t r ; // String has been
set by setString
12 return 0;
15 }
1.2.2Returning Pointers
When you declare a local variable within a function, that variable goes out of scope when the
function exits: the memory allocated to it is reclaimed by the operating system, and anything that
was stored in that memory may be cleared. It therefore usually generates a runtime error to return
a pointer to a local variable:
1 int * getRandNumPtr
()
{
2 int x = rand () ;
3 return & x;
4 }
5
6 i nt mai n ( ) {
7 i nt * randNumPt r = get RandNumPt r ( ) ;
8 cout << * randNumPt r ; // ERROR
9 return 0;
10 }
Line 8 will likely crash the program or print a strange value, since it is trying to
access memory that is no longer in use – x from getRandNumPtr has been
deallocated.
cpphomeworkhelp.com
1.3.2Pointers to Array Elements
It is important to note that arrays in C + + are pointers to continuous regions in
memory. Therefore the following code is valid:
1
2
3
4
const int ARRAY_LEN = 100; int arr [
ARRAY_LEN ];
int * p = arr ;
int * q = & arr [0];
Now p and q point to exactly the same location as arr (ie. arr[0]), and p, q and arr can be
used interchangeably. You can also make a pointer to some element in the middle of an array
(similarly to q):
1 i nt * z = &ar r [ 10] ;
1.4 Global Scope
3. Arrays and Pointers
1. Arrays of Pointers
Arrays can contain any type of value, including pointers. One common application of
this is arrays of strings, i.e., arrays of char *’s. For instance:
1const char * suitNames [ ] = {" Clubs " , " Diamonds " , " Spades " , " Clubs
" } ;
2cout << " Ent er a sui t number ( 1 - 4) : ";
3unsi gned i nt sui t Num;
4ci n >> sui t Num;
5 i f ( sui t Num <= 3)
6 cout << sui t Names [ sui t Num - 1] ;
cpphomeworkhelp.com
We discussed in lecture how variables can be declared at global scope 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
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 voi d f ( const i nt a = 5)
2 {
3
4 }
5
6 int a = 123;
7 i nt mai n ( )
8 {
9 f (1) ;
10 f (a ) ;
11 int b = 3;
12 f (b ) ;
13 int a = 4;
14 f (a ) ;
15 f();
std : : cout << a *2 << " n";
16 }
cpphomeworkhelp.com
3 F i x the Function
Identify the errors in the following programs, and explain how you would correct them to make
them do what they were apparently meant to do.
3.1
1 # i ncl ude <i ost ream>
2
3 i nt mai n ( ) {
4 pr i nt Num( 35) ;
5 return 0;
6 }
7
8 void printNum ( int number) { std : : cout << number; }
(Give two ways to fix this code.)
3.2
1 # i ncl ude <i ost ream>
2
3 void printNum ( ) { std : : cout << number; } ;
4
5 i nt mai n ( ) {
6 int number = 35;
7 pr i nt Num( number ) ;
8 return 0;
cpphomeworkhelp.com
9 }
(Give two ways to fix this code. Indicate which is preferable and why.)
3.3
1 # i ncl ude <i ost r eam>
2
3 voi d doubl e Number ( i nt num) { num = num * 2; }
4
5 i nt mai n ( ) {
6 int num = 35;
7 doubl e Number ( num) ;
8 st d : : cout << num; // Shoul d pr i nt 70
9 return 0;
10 }
(Changing the return type of doubleNumber is not a valid solution.)
3.4
1# i ncl ude <i ost r eam>
2# include <cstdlib > // contains some math functions
3
cpphomeworkhelp.com
mai n ( ) {
std : : cout << di f f erence ( 24 ,
1238) ; return 0;
4 i nt di f f erence ( const i nt x, const i nt y) {
5 int diff = abs( x - y ); // abs( n) returns absolute value
of n
6 }
7
8 int
9
10
11 }
3.5
1 # i ncl ude <i ost ream>
2
3 i nt sum( const i nt x , const i nt
y) {
4 return x + y;
5 }
6
7 int
8
9
10 }
// Should print
6
mai n ( ) {
std : : cout << sum( 1 , 2 ,
3) ;
return 0;
3.6
1# i ncl ude <i ost ream>
2const int ARRAY_LEN = 10;
3 cpphomeworkhelp.com
i nt * xPt r = arr , yPt r = ar r
+
// Note implicit in it ia lizat io n of
// other elements
ARRAY_LEN - 1;
std : : cout << * xPtr << ’ ’ << * yPtr; // Should output 10 0
return 0;
4 i nt mai n ( ) {
5 i nt ar r [ ARRAY_LEN] = { 10} ;
6
7
8
9
10 }
4 Sums
Make sure to use const arguments where appropriate throughout this problem (and all
the others).
4.1
Write a single sum function that returns the sum of two integers. Also write the
equivalent function for taking the sum of two doubles.
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 function
call. Remember that the compiler converts between numerical types for you if necessary.) [1
point]
4.3 Write 2 more functions such that you can find the sum of anywhere between 2
and 4 integers by writing sum(num1, num2, ...).
cpphomeworkhelp.com
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, and called sum(3, 5, 7)? Why?
4.5
Write a single sum function capable of handling an arbitrary number of integers. It should take
two arguments, include a loop, and return an integer. (Hint: What 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 compute a good
approximation of π. Consider a circle of radius 1, centered on the origin and circum scribed by a
square, like so:
cpphomeworkhelp.com
Imagine that this is a dartboard and that you are tossing darts at it randomly. With enough
darts, the ratio of darts in the circle to total darts thrown should be the ratio between total
darts 4 the area of the circle (call it a) and the area of the square (4): = . We can use darts
in circle a this ratio to calculate a, from which we can then find π = a 2 . r 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 will actually find a 4 , a and then
compute π = 4 × r 4 2 . We’ll build a function step by step to do all this.
5.1
Define variables to store the x and y coordinates of a particular dart throw. Initialize
them to random doubles in the range [0, 1] (simulating one dart throw). (Hint:
remember that rand() returns a value in the range [0, RAND MAX]; we just want to
convert that value to 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 variable n 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 dart is within a given radius with the Euclidean distance formula,
d2 = x2 + y2; you may find the sqrt function from the <cmath> header useful.)
cpphomeworkhelp.com
5.3
Now use your loop to build a π-calculating function. The function should take one
argument specifying the number of dart throws to run (n from 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 pretty good results for around 5,000,000 dart throws.
6 Array Operations
6.1
Write a function printArray 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 a reverse 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
original array, and return nothing.
6.3
Assume the existence of two constants WIDTH and LENGTH. Write a function with the
following signature:
void transpose ( const int input [ ] [ LENGTH ] , int output [ ] [ WIDTH ] ) ;
cpphomeworkhelp.com
Your function should transpose the WIDTH × LENGTH matrix in input, placing the LENGTH
× WIDTH transposed matrix into output. (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 having output be an “out argument,” we simply
declared a new array within transpose 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 a string (char *), 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.
cpphomeworkhelp.com
7.5
Assume that the following variable declaration has already been made:
1 char * odd Or Even = " 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 in each of them.
1. Create a pointer to a char value named nthCharPtr 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 in
oddOrEven.
3.Print the value currently pointed to by nthCharPtr.
4.Create a new pointer to a pointer (a char **) named pointerPtr that points to
nthCharPtr.
5.Print the value stored in pointerPtr.
1 int x = 5, y = 6;
2 int * ptr1 = &x , * ptr2 = &y;
3 swap (& ptr1 , & ptr2 );
4 cout << * ptr1 <
<
’ ’ << * ptr2 ; // Prints "6 5"
7.4
Write a function similar to the one in part 3, but instead of swapping two values, it
swaps two pointers to point to each other’s values. Your function should work
correctly for the following example invocation:
cpphomeworkhelp.com
5.Using pointerPtr, print the value pointed to by nthCharPtr.
6.Update nthCharPtr to point to the next character in oddOrEven (i.e. one
character past the location it currently points to).
7.Using pointer arithmetic, print out how far away from the character currently
pointed to by nthCharPtr is from the start of the string.
cpphomeworkhelp.com
2 A Simple Function
The program prints: 2 246 6 8 10
3 Fix the Function [1 point/fix, so 2 points for first 2]
3.1
Either declare a function prototype for printNum before main, or move the definition of
printNum to before main.
3.2
Either add an int argument called number to printNum (preferable because it avoids use
of global variables), or move the int number declaration to a global variable.
3.3
Make num a pass-by-reference parameter (i.e. add a &before its name).
3.4
Add a return statement to difference returning diff (or just scrap diff altogether and
make the function return abs(x-y);).
3.5
Add a third argument to sum.
Solution
cpphomeworkhelp.com
4.4
4 Sums
In this problem and all others, half a point should be deducted for not using a const
argument where it would have been appropriate.
1.
1 i nt sum( const i nt x, const i nt y) {
2 return x + y;
3 }
4
5doubl e sum( const doubl e x, const doubl e y) {
6 return x + y;
7 }
2.
Mixing and matching an int with a double makes it ambiguous which one you want to
call. The compiler could either cast 1 to a double and call the double version of sum,
or it could cast 10.0 to an int and call the int version.
3.6
Add a * to make line 7 say int *xPtr = arr, *yPtr = ....
1 int sum( const int a, const int b, const int c = 0 , const int d = 0) { 2 return a + b + c + d ; 3 }
If the given definitions were included together, the compiler would give a compile error, since
it cannot disambiguate between a call to the 3-argument function and a call to the 4-
argument one with a default parameter.
cpphomeworkhelp.com
i nt numbersLen
) {
++i) {
+= numbers [
i ] ;
int sum
= f or (
i nt i
sum
}
ret ur n
sum;
1 i nt sum( const i nt numbers [ ] ,
const
2 0;
3 = 0; i < numbersLen ;
4
5
6
7 }
4.6
1int sum ( const int numbers [ ] , const int numbersLen ) {
2 r et ur n number sLen == 0 ? 0 : number s [ 0] + sum( number s
+ 1 , numbersLen - 1);
3 }
5 Calculating π
1.
1 double x = rand ( ) / ( double ) RAND_MAX , y = rand ( ) / ( double )
RAND_MAX ;
5.2
cpphomeworkhelp.com
1
2
3
4
double compute Pi ( const
int srand ( time (0) );
int dartsInCircle = 0;
n) {
3 double x = rand ( ) / ( double ) RAND_MAX , y = rand ( ) /
( double ) RAND_MAX ;
i f ( sqr t ( x* x + y* y) < 1 ) {
++ dar t sI n Ci r cl e ;
}
4
5
6
7
}
5.3
1 i nt dar t sI n Ci r cl e = 0;
2 f or ( i nt i = 0; i < n; ++i ) {
5 for ( int i = 0; i < n; ++i) {
6 doubl
e
x = rand () / ( double )
RAND_MAX ,
y = rand () / ( double )
RAND_MAX ;
7 if ( sqrt(x* x + y*
y)
< 1 ) {
8 ++ dartsInCircle ;
9 }
10 }
11
12 // r ^2 is 1 , and a /4 = dartsInCircle /n , yielding this for pi :
13 return dartsInCircle / static_cast < double >( n) * 4;
14 }
cpphomeworkhelp.com
6 Array Operations
1.
1 void printArray ( const int arr[] , const int len ) {
2 for ( int i = 0; i < len ; ++i) {
3 cout << arr[i];
4 if( i < len -1) {
5 cout << " , ";
6 }
7 }
8 }
6.2
1 void reverse ( int numbers [], const int numbersLen ) {
2 for ( int i = 0; i < numbersLen / 2; ++i) {
3 int tmp = numbers[ i];
4 int indexFromEnd = numbersLen - i - 1;
5 numbers[ i ] = numbers[ indexFrom End ] ;
6 numbers[ indexFromEnd ] = tmp ;
7 }
8 }
6.3
1 void transpose ( const int input [ ] [ LENGTH ] , int output [ ] [ WIDTH ] ) {
2
3
f or ( i nt i = 0; i < WI DTH; ++i )
{ f or ( i nt j = 0; j < LENGTH
; ++j ) {
cpphomeworkhelp.com
4 output[ j][ i] = input[i][ j];
5 }
6 }
7 }
2 for ( int i = 0; i < numbersLen / 2; ++i) {
3 int tmp = *( numbers + i);
4 int indexFromEnd = numbersLen - i - 1;
5 *( numbers + i ) = *( numbers + indexFrom End ) ;
6 *( numbers + indexFromEnd ) = tmp ;
7 }
8 }
4.
A pointer to the first element in the array would be returned, but the array
would have gone out of scope, making the pointer invalid.
5.
1 void reverse ( int numbers [ ] , const int numbersLen ) {
7 Pointers and Strings
1.
1 i nt st r i ng Lengt h ( const char *
st r ) {
2 int length = 0;
cpphomeworkhelp.com
2 int tmp = x;
3 x = y;
4 y = tmp ;
5 }
1 whi l e ( *( st r + l engt h ) != ’ 0 ’ )
{
4 ++ l engt h ;
5 }
6 r et ur n l engt h ;
7 }
7.2
1 voi d swap ( i nt &x , i nt &y) {
7.3
1 voi d swap ( i nt *x, i nt *
y) { i nt t mp = *
x;
* x = * y;
* y = t mp ;
2
3
4
5 }
7.4 ]
1 voi d swap ( i nt ** x, i nt
** y) {
cpphomeworkhelp.com
5.
char *nthCharPtr = &oddOrEven[5];
1.nthCharPtr -= 2; or nthCharPtr = oddOrEven + 3;
2.cout << *nthCharPtr;
3.char **pointerPtr = &nthCharPtr;
4.cout << pointerPtr;
5.cout << **pointerPtr;
6.nthCharPtr++; to point to the next character in oddOrEven (i.e. one
character past the location it currently points to)
7.cout << nthCharPtr - oddOrEven;
2
3
4
5 }
i nt * t mp =
* x;
* x = * y;
* y = t mp ;
cpphomeworkhelp.com

More Related Content

CPP Homework Help

  • 1. For any help regarding CPP Homework Help Visit :- https://www.cpphomeworkhelp.com/ , Email :- info@cpphomeworkhelp.com or Call us at :- +1 678 648 4277
  • 2. 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. Functions 1. Default Arguments Say you have a function with 1 argument, but that argument is usually the same. For instance, say we want a function that prints a message n times, but most of the time it will only need to print it once: 1 voi d pr i nt NTi mes ( char * msg , i nt n) { f or ( i nt i = 0; i < n; ++i ) { cout << msg; } 2 3 4 5 } Rather than writing printNTimes("Some message", 1); every time, C + + allows de fault arguments to be defined for a function: 1 void printNTimes ( char * msg , int n = 1) { f or ( i nt i = 0; i < n; ++i ) { cout << msg ; } 2 3 4 5 } Solution cpphomeworkhelp.com
  • 3. Declaring the function argument as int n = 1 allows us to call the function with printNTimes("Some message");. The compiler automatically inserts 1 as the second argument. You may have multiple default arguments for a function: 1 void printNTimes ( char * msg = " n", int n = 1) { 2 for ( int i = 0; i < n ; ++ i ) { 3 cout << msg ; 4 5 } } Now, to print one newline, we can simply write printNTimes();. However, C + + does not allow skipping arguments, so we could not print k newlines by writing printNTimes(k);. To do that, we’d need to say printNTimes("n", k);. 1.1.2Constant Arguments It’s often useful to specify that arguments to a function should be treated as constants. As with regular variables, we can declare function arguments to be const: 1void print( const int n) { 2 cout << n; 3 } This is particularly useful when we are passing values by reference to a function, but don’t want to allow the function to make any changes to the original value: 1 void print( const long & x) { // Pass - by - reference avoids overhead cpphomeworkhelp.com
  • 4. // of copying large number cout << x; 2 3 4 } 5 6 i nt mai n ( ) { 7 l ong x = 234923592 ; 8 pr i nt ( x) ; // W e are guarant eed t hat 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 it const. That way, the compiler can catch you if you messed up and tried to change it somewhere. 1.1.3Random Number Generation Functions The C + + standard libraries include the rand() function for generating random numbers between 0 and RAND MAX (an integer constant defined by the compiler). These numbers are not truly random; they are a random-seeming but deterministic sequence based on a particular “seed” number. To make sure we don’t keep getting the same random-number sequence, we generally use the current time as the seed number. Here is an example of how this is done: 1# i ncl ude 2# i ncl ude 3 <iostream > <cstdlib > // C standard library // def i nes rand ( ) , srand ( ) , RAND_MAX cpphomeworkhelp.com
  • 5. 4 # i ncl ude <ct i me >// C t i me f unct i ons - def i nes t i me ( ) 5 int 6 main () 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: " << rand Num << endl; 10 return 0; 11 } 2. Pointers 1. Pointers to Pointers We can have pointers to any type, including pointers to pointers. This is commonly used in C (and less commonly in C++) to allow functions to set the values of pointers in their calling functions. For example: 1 voi d set St r i ng ( char ** st r Pt r ) { int x; cin >> x; i f ( x < 0) *st r Pt r = " Negat i ve ! "; else *st r Pt r = " Nonnegat i ve ! "; 2 3 4 5 6 7 8 } 9 1 0 i nt mai n ( ) { 11 char * st r ; cpphomeworkhelp.com
  • 6. 10 set St r i ng ( &st r ) ; 11 cout << s t r ; // String has been set by setString 12 return 0; 15 } 1.2.2Returning Pointers When you declare a local variable within a function, that variable goes out of scope when the function exits: the memory allocated to it is reclaimed by the operating system, and anything that was stored in that memory may be cleared. It therefore usually generates a runtime error to return a pointer to a local variable: 1 int * getRandNumPtr () { 2 int x = rand () ; 3 return & x; 4 } 5 6 i nt mai n ( ) { 7 i nt * randNumPt r = get RandNumPt r ( ) ; 8 cout << * randNumPt r ; // ERROR 9 return 0; 10 } Line 8 will likely crash the program or print a strange value, since it is trying to access memory that is no longer in use – x from getRandNumPtr has been deallocated. cpphomeworkhelp.com
  • 7. 1.3.2Pointers to Array Elements It is important to note that arrays in C + + are pointers to continuous regions in memory. Therefore the following code is valid: 1 2 3 4 const int ARRAY_LEN = 100; int arr [ ARRAY_LEN ]; int * p = arr ; int * q = & arr [0]; Now p and q point to exactly the same location as arr (ie. arr[0]), and p, q and arr can be used interchangeably. You can also make a pointer to some element in the middle of an array (similarly to q): 1 i nt * z = &ar r [ 10] ; 1.4 Global Scope 3. Arrays and Pointers 1. Arrays of Pointers Arrays can contain any type of value, including pointers. One common application of this is arrays of strings, i.e., arrays of char *’s. For instance: 1const char * suitNames [ ] = {" Clubs " , " Diamonds " , " Spades " , " Clubs " } ; 2cout << " Ent er a sui t number ( 1 - 4) : "; 3unsi gned i nt sui t Num; 4ci n >> sui t Num; 5 i f ( sui t Num <= 3) 6 cout << sui t Names [ sui t Num - 1] ; cpphomeworkhelp.com
  • 8. We discussed in lecture how variables can be declared at global scope 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 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 voi d f ( const i nt a = 5) 2 { 3 4 } 5 6 int a = 123; 7 i nt mai n ( ) 8 { 9 f (1) ; 10 f (a ) ; 11 int b = 3; 12 f (b ) ; 13 int a = 4; 14 f (a ) ; 15 f(); std : : cout << a *2 << " n"; 16 } cpphomeworkhelp.com
  • 9. 3 F i x the Function Identify the errors in the following programs, and explain how you would correct them to make them do what they were apparently meant to do. 3.1 1 # i ncl ude <i ost ream> 2 3 i nt mai n ( ) { 4 pr i nt Num( 35) ; 5 return 0; 6 } 7 8 void printNum ( int number) { std : : cout << number; } (Give two ways to fix this code.) 3.2 1 # i ncl ude <i ost ream> 2 3 void printNum ( ) { std : : cout << number; } ; 4 5 i nt mai n ( ) { 6 int number = 35; 7 pr i nt Num( number ) ; 8 return 0; cpphomeworkhelp.com
  • 10. 9 } (Give two ways to fix this code. Indicate which is preferable and why.) 3.3 1 # i ncl ude <i ost r eam> 2 3 voi d doubl e Number ( i nt num) { num = num * 2; } 4 5 i nt mai n ( ) { 6 int num = 35; 7 doubl e Number ( num) ; 8 st d : : cout << num; // Shoul d pr i nt 70 9 return 0; 10 } (Changing the return type of doubleNumber is not a valid solution.) 3.4 1# i ncl ude <i ost r eam> 2# include <cstdlib > // contains some math functions 3 cpphomeworkhelp.com
  • 11. mai n ( ) { std : : cout << di f f erence ( 24 , 1238) ; return 0; 4 i nt di f f erence ( const i nt x, const i nt y) { 5 int diff = abs( x - y ); // abs( n) returns absolute value of n 6 } 7 8 int 9 10 11 } 3.5 1 # i ncl ude <i ost ream> 2 3 i nt sum( const i nt x , const i nt y) { 4 return x + y; 5 } 6 7 int 8 9 10 } // Should print 6 mai n ( ) { std : : cout << sum( 1 , 2 , 3) ; return 0; 3.6 1# i ncl ude <i ost ream> 2const int ARRAY_LEN = 10; 3 cpphomeworkhelp.com
  • 12. i nt * xPt r = arr , yPt r = ar r + // Note implicit in it ia lizat io n of // other elements ARRAY_LEN - 1; std : : cout << * xPtr << ’ ’ << * yPtr; // Should output 10 0 return 0; 4 i nt mai n ( ) { 5 i nt ar r [ ARRAY_LEN] = { 10} ; 6 7 8 9 10 } 4 Sums Make sure to use const arguments where appropriate throughout this problem (and all the others). 4.1 Write a single sum function that returns the sum of two integers. Also write the equivalent function for taking the sum of two doubles. 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 function call. Remember that the compiler converts between numerical types for you if necessary.) [1 point] 4.3 Write 2 more functions such that you can find the sum of anywhere between 2 and 4 integers by writing sum(num1, num2, ...). cpphomeworkhelp.com
  • 13. 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, and called sum(3, 5, 7)? Why? 4.5 Write a single sum function capable of handling an arbitrary number of integers. It should take two arguments, include a loop, and return an integer. (Hint: What 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 compute a good approximation of π. Consider a circle of radius 1, centered on the origin and circum scribed by a square, like so: cpphomeworkhelp.com
  • 14. Imagine that this is a dartboard and that you are tossing darts at it randomly. With enough darts, the ratio of darts in the circle to total darts thrown should be the ratio between total darts 4 the area of the circle (call it a) and the area of the square (4): = . We can use darts in circle a this ratio to calculate a, from which we can then find π = a 2 . r 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 will actually find a 4 , a and then compute π = 4 × r 4 2 . We’ll build a function step by step to do all this. 5.1 Define variables to store the x and y coordinates of a particular dart throw. Initialize them to random doubles in the range [0, 1] (simulating one dart throw). (Hint: remember that rand() returns a value in the range [0, RAND MAX]; we just want to convert that value to 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 variable n 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 dart is within a given radius with the Euclidean distance formula, d2 = x2 + y2; you may find the sqrt function from the <cmath> header useful.) cpphomeworkhelp.com
  • 15. 5.3 Now use your loop to build a π-calculating function. The function should take one argument specifying the number of dart throws to run (n from 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 pretty good results for around 5,000,000 dart throws. 6 Array Operations 6.1 Write a function printArray 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 a reverse 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 original array, and return nothing. 6.3 Assume the existence of two constants WIDTH and LENGTH. Write a function with the following signature: void transpose ( const int input [ ] [ LENGTH ] , int output [ ] [ WIDTH ] ) ; cpphomeworkhelp.com
  • 16. Your function should transpose the WIDTH × LENGTH matrix in input, placing the LENGTH × WIDTH transposed matrix into output. (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 having output be an “out argument,” we simply declared a new array within transpose 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 a string (char *), 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. cpphomeworkhelp.com
  • 17. 7.5 Assume that the following variable declaration has already been made: 1 char * odd Or Even = " 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 in each of them. 1. Create a pointer to a char value named nthCharPtr 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 in oddOrEven. 3.Print the value currently pointed to by nthCharPtr. 4.Create a new pointer to a pointer (a char **) named pointerPtr that points to nthCharPtr. 5.Print the value stored in pointerPtr. 1 int x = 5, y = 6; 2 int * ptr1 = &x , * ptr2 = &y; 3 swap (& ptr1 , & ptr2 ); 4 cout << * ptr1 < < ’ ’ << * ptr2 ; // Prints "6 5" 7.4 Write a function similar to the one in part 3, but instead of swapping two values, it swaps two pointers to point to each other’s values. Your function should work correctly for the following example invocation: cpphomeworkhelp.com
  • 18. 5.Using pointerPtr, print the value pointed to by nthCharPtr. 6.Update nthCharPtr to point to the next character in oddOrEven (i.e. one character past the location it currently points to). 7.Using pointer arithmetic, print out how far away from the character currently pointed to by nthCharPtr is from the start of the string. cpphomeworkhelp.com
  • 19. 2 A Simple Function The program prints: 2 246 6 8 10 3 Fix the Function [1 point/fix, so 2 points for first 2] 3.1 Either declare a function prototype for printNum before main, or move the definition of printNum to before main. 3.2 Either add an int argument called number to printNum (preferable because it avoids use of global variables), or move the int number declaration to a global variable. 3.3 Make num a pass-by-reference parameter (i.e. add a &before its name). 3.4 Add a return statement to difference returning diff (or just scrap diff altogether and make the function return abs(x-y);). 3.5 Add a third argument to sum. Solution cpphomeworkhelp.com
  • 20. 4.4 4 Sums In this problem and all others, half a point should be deducted for not using a const argument where it would have been appropriate. 1. 1 i nt sum( const i nt x, const i nt y) { 2 return x + y; 3 } 4 5doubl e sum( const doubl e x, const doubl e y) { 6 return x + y; 7 } 2. Mixing and matching an int with a double makes it ambiguous which one you want to call. The compiler could either cast 1 to a double and call the double version of sum, or it could cast 10.0 to an int and call the int version. 3.6 Add a * to make line 7 say int *xPtr = arr, *yPtr = .... 1 int sum( const int a, const int b, const int c = 0 , const int d = 0) { 2 return a + b + c + d ; 3 } If the given definitions were included together, the compiler would give a compile error, since it cannot disambiguate between a call to the 3-argument function and a call to the 4- argument one with a default parameter. cpphomeworkhelp.com
  • 21. i nt numbersLen ) { ++i) { += numbers [ i ] ; int sum = f or ( i nt i sum } ret ur n sum; 1 i nt sum( const i nt numbers [ ] , const 2 0; 3 = 0; i < numbersLen ; 4 5 6 7 } 4.6 1int sum ( const int numbers [ ] , const int numbersLen ) { 2 r et ur n number sLen == 0 ? 0 : number s [ 0] + sum( number s + 1 , numbersLen - 1); 3 } 5 Calculating π 1. 1 double x = rand ( ) / ( double ) RAND_MAX , y = rand ( ) / ( double ) RAND_MAX ; 5.2 cpphomeworkhelp.com
  • 22. 1 2 3 4 double compute Pi ( const int srand ( time (0) ); int dartsInCircle = 0; n) { 3 double x = rand ( ) / ( double ) RAND_MAX , y = rand ( ) / ( double ) RAND_MAX ; i f ( sqr t ( x* x + y* y) < 1 ) { ++ dar t sI n Ci r cl e ; } 4 5 6 7 } 5.3 1 i nt dar t sI n Ci r cl e = 0; 2 f or ( i nt i = 0; i < n; ++i ) { 5 for ( int i = 0; i < n; ++i) { 6 doubl e x = rand () / ( double ) RAND_MAX , y = rand () / ( double ) RAND_MAX ; 7 if ( sqrt(x* x + y* y) < 1 ) { 8 ++ dartsInCircle ; 9 } 10 } 11 12 // r ^2 is 1 , and a /4 = dartsInCircle /n , yielding this for pi : 13 return dartsInCircle / static_cast < double >( n) * 4; 14 } cpphomeworkhelp.com
  • 23. 6 Array Operations 1. 1 void printArray ( const int arr[] , const int len ) { 2 for ( int i = 0; i < len ; ++i) { 3 cout << arr[i]; 4 if( i < len -1) { 5 cout << " , "; 6 } 7 } 8 } 6.2 1 void reverse ( int numbers [], const int numbersLen ) { 2 for ( int i = 0; i < numbersLen / 2; ++i) { 3 int tmp = numbers[ i]; 4 int indexFromEnd = numbersLen - i - 1; 5 numbers[ i ] = numbers[ indexFrom End ] ; 6 numbers[ indexFromEnd ] = tmp ; 7 } 8 } 6.3 1 void transpose ( const int input [ ] [ LENGTH ] , int output [ ] [ WIDTH ] ) { 2 3 f or ( i nt i = 0; i < WI DTH; ++i ) { f or ( i nt j = 0; j < LENGTH ; ++j ) { cpphomeworkhelp.com
  • 24. 4 output[ j][ i] = input[i][ j]; 5 } 6 } 7 } 2 for ( int i = 0; i < numbersLen / 2; ++i) { 3 int tmp = *( numbers + i); 4 int indexFromEnd = numbersLen - i - 1; 5 *( numbers + i ) = *( numbers + indexFrom End ) ; 6 *( numbers + indexFromEnd ) = tmp ; 7 } 8 } 4. A pointer to the first element in the array would be returned, but the array would have gone out of scope, making the pointer invalid. 5. 1 void reverse ( int numbers [ ] , const int numbersLen ) { 7 Pointers and Strings 1. 1 i nt st r i ng Lengt h ( const char * st r ) { 2 int length = 0; cpphomeworkhelp.com
  • 25. 2 int tmp = x; 3 x = y; 4 y = tmp ; 5 } 1 whi l e ( *( st r + l engt h ) != ’ 0 ’ ) { 4 ++ l engt h ; 5 } 6 r et ur n l engt h ; 7 } 7.2 1 voi d swap ( i nt &x , i nt &y) { 7.3 1 voi d swap ( i nt *x, i nt * y) { i nt t mp = * x; * x = * y; * y = t mp ; 2 3 4 5 } 7.4 ] 1 voi d swap ( i nt ** x, i nt ** y) { cpphomeworkhelp.com
  • 26. 5. char *nthCharPtr = &oddOrEven[5]; 1.nthCharPtr -= 2; or nthCharPtr = oddOrEven + 3; 2.cout << *nthCharPtr; 3.char **pointerPtr = &nthCharPtr; 4.cout << pointerPtr; 5.cout << **pointerPtr; 6.nthCharPtr++; to point to the next character in oddOrEven (i.e. one character past the location it currently points to) 7.cout << nthCharPtr - oddOrEven; 2 3 4 5 } i nt * t mp = * x; * x = * y; * y = t mp ; cpphomeworkhelp.com