



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions and explanations for various coding errors in a c programming lab, including issues with function definitions, sum functions, and array operations. It covers topics such as function prototypes, pass-by-reference parameters, and pointer manipulation.
Typology: Exercises
1 / 7
This page cannot be seen from the preview
Don't miss anything!




4 Sums
4.1 [4 points] 1 int sum ( const int x , const int y ) { 2 return x + y ; 3 } 4 5 double sum ( const double x , const double y ) { 6 return x + y ; 7 } 4.2 [1 point]
4.3 [2+2 points] 1 int sum ( const int x , const int y , const int z ) { 2 return x + y + z ; 3 } 4 5 int sum ( const int a , const int b , const int c , const int d ) { 6 return a + b + c + d ; 7 } 4.4 [5 + 1 points] 1 int sum ( const int a , const int b , const int c = 0 , const int d = 0) { 2 return a + b + c + d ; 3 }
5 for ( int i = 0; i < n ; ++ i ) { 6 double 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 } 6 Array Operations 6.1 [4 points] 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 [4 points] 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 [ indexFromEnd ]; 6 numbers [ indexFromEnd ] = tmp ; 7 } 8 } 6.3 [6 points] 1 void transpose ( const int input [][ LENGTH ] , int output [][ WIDTH ]) { 2 for ( int i = 0; i < WIDTH ; ++ i ) { 3 for ( int j = 0; j < LENGTH ; ++ j ) {
4 output [ j ][ i ] = input [ i ][ j ]; 5 } 6 } 7 } 6.4 [2 points]
6.5 [3 points] 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 + indexFromEnd ) ; 6 ( numbers + indexFromEnd ) = tmp ; 7 } 8 } 7 Pointers and Strings 7.1 [5 points] 1 int stringLength ( const char * str ) { 2 int length = 0; 3 while (( str + length ) != ’ \0 ’) { 4 ++ length ; 5 } 6 return length ; 7 } 7.2 [3 points] 1 void swap ( int &x , int & y ) { 2 int tmp = x ; 3 x = y ; 4 y = tmp ; 5 }