






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







1 Additional Material 1.1 Functions
1 void printNTimes ( char * msg , int n ) { 2 for ( int i = 0; i < n ; ++ i ) { 3 cout << msg ; 4 } 5 }
1 void printNTimes ( char * msg , int n = 1) { 2 for ( int i = 0; i < n ; ++ i ) { 3 cout << msg ; 4 } 5 }
1 void printNTimes ( char * msg = " \ n " , int n = 1) { 2 for ( int i = 0; i < n ; ++ i ) { 3 cout << msg ;
1 void print ( const int n ) { 2 cout << n ; 3 }
1 void print ( const long & x ) { // Pass - by - reference avoids overhead 2 // of copying large number 3 cout << x ; 4 } 5 6 int main () { 7 long x = 234923592; 8 print ( x ) ; // We are guaranteed that x 9 // will not be changed by this 10 return 0; 11 }
1 # include < iostream > 2 # include < cstdlib > // C standard library 3 // defines rand () , srand () , RAND_MAX
6 int main () { 7 int * randNumPtr = getRandNumPtr () ; 8 cout << * randNumPtr ; // ERROR 9 return 0; 10 }
1.3 Arrays and Pointers
1 const char * suitNames [] = { " 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 << suitNames [ suitNum - 1];
const int ARRAY_LEN = 100; int arr [ ARRAY_LEN ]; int * p = arr ; int * q = & arr [0];
1 int * z = & arr [10]; 1.4 Global Scope
2 A Simple Function
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
1 # include < iostream > 2 3 int main () { 4 printNum (35) ; 5 return 0; 6 } 7 8 void printNum ( int number ) { std :: cout << number ; }
1 # include < iostream >
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 }
1 # include < iostream > 2 const int ARRAY_LEN = 10; 3 4 int main () { 5 int arr [ ARRAY_LEN ] = {10}; // Note implicit initialization of 6 // other elements 7 int * xPtr = arr , yPtr = arr + ARRAY_LEN - 1; 8 std :: cout << * xPtr << ’ ’ << * yPtr ; // Should output 10 0 9 return 0; 10 } 4 Sums
a
7 Pointers and Strings
1 int x = 5 , y = 6; 2 int * ptr1 = &x , * ptr2 = & y ; 3 swap (& ptr1 , & ptr2 ) ; 4 cout << * ptr1 << ’ ’ << * ptr2 ; // Prints "6 5"
1 char * oddOrEven = " Never odd or even " ;