Solutions for H5. Lecture: Xu-Ying Liu

Size: px
Start display at page:

Download "Solutions for H5. Lecture: Xu-Ying Liu"

Transcription

1 Lecture: Xu-Ying Liu Ex // Exercise Solution: DoubleSubscriptedArray.h 2 // DoubleSubscriptedArray class for storing 3 // double subscripted arrays of integers. 4 #ifndef DOUBLE_SUBSCRIPTED_ARRAY_H 5 #define DOUBLE_SUBSCRIPTED_ARRAY_H 6 7 #include <iostream> 8 using namespace std; 9 10 class DoubleSubscriptedArray 11 { 12 friend ostream &operator<<( 13 ostream &, const DoubleSubscriptedArray & ); 14 friend istream &operator>>( istream &, DoubleSubscriptedArray & ); 15 public: 16 DoubleSubscriptedArray( int = 3, int = 3 ); // default constructor // copy constructor 19 DoubleSubscriptedArray( const DoubleSubscriptedArray & ); ~DoubleSubscriptedArray(); // destructor 22 int getrowsize() const; // return number of rows 23 int getcolumnsize() const; // return number of columns const DoubleSubscriptedArray &operator=( 26 const DoubleSubscriptedArray & ); // assignment operator // equality operator 29 bool operator==( const DoubleSubscriptedArray & ) const; // inequality operator; returns opposite of == operator 32 bool operator!=( const DoubleSubscriptedArray &right ) const 33 { 34 // invokes DoubleSubscriptedArray::operator== 35 return!( *this == right ); 36 } // end function operator!=

2 37 38 // function call operator for non-const objects 39 // returns modifiable lvalue 40 int &operator()( int, int ); // function call operator for const objects returns rvalue 43 int operator()( int, int ) const; 44 private: 45 int rowsize; // number of rows in array 46 int columnsize; // number of columns in array 47 int *ptr; // pointer to first element of pointer-based array 48 }; // end class DoubleSubscriptedArray #endif 1 // Exercise Solution: DoubleSubscriptedArray.cpp 2 // DoubleSubscriptedArray class member- and friend-function definitions. 3 #include <iostream> 4 #include <iomanip> 5 #include <cstdlib> // exit function prototype 6 #include "DoubleSubscriptedArray.h" // DoubleSubscriptedArray definition 7 using namespace std; 8 9 // default constructor for class DoubleSubscriptedArray 10 DoubleSubscriptedArray::DoubleSubscriptedArray( 11 int rowsizeentered, int columnsizeentered ) 12 { 13 // validate row and column size 14 rowsize = ( rowsizeentered > 0? rowsizeentered : 3 ); 15 columnsize = ( columnsizeentered > 0? columnsizeentered : 3 ); ptr = new int[ rowsize * columnsize ]; // create space for array for ( int loop = 0; loop < rowsize * columnsize; loop++ ) 20 ptr[ loop ] = 0; // set pointer-based array element 21 } // end DoubleSubscriptedArray default constructor // copy constructor for class DoubleSubscriptedArray; 24 // must receive a reference to prevent infinite recursion 25 DoubleSubscriptedArray::DoubleSubscriptedArray( 26 const DoubleSubscriptedArray &arraytocopy ) 27 : rowsize( arraytocopy.rowsize ), columnsize( arraytocopy.columnsize ) 28 { 29 ptr = new int[ rowsize * columnsize ]; // create space for array 30 2

3 31 for ( int loop = 0; loop < rowsize * columnsize; loop++ ) 32 ptr[ loop ] = arraytocopy.ptr[ loop ]; // copy into object 33 } // end DoubleSubscriptedArray copy constructor // destructor for class DoubleSubscriptedArray 36 DoubleSubscriptedArray::~DoubleSubscriptedArray() 37 { 38 delete [] ptr; // release pointer-based array space 39 } // end destructor // return number of rows of DoubleSubscriptedArray 42 int DoubleSubscriptedArray::getRowSize() const 43 { 44 return rowsize; // number of rows in DoubleSubscriptedArray 45 } // end function getrowsize // return number of columns of DoubleSubscriptedArray 48 int DoubleSubscriptedArray::getColumnSize() const 49 { 50 return columnsize; // number of columns in DoubleSubscriptedArray 51 } // end function getcolumnsize // overloaded assignment operator; 54 // const return avoids: ( a1 = a2 ) = a3 55 const DoubleSubscriptedArray &DoubleSubscriptedArray::operator=( 56 const DoubleSubscriptedArray &right ) 57 { 58 if ( &right!= this ) // avoid self-assignment 59 { 60 // for arrays of different sizes, deallocate original 61 // left-side array, then allocate new left-side array 62 if ( rowsize * columnsize!= right.rowsize * right.columnsize ) 63 { 64 delete [] ptr; // release space 65 rowsize = right.rowsize; // resize this object 66 columnsize = right.columnsize; 67 ptr = new int[ rowsize * columnsize ]; // create space for copy 68 } // end inner if for ( int loop = 0; loop < rowsize * columnsize; loop++ ) 71 ptr[ loop ] = right.ptr[ loop ]; // copy into object 72 } // end outer if return *this; // enables x = y = z, for example 75 } // end function operator= 76 3

4 77 // determine if two DoubleSubscriptedArrays are equal and 78 // return true, otherwise return false 79 bool DoubleSubscriptedArray::operator==( 80 const DoubleSubscriptedArray &right ) const 81 { 82 if ( rowsize * columnsize!= right.rowsize * right.columnsize ) 83 return false; // arrays of different number of elements for ( int loop = 0; loop < rowsize * columnsize; loop++ ) 86 if ( ptr[ loop ]!= right.ptr[ loop ] ) 87 return false; // DoubleSubscriptedArray contents are not equal return true; // DoubleSubscriptedArrays are equal 90 } // end function operator== // overloaded subscript operator for non-const DoubleSubscriptedArrays; 93 // reference return creates a modifiable lvalue 94 int &DoubleSubscriptedArray::operator()( 95 int rowsubscript, int columnsubscript ) 96 { 97 // check for subscript out-of-range error 98 if ( ( rowsubscript < 0 rowsubscript >= rowsize ) 99 ( columnsubscript < 0 columnsubscript >= columnsize ) ) 100 { 101 cerr << "\nerror: One or both subscripts out of range" << endl; 102 exit( 1 ); // terminate program; one or both subscripts out of range 103 } // end if // reference return 106 return ptr[ ( rowsubscript * columnsize ) + columnsubscript ]; 107 } // end function operator() // overloaded subscript operator for const DoubleSubscriptedArrays 110 // const reference return creates an rvalue 111 int DoubleSubscriptedArray::operator()( 112 int rowsubscript, int columnsubscript ) const 113 { 114 // check for subscript out-of-range error 115 if ( ( rowsubscript < 0 rowsubscript >= rowsize ) 116 ( columnsubscript < 0 columnsubscript >= columnsize ) ) 117 { 118 cerr << "\nerror: One or both subscripts out of range" << endl; 119 exit( 1 ); // terminate program; one or both subscripts out of range 120 } // end if // returns copy of this element 4

5 123 return ptr[ ( rowsubscript * columnsize ) + columnsubscript ]; 124 } // end function operator() // overloaded input operator for class DoubleSubscriptedArray; 127 // inputs values for entire DoubleSubscriptedArray 128 istream &operator>>( istream &input, DoubleSubscriptedArray &a ) 129 { 130 for ( int loop = 0; loop < a.rowsize * a.columnsize; loop++ ) 131 input >> a.ptr[ loop ]; return input; // enables cin >> x >> y; 134 } // end function operator>> // overloaded output operator for class DoubleSubscriptedArray 137 ostream &operator<<( ostream &output, const DoubleSubscriptedArray &a ) 138 { 139 for ( int loop = 0; loop < a.rowsize; loop++ ) 140 { 141 for ( int loop2 = 0; loop2 < a.columnsize; loop2++ ) 142 output << a.ptr[ ( loop * a.columnsize ) + loop2 ] << ' '; output << endl; 145 } // end for return output; // enables cout << x << y; 148 } // end function operator<< 1 // Exercise Solution: ex11_11.cpp 2 // DoubleSubscriptedArray class test program. 3 #include <iostream> 4 #include "DoubleSubscriptedArray.h" 5 using namespace std; 6 7 int main() 8 { 9 DoubleSubscriptedArray integers1( 2, 4 ); // seven-element array 10 DoubleSubscriptedArray integers2; // 3-by-3 array by default // print integers1 size and contents 13 cout << "Size of DoubleSubscriptedArray integers1 is " 14 << integers1.getrowsize() << " X " << integers1.getcolumnsize() 15 << "\ndoublesubscriptedarray after initialization:\n" << integers1; // print integers2 size and contents 18 cout << "\nsize of DoubleSubscriptedArray integers2 is " 5

6 19 << integers2.getrowsize() << " X " << integers2.getcolumnsize() 20 << "\ndoublesubscriptedarray after initialization:\n" << integers2; // input and print integers1 and integers2 23 cout << "\nenter 17 integers:" << endl; 24 cin >> integers1 >> integers2; cout << "\nafter input, the DoubleSubscriptedArrays contain:\n" 27 << "integers1:\n" << integers1 28 << "\nintegers2:\n" << integers2 << endl; // use overloaded inequality (!=) operator 31 cout << "Evaluating: integers1!= integers2" << endl; if ( integers1!= integers2 ) 34 cout << "integers1 and integers2 are not equal" << endl; // create DoubleSubscriptedArray integers3 using integers1 as an 37 // initializer with copy constructor; print size and contents 38 DoubleSubscriptedArray integers3( integers1 ); cout << "\nsize of DoubleSubscriptedArray integers3 is " 41 << integers3.getrowsize() << " X " << integers3.getcolumnsize() 42 << "\ndoublesubscriptedarray after initialization:\n" << integers3; // use overloaded assignment (=) operator 45 cout << "\nassigning integers2 to integers1:" << endl; 46 integers1 = integers2; // note target Array is smaller cout << "integers1:\n" << integers1 49 << "\nintegers2:\n" << integers2; // use overloaded equality (==) operator 52 cout << "\nevaluating: integers1 == integers2" << endl; if ( integers1 == integers2 ) 55 cout << "integers1 and integers2 are equal" << endl; // use overloaded subscript operator to create rvalue 58 cout << "\nintegers1( 1, 2 ) is " << integers1( 1, 2 ); // use overloaded subscript operator to create lvalue 61 cout << "\n\nassigning 1000 to integers1( 1, 2 )" << endl; 62 integers1( 1, 2 ) = 1000; 63 cout << "integers1:\n" << integers1; 64 6

7 65 // attempt to use out-of-range subscript 66 cout << "\nattempt to assign 1000 to integers1( 15, 2 )" << endl; 67 integers1( 15, 2 ) = 1000; // ERROR: out of range 68 } // end main Ex // Exercise Solution: Hugeint.h 2 // HugeInt class definition. 3 #ifndef HUGEINT_H 4 #define HUGEINT_H 5 6 #include <iostream> 7 #include <string> 8 using namespace std; 9 10 class HugeInt 11 { 12 friend ostream &operator<<( ostream &, const HugeInt & ); 13 public: 14 static const int digits = 30; // maximum digits in a HugeInt HugeInt( long = 0 ); // conversion/default constructor 17 HugeInt( const string & ); // conversion constructor // addition operator; HugeInt + HugeInt 20 HugeInt operator+( const HugeInt & ) const; // addition operator; HugeInt + int 23 HugeInt operator+( int ) const; // addition operator; 26 // HugeInt + string that represents large integer value 27 HugeInt operator+( const string & ) const; bool operator==( const HugeInt & ) const; // equality operator 30 bool operator!=( const HugeInt & ) const; // inequality operator 31 bool operator<( const HugeInt & ) const; // less than operator // less than or equal to operator 34 bool operator<=( const HugeInt & ) const; 35 bool operator>( const HugeInt & ) const; // greater than operator // greater than or equal to operator 38 bool operator>=( const HugeInt & ) const; 39 HugeInt operator-( const HugeInt & ) const; // subtraction operator 40 HugeInt operator*( const HugeInt & ) const; // multiply two HugeInts 7

8 41 HugeInt operator/( const HugeInt & ) const; // divide two HugeInts int getlength() const; 44 private: 45 short integer[ digits ]; 46 }; // end class HugeInt #endif 1 // Exercise Solution: Hugeint.cpp 2 // HugeInt member-function and friend-function definitions. 3 #include <iostream> 4 #include <cctype> // isdigit function prototype 5 #include "Hugeint.h" // HugeInt class definition 6 using namespace std; 7 8 // default constructor; conversion constructor that converts 9 // a long integer into a HugeInt object 10 HugeInt::HugeInt( long value ) 11 { 12 // initialize array to zero 13 for ( int i = 0; i < digits; i++ ) 14 integer[ i ] = 0; // place digits of argument into array 17 for ( int j = digits - 1; value!= 0 && j >= 0; j-- ) 18 { 19 integer[ j ] = value % 10; 20 value /= 10; 21 } // end for 22 } // end HugeInt default/conversion constructor // conversion constructor that converts a character string 25 // representing a large integer into a HugeInt object 26 HugeInt::HugeInt( const string &number ) 27 { 28 // initialize array to zero 29 for ( int i = 0; i < digits; i++ ) 30 integer[ i ] = 0; // place digits of argument into array 33 int length = number.size(); for ( int j = digits - length, k = 0; j < digits; j++, k++ ) 36 if ( isdigit( number[ k ] ) ) 8

9 37 integer[ j ] = number[ k ] - '0'; } // end HugeInt conversion constructor // get function calculates length of integer 42 int HugeInt::getLength() const 43 { 44 int i; for ( i = 0; i < digits; i++ ) 47 if ( integer[ i ]!= 0 ) 48 break; // break when first digit is reached return digits - i; // length is from first digit (at i) to end of array 51 } // end function getlength // addition operator; HugeInt + HugeInt 54 HugeInt HugeInt::operator+( const HugeInt &op2 ) const 55 { 56 HugeInt temp; // temporary result 57 int carry = 0; for ( int i = digits - 1; i >= 0; i-- ) 60 { 61 temp.integer[ i ] = integer[ i ] + op2.integer[ i ] + carry; // determine whether to carry a 1 64 if ( temp.integer[ i ] > 9 ) 65 { 66 temp.integer[ i ] %= 10; // reduce to carry = 1; 68 } // end if 69 else // no carry 70 carry = 0; 71 } // end for return temp; // return copy of temporary object 74 } // end function operator // addition operator; HugeInt + int 77 HugeInt HugeInt::operator+( int op2 ) const 78 { 79 // convert op2 to a HugeInt, then invoke 80 // operator+ for two HugeInt objects 81 return *this + HugeInt( op2 ); 82 } // end function operator+ 9

10 83 84 // addition operator; 85 // HugeInt + string that represents large integer value 86 HugeInt HugeInt::operator+( const string &op2 ) const 87 { 88 // convert op2 to a HugeInt, then invoke 89 // operator+ for two HugeInt objects 90 return *this + HugeInt( op2 ); 91 } // end function operator // equality operator; HugeInt == HugeInt 94 bool HugeInt::operator==( const HugeInt &op2 ) const 95 { 96 for ( int i = 0; i < digits; i++ ) // compare each element 97 if ( op2.integer[ i ]!= integer[ i ] ) 98 return false; // return false if mismatch found return true; // all elements match, return true 101 } // end function operator== // inequality operator; HugeInt!= HugeInt 104 bool HugeInt::operator!=( const HugeInt &op2 ) const 105 { 106 return!( *this == op2 ); // return opposite of == 107 } // end function operator!= // less than operator; HugeInt < HugeInt 110 bool HugeInt::operator<( const HugeInt &op2 ) const 111 { 112 for ( int i = 0; i < digits; i++ ) // compare each element 113 { 114 if ( integer[ i ] == op2.integer[ i ] ) 115 continue; // test next element 116 else if ( integer[ i ] > op2.integer[ i ] ) 117 return false; // first element larger 118 else 119 return true; // first element smaller 120 } // end for return false; // if reached this point, objects are equal 123 } // end function operator< // less than or equal operator; HugeInt <= HugeInt 126 bool HugeInt::operator<=( const HugeInt &op2 ) const 127 { 128 return!( *this > op2 ); 10

11 129 } // end function operator<= // greater than operator; HugeInt > HugeInt 132 bool HugeInt::operator>( const HugeInt &op2 ) const 133 { 134 return op2 < *this; 135 } // end function operator> // greater than or equal operator; HugeInt >= HugeInt 138 bool HugeInt::operator>=( const HugeInt &op2 ) const 139 { 140 return!( *this < op2 ); 141 } // end function operator>= // overloaded output operator 144 ostream& operator<<( ostream &output, const HugeInt &num ) 145 { 146 int i; for ( i = 0; i < HugeInt::digits && num.integer[ i ] == 0; i++ ) 149 ; // skip leading zeros if ( i == HugeInt::digits ) 152 output << 0; 153 else 154 for ( ; i < HugeInt::digits; i++ ) 155 output << num.integer[ i ]; return output; 158 } // end function operator<< // subtraction operator, subtract op2 from (*this) 161 HugeInt HugeInt::operator-( const HugeInt &op2 ) const 162 { 163 // return if first value is smaller; we are not handling negatives 164 if ( op2 > *this ) 165 { 166 cout << "Error: Tried to subtract larger value from smaller value." 167 << endl; 168 return HugeInt( "0" ); 169 } // end if HugeInt result( "0" ); // final result currently // used to determine if previous digit had 10 added to it; 174 // if true, current digit needs to be reduced by 1 11

12 175 bool minusone = false; // for each digit in both arrays, 178 // subtract digit of smaller int from digit of larger int 179 for ( int i = digits - 1; i >= 0; i-- ) 180 { 181 // find digits we will currently be subtracting 182 int topvalue = this->integer[ i ]; 183 int bottomvalue = op2.integer[ i ]; // if previous topvalue had 10 added to it; 186 // subtract one from current topvalue 187 if ( minusone ) 188 { 189 if ( topvalue == 0 ) // topvalue cannot become // set to 9 but keep minusone true for next digit 191 topvalue = 9; 192 else 193 { 194 topvalue -= 1; // subtract from top value 195 minusone = false; // minusone is handled, return to false 196 } // end else 197 } // end outer if if ( topvalue >= bottomvalue ) 200 // if topvalue larger, perform subtraction and store result 201 result.integer[ i ] = topvalue - bottomvalue; 202 else 203 { 204 topvalue += 10; // if bottomvalue larger, add 10 to topvalue 205 minusone = true; // next digit must be decreased // topvalue is now larger, perform subtraction and store result 208 result.integer[ i ] = topvalue - bottomvalue; 209 } // end else 210 } // end for return result; // return final result 213 } // end function operator // multiplication operator; multiply op2 with (*this) 216 HugeInt HugeInt::operator*( const HugeInt &op2 ) const 217 { 218 int carryover = 0; // carry value when previous digits are multiplied 219 HugeInt total( "0" ); // result currently

13 221 // find the smaller int 222 HugeInt smaller = ( *this < op2 )? *this : op2; 223 HugeInt larger = ( *this > op2 )? *this : op2; // determine index of larger's first digit; used to determine 226 // when to stop multiplying 227 int x; for ( x = 0; ( x < digits ) && ( larger.integer[ x ] == 0 ); x++ ) 230 ; int indexoffirstdigitforlarger = x; // for each digit in smaller, multiply by each digit in larger 235 for ( int i = digits; i > digits - smaller.getlength(); i-- ) 236 { 237 // currentint stores result of current digit in 238 // smaller multiplied by digits in larger 239 HugeInt currentint( "0" ); // currentintfronthandle used to keep track of 242 // index of first digit in currentint 243 int currentintfronthandle = i - 1; // multiply each digit in larger with the current digit in smaller; 246 // go backward from last digit in larger to first digit 247 for ( int j = digits; j > digits - larger.getlength(); j-- ) 248 { 249 // perform multiplication; 250 // add carryover from previous multiplications 251 int currentresult = carryover ( larger.integer[ j - 1 ] * smaller.integer[ i - 1 ] ); // if we have reached the first digit of larger 255 if ( j - 1 == indexoffirstdigitforlarger ) 256 { 257 carryover = 0; // no more carryover required // store two digits at beginning of currentint, update handle 260 currentint.integer[ currentintfronthandle ] = 261 currentresult % 10; 262 currentintfronthandle -= 1; 263 currentint.integer[ currentintfronthandle ] = 264 currentresult / 10; 265 currentintfronthandle -= 1; 266 } // end if 13

14 267 else 268 { 269 // carryover is first digit when currentresult > carryover = currentresult / 10; // store remaining digit in current result; update handle 273 currentint.integer[ currentintfronthandle ] = 274 currentresult % 10; 275 currentintfronthandle -= 1; 276 } // end else 277 } // end inner for total = total + currentint; // add current result to running total 280 } // end outer for return total; // return product 283 } // end function operator* // division operator; divide op2 by (*this) 286 HugeInt HugeInt::operator/( const HugeInt &op2 ) const 287 { 288 // use copy constructor to create remainderintegers; 289 // remainderintegers used to add digits to remainders 290 HugeInt remainderintegers( *this ); // contains portion of (*this) 293 HugeInt currentvalue( "0" ); 294 HugeInt result( "0" ); // final result, 0 for now // solution will not be longer than original value being divided 297 int maxsolutionlength = this->getlength(); // for each digit in value being divided 300 for ( int i = digits - maxsolutionlength; i < digits; i++ ) 301 { 302 // add remainder to end of current value 303 currentvalue = currentvalue * HugeInt( "10" ); 304 currentvalue.integer[ digits - 1 ] = remainderintegers.integer[ i ]; HugeInt tempresult( "0" ); // result of currentvalue divided by op if ( op2 > currentvalue ) 309 // store result of op2 / currentvalue 310 result.integer[ i ] = 0; 311 else 312 { 14

15 313 int j; // op2 / currentvalue cannot be greater than 9; 316 // use loop to determine what solution is 317 for ( j = 1; j <= 10; j++ ) 318 { 319 HugeInt tempproduct = op2 * HugeInt( j ); // if op2 * HugeInt( j ) is greater than currentvalue, 322 // then op2 / currentvalue is the value of j if ( tempproduct > currentvalue ) 324 break; 325 } // end for result.integer[ i ] = j - 1; // result of op2 / currentvalue // product used to determine next value that must be divided 330 tempresult = op2 * HugeInt( j - 1 ); 331 } // end else // subtract tempresult to get remainder used to continue division 334 currentvalue = currentvalue - tempresult; 335 } // end for return result; 338 } // end function operator/ 1 // Exercise Solution: ex11_14.cpp 2 // HugeInt test program. 3 #include <iostream> 4 #include "Hugeint.h" 5 using namespace std; 6 7 int main() 8 { 9 HugeInt n1( ); 10 HugeInt n2( ); 11 HugeInt n3( " " ); 12 HugeInt n4( "1" ); 13 HugeInt n5( " " ); 14 HugeInt n6( "7888" ); 15 HugeInt result; cout << "n1 is " << n1 << "\nn2 is " << n2 18 << "\nn3 is " << n3 << "\nn4 is " << n4 15

16 19 << "\nn5 is " << n5 << "\nn6 is " << n6 20 << "\nresult is " << result << "\n\n"; // test relational and equality operators 23 if ( n1 == n2 ) 24 cout << "n1 equals n2" << endl; if ( n1!= n2 ) 27 cout << "n1 is not equal to n2" << endl; if ( n1 < n2 ) 30 cout << "n1 is less than n2" << endl; if ( n1 <= n2 ) 33 cout << "n1 is less than or equal to n2" << endl; if ( n1 > n2 ) 36 cout << "n1 is greater than n2" << endl; if ( n1 >= n2 ) 39 cout << "n1 is greater than or equal to n2" << endl; result = n1 + n2; 42 cout << n1 << " + " << n2 << " = " << result << "\n\n"; cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n"; result = n1 + 9; 47 cout << n1 << " + " << 9 << " = " << result << endl; result = n2 + "10000"; 50 cout << n2 << " + " << "10000" << " = " << result << endl; result = n5 * n6; 53 cout << n5 << " * " << n6 << " = " << result << endl; result = n5 - n6; 56 cout << n5 << " - " << n6 << " = " << result << endl; result = n5 / n6; 59 cout << n5 << " / " << n6 << " = " << result << endl; 60 } // end main 16

17 Ex // Exercise Solution: Polynomial.h 2 // Polynomial class definition. 3 #ifndef POLYNOMIAL_H 4 #define POLYNOMIAL_H 5 6 class Polynomial 7 { 8 public: 9 static const int maxterms = 100; // maximum number of terms Polynomial(); 12 Polynomial operator+( const Polynomial & ) const; // addition 13 Polynomial operator-( const Polynomial & ) const; // subtraction 14 Polynomial operator*( const Polynomial & ) const; // multiplication 15 Polynomial &operator=( const Polynomial & ); // assignment 16 Polynomial &operator+=( const Polynomial & ); 17 Polynomial &operator-=( const Polynomial & ); 18 Polynomial &operator*=( const Polynomial & ); 19 void enterterms(); 20 void printpolynomial() const; 21 int getnumberofterms() const; // user can only retrieve value 22 int gettermexponent( int ) const; 23 int gettermcoefficient( int ) const; 24 void setcoefficient( int, int ); // set coefficient of a specific term 25 ~Polynomial(); // destructor 26 private: 27 int numberofterms; 28 int exponents[ maxterms ]; // exponent array 29 int coefficients[ maxterms ]; // coefficients array 30 static void polynomialcombine( Polynomial & ); // combine common terms 31 }; // end class Polynomial #endif 1 // Exercise Solution: Polynomial.cpp 2 // Polynomial member-function definitions. 3 #include <iostream> 4 #include <iomanip> 5 #include "Polynomial.h" 6 using namespace std; 7 8 Polynomial::Polynomial() 17

18 9 { 10 for ( int t = 0; t < maxterms; t++ ) 11 { 12 coefficients[ t ] = 0; 13 exponents[ t ] = 0; 14 } // end for numberofterms = 0; 17 } // end Polynomial constructor void Polynomial::printPolynomial() const 20 { 21 int start; 22 bool zero = false; if ( coefficients[ 0 ] ) // output constants 25 { 26 cout << coefficients[ 0 ]; 27 start = 1; 28 zero = true; // at least one term exists 29 } 30 else 31 { 32 if ( coefficients[ 1 ] ) 33 { 34 cout << coefficients[ 1 ] << 'x'; // constant does not exist 35 // so output first term 36 // without a sign 37 if ( ( exponents[ 1 ]!= 0 ) && ( exponents[ 1 ]!= 1 ) ) 38 cout << '^' << exponents[ 1 ]; zero = true; // at least one term exists 41 } // end inner if start = 2; 44 } // end else // output remaining polynomial terms 47 for ( int x = start; x < maxterms; x++ ) 48 { 49 if ( coefficients[ x ]!= 0 ) 50 { 51 cout << showpos << coefficients[ x ] << noshowpos << 'x'; if ( ( exponents[ x ]!= 0 ) && ( exponents[ x ]!= 1 ) ) 54 cout << '^' << exponents[ x ]; 18

19 55 56 zero = true; // at least one term exists 57 } // end if 58 } // end for if (!zero ) // no terms exist in the polynomial 61 cout << '0'; cout << endl; 64 } // end function printpolynomial Polynomial &Polynomial::operator=( const Polynomial &r ) 67 { 68 exponents[ 0 ] = r.exponents[ 0 ]; 69 coefficients[ 0 ] = r.coefficients[ 0 ]; for ( int s = 1; s < maxterms; s++ ) 72 { 73 if ( r.exponents[ s ]!= 0 ) 74 { 75 exponents[ s ] = r.exponents[ s ]; 76 coefficients[ s ] = r.coefficients[ s ]; 77 } 78 else 79 { 80 if ( exponents[ s ] == 0 ) 81 break; exponents[ s ] = 0; 84 coefficients[ s ] = 0; 85 } // end else 86 } // end for return *this; 89 } // end function operator= Polynomial Polynomial::operator+( const Polynomial &r ) const 92 { 93 Polynomial temp; 94 bool exponentexists; 95 int s; // process element with a zero exponent 98 temp.coefficients[ 0 ] = coefficients[ 0 ] + r.coefficients[ 0 ]; // copy right arrays into temp object; s will be used to keep 19

20 101 // track of first open coefficient element 102 for ( s = 1; ( s < maxterms ) && ( r.exponents[ s ]!= 0 ); s++ ) 103 { 104 temp.coefficients[ s ] = r.coefficients[ s ]; 105 temp.exponents[ s ] = r.exponents[ s ]; 106 } // end for for ( int x = 1; x < maxterms; x++ ) 109 { 110 exponentexists = false; // assume exponent will not be found for ( int t = 1; ( t < maxterms ) && (!exponentexists ); t++ ) 113 if ( exponents[ x ] == temp.exponents[ t ] ) 114 { 115 temp.coefficients[ t ] += coefficients[ x ]; 116 exponentexists = true; // exponent found 117 } // end if // exponent was not found, insert into temp 120 if (!exponentexists ) 121 { 122 temp.exponents[ s ] = exponents[ x ]; 123 temp.coefficients[ s ] += coefficients[ x ]; 124 s++; 125 } // end if 126 } // end for return temp; 129 } // end function operator Polynomial &Polynomial::operator+=( const Polynomial &r ) 132 { 133 *this = *this + r; 134 return *this; 135 } // end function operator+= Polynomial Polynomial::operator-( const Polynomial &r ) const 138 { 139 Polynomial temp; 140 bool exponentexists; 141 int s; // process element with a zero exponent 144 temp.coefficients[ 0 ] = coefficients[ 0 ] - r.coefficients[ 0 ]; // copy left arrays into temp object; s will be used to keep 20

21 147 // track of first open coefficient element 148 for ( s = 1; ( s < maxterms ) && ( exponents[ s ]!= 0 ); s++ ) 149 { 150 temp.coefficients[ s ] = coefficients[ s ]; 151 temp.exponents[ s ] = exponents[ s ]; 152 } // end for for ( int x = 1; x < maxterms; x++ ) 155 { 156 exponentexists = false; // assume exponent will not be found for ( int t = 1; ( t < maxterms ) && (!exponentexists ); t++ ) if ( r.exponents[ x ] == temp.exponents[ t ] ) 161 { 162 temp.coefficients[ t ] -= r.coefficients[ x ]; 163 exponentexists = true; // exponent found 164 } // end if // exponent was not found, insert into temp 167 if (!exponentexists ) 168 { 169 temp.exponents[ s ] = r.exponents[ x ]; 170 temp.coefficients[ s ] -= r.coefficients[ x ]; 171 s++; 172 } // end if 173 } // end for return temp; 176 } // end function operator Polynomial &Polynomial::operator-=( const Polynomial &r ) 179 { 180 *this = *this - r; 181 return *this; 182 } // end function operator-= Polynomial Polynomial::operator*( const Polynomial &r ) const 185 { 186 Polynomial temp; 187 int s = 1; // subscript location for temp coefficient and exponent for ( int x = 0; ( x < maxterms ) && 190 ( x == 0 coefficients[ x ]!= 0 ); x++ ) for ( int y = 0; ( y < maxterms ) && 21

22 193 ( y == 0 r.coefficients[ y ]!= 0 ); y++ ) if ( coefficients[ x ] * r.coefficients[ y ] ) if ( ( exponents[ x ] == 0 ) && ( r.exponents[ y ] == 0 ) ) 198 temp.coefficients[ 0 ] += 199 coefficients[ x ] * r.coefficients[ y ]; 200 else 201 { 202 temp.coefficients[ s ] = 203 coefficients[ x ] * r.coefficients[ y ]; 204 temp.exponents[ s ] = exponents[ x ] + r.exponents[ y ]; 205 s++; 206 } // end else polynomialcombine( temp ); // combine common terms 209 return temp; 210 } // end function operator* void Polynomial::polynomialCombine( Polynomial &w ) 213 { 214 Polynomial temp = w; // zero out elements of w 217 for ( int x = 0; x < maxterms; x++ ) 218 { 219 w.coefficients[ x ] = 0; 220 w.exponents[ x ] = 0; 221 } // end for for ( int x = 1; x < maxterms; x++ ) 224 { 225 for ( int y = x + 1; y < maxterms; y++ ) 226 if ( temp.exponents[ x ] == temp.exponents[ y ] ) 227 { 228 temp.coefficients[ x ] += temp.coefficients[ y ]; 229 temp.exponents[ y ] = 0; 230 temp.coefficients[ y ] = 0; 231 } // end if 232 } // end outer for w = temp; 235 } // end function polynomialcombine Polynomial &Polynomial::operator*=( const Polynomial &r ) 238 { 22

23 239 *this = *this * r; 240 return *this; 241 } // end function operator*= void Polynomial::enterTerms() 244 { 245 bool found = false; 246 int c, e, term; cout << "\nenter number of polynomial terms: "; 249 cin >> numberofterms; for ( int n = 0; n < maxterms && n < numberofterms; n++ ) 252 { 253 cout << "\nenter coefficient: "; 254 cin >> c; 255 cout << "Enter exponent: "; 256 cin >> e; if ( c!= 0 ) 259 { 260 // exponents of zero are forced into first element 261 if ( e == 0 ) 262 { 263 coefficients[ 0 ] += c; 264 continue; 265 } // end if for ( term = 1; ( term < maxterms ) && 268 ( coefficients[ term ]!= 0 ); term++ ) if ( e == exponents[ term ] ) 271 { 272 coefficients[ term ] += c; 273 exponents[ term ] = e; 274 found = true; // existing exponent updated 275 } // end if if (!found ) // add term 278 { 279 coefficients[ term ] += c; 280 exponents[ term ] = e; 281 } // end if 282 } // end outer if 283 } // end outer for 284 } // end function endterms 23

24 int Polynomial::getNumberOfTerms() const 287 { 288 return numberofterms; 289 } // end function getnumberofterms int Polynomial::getTermExponent( int term ) const 292 { 293 return exponents[ term ]; 294 } // end function gettermexponent int Polynomial::getTermCoefficient( int term ) const 297 { 298 return coefficients[ term ]; 299 } // end function gettermscoefficient void Polynomial::setCoefficient( int term, int coefficient ) 302 { 303 if ( coefficients[ term ] == 0 ) // no term at this location 304 cout << "No term at this location, cannot set term." << endl; 305 else // otherwise, set term 306 coefficients[ term ] = coefficient; 307 } // end function setterm // destructor 310 Polynomial::~Polynomial() 311 { 312 // empty destructor 313 } // end destructor 1 // Exercise Solution: ex11_17.cpp 2 // Polynomial test program. 3 #include <iostream> 4 #include "Polynomial.h" 5 using namespace std; 6 7 int main() 8 { 9 Polynomial a, b, c, t; a.enterterms(); 12 b.enterterms(); 13 t = a; // save the value of a 14 cout << "First polynomial is:\n"; 15 a.printpolynomial(); 24

25 16 cout << "Second polynomial is:\n"; 17 b.printpolynomial(); 18 cout << "\nadding the polynomials yields:\n"; 19 c = a + b; 20 c.printpolynomial(); 21 cout << "\n+= the polynomials yields:\n"; 22 a += b; 23 a.printpolynomial(); 24 cout << "\nsubtracting the polynomials yields:\n"; 25 a = t; // reset a to original value 26 c = a - b; 27 c.printpolynomial(); 28 cout << "\n-= the polynomials yields:\n"; 29 a -= b; 30 a.printpolynomial(); 31 cout << "\nmultiplying the polynomials yields:\n"; 32 a = t; // reset a to original value 33 c = a * b; 34 c.printpolynomial(); 35 cout << "\n*= the polynomials yields:\n"; 36 a *= b; 37 a.printpolynomial(); 38 cout << endl; 39 } // end main 25

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

W8.2 Operator Overloading

W8.2 Operator Overloading 1 W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

Introduction. W8.2 Operator Overloading

Introduction. W8.2 Operator Overloading W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information

EECE.3220: Data Structures Spring 2017

EECE.3220: Data Structures Spring 2017 EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based

More information

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes

More information

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Review: C++ Basic Concepts. Dr. Yingwu Zhu Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2305/lab06.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 2 Extend the IntegerSet class from Lab 04 to provide the following

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Operator Overloading

Operator Overloading Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is

More information

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1 Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures

More information

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

การทดลองท 8_2 Editor Buffer Array Implementation

การทดลองท 8_2 Editor Buffer Array Implementation การทดลองท 8_2 Editor Buffer Array Implementation * File: buffer.h * -------------- * This file defines the interface for the EditorBuffer class. #ifndef _buffer_h #define _buffer_h * Class: EditorBuffer

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.

More information

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class What you will learn from Lab 4 In this laboratory, you will learn how to use const to identify constant pointer and the basic of

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with

More information

Object oriented programming

Object oriented programming Exercises 12 Version 1.0, 9 May, 2017 Table of Contents 1. Virtual destructor and example problems...................................... 1 1.1. Virtual destructor.......................................................

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

Lecture 23: Pointer Arithmetic

Lecture 23: Pointer Arithmetic Lecture 23: Pointer Arithmetic Wai L. Khoo Department of Computer Science City College of New York November 29, 2011 Wai L. Khoo (CS@CCNY) Lecture 23 November 29, 2011 1 / 14 Pointer Arithmetic Pointer

More information

BITG 1113: Array (Part 1) LECTURE 8

BITG 1113: Array (Part 1) LECTURE 8 BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/04/lab04.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 3 In this assignment create an IntegerSet class that will provide

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects

More information

Midterm Examination. Instructor: Gary Chan Date: Saturday, 23 October 2010 Time: 2:30pm 4:00pm Venue: LTC

Midterm Examination. Instructor: Gary Chan Date: Saturday, 23 October 2010 Time: 2:30pm 4:00pm Venue: LTC THE HONG KONG UNIVERSITY OF SCIENCE & TECHNOLOGY Department of Computer Science & Engineering COMP 152: Object-Oriented Programming and Data Structures Fall 2010 Midterm Examination Instructor: Gary Chan

More information

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.) Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* TNCG18(C++): Lec 10 1 Class string Template class

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Exam 3 Chapters 7 & 9

Exam 3 Chapters 7 & 9 Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False

More information

Topics. bool and string types input/output library functions comments memory allocation templates classes

Topics. bool and string types input/output library functions comments memory allocation templates classes C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers

More information

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture: CISC 2200 Data Structure Fall, 2016 C++ Review:3/3 1 From last lecture: pointer type and pointer variable (stores memory addresses of a variable (of any type, local or global, automatic/static/dynamic)

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std; More Group HW The following code is contained in the file ex1stck.h. Fill in the blanks with the C++ statement(s) that will correctly finish the method. Each blank may be filled in with more than one statement.

More information

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each). A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Chapter 11. if (prev!= 0) { newptr->next = prev->next; prev->next = newptr; if (current == 0) // new last element in priority queue myback = newptr;

Chapter 11. if (prev!= 0) { newptr->next = prev->next; prev->next = newptr; if (current == 0) // new last element in priority queue myback = newptr; Chapter 11: More Linking Up with Linked Lists Exercises 11.1 1. The implementation of the Queue class using a linked list in Section 8.3 can be easily converted to a class template (see how this was done

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

C++ Programming Assignment 3

C++ Programming Assignment 3 C++ Programming Assignment 3 Author: Ruimin Zhao Module: EEE 102 Lecturer: Date: Fei.Xue April/19/2015 Contents Contents ii 1 Question 1 1 1.1 Specification.................................... 1 1.2 Analysis......................................

More information

TEMPLATE IN C++ Function Templates

TEMPLATE IN C++ Function Templates TEMPLATE IN C++ Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates.

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/06/lab06.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 2 Extend the IntegerSet class from Lab 04 to provide the following

More information

1 Short Answer (5 Points Each)

1 Short Answer (5 Points Each) 1 Short Answer ( Points Each) 1. Find and correct the errors in the following segment of code. int x, *ptr = nullptr; *ptr = &x; int x, *ptr = nullptr; ptr = &x; 2. Find and correct the errors in the following

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions

Homework 3. Due: Feb 25, 23:59pm. Section 1 (20 pts, 2 pts each) Multiple Choice Questions Homework 3 Due: Feb 25, 23:59pm Section 1 (20 pts, 2 pts each) Multiple Choice Questions Q1: A function that modifies an array by using pointer arithmetic such as ++ptr to process every value of the array

More information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM CS 117 Programming II, Spring 2018 Dr. Ghriga Midterm Exam Estimated Time: 2 hours March 21, 2018 DUE DATE: March 28, 2018 at 12:00 PM INSTRUCTIONS: Do all exercises for a total of 100 points. You are

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

Chapter 7: Stacks. Exercises 7.2

Chapter 7: Stacks. Exercises 7.2 hapter 7: Stacks Exercises 7.2 1. mytop == 0; myrray contains 3 elements: 10, 22, 37,?,? but note that only element 10 is considered to be in the stack. 2. mytop == 1; myrray contains 3 elements: 10, 9,

More information

CS 247: Software Engineering Principles. ADT Design

CS 247: Software Engineering Principles. ADT Design CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

Local and Global Variables

Local and Global Variables Lecture 10 Local and Global Variables Nearly every programming language has a concept of local variable. As long as two functions mind their own data, as it were, they won t interfere with each other.

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

CSC 330 Object-Oriented Programming. Exception Handling CSC 330 Object-Oriented Programming Exception Handling 1 C++ Exception Handling Topics Exception Handling C++ Exception Handling Basics Throwing and Catching Exceptions Constructors, Destructors and Exceptions

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data

More information

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47 Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers

More information

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter What you will learn from Lab 7 In this laboratory, you will understand how to use typical function prototype with

More information

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang C++11 Move Constructors and Move Assignment For Introduction to C++ Programming By Y. Daniel Liang C+11 provides move constructors and move assignment to improve performance by moving a large rvalue object

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes... CISC 2000 Computer Science II Fall, 2014 Note 11/13/2014 1 Review of operator overloading (a) Lab class: take-away ############################ # Pass-by-value parameters # ############################

More information

FORM 2 (Please put your name and form # on the scantron!!!!)

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

Intermediate Programming & Design (C++) Classes in C++

Intermediate Programming & Design (C++) Classes in C++ Classes in C++ A class is a data type similar to a C structure. It includes various local data (called data members) together with constructors, destructors and member functions. All of them are called

More information

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Fall 2015 Jill Seaman 1 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements Chapter 5 Looping Building on the foundation Now that we know a little about cout cin math operators boolean operators making decisions using if statements Advantages of Computers Computers are really

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

Faculty of Science, Engineering and Technology

Faculty of Science, Engineering and Technology Swinburne University of Technology Faculty of Science, Engineering and Technology ASSIGNMENT COVER SHEET Subject Code: COS30008 Subject Title: Data Structures and Patterns Assignment number and title:

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

CpSc212 Goddard Notes Chapter 10. Linked Lists

CpSc212 Goddard Notes Chapter 10. Linked Lists CpSc212 Goddard Notes Chapter 10 Linked Lists 10.1 Links and Pointers The linked list is not an ADT in its own right; rather it is a way of implementing many data structures. It is designed to replace

More information

Circle all of the following which would make sense as the function prototype.

Circle all of the following which would make sense as the function prototype. Student ID: Lab Section: This test is closed book, closed notes. Points for each question are shown inside [ ] brackets at the beginning of each question. You should assume that, for all quoted program

More information

Comp151. Generic Programming: Container Classes

Comp151. Generic Programming: Container Classes Comp151 Generic Programming: Container Classes Container Classes Container classes are a typical use for class templates, since we need container classes for objects of many different types, and the types

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

Object-Oriented Programming in C++

Object-Oriented Programming in C++ Object-Oriented Programming in C++ Pre-Lecture 9: Advanced topics Prof Niels Walet (Niels.Walet@manchester.ac.uk) Room 7.07, Schuster Building March 24, 2015 Prelecture 9 Outline This prelecture largely

More information

for (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;

for (int i = 1; i <= 3; i++) { do { cout << Enter a positive integer: ; cin >> n; // Workshop 1 #include using namespace std; int main () int n, k; int sumdigits; for (int i = 1; i n; cin.clear (); cin.ignore (100,

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

05-01 Discussion Notes

05-01 Discussion Notes 05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

Set Implementation Version 1

Set Implementation Version 1 Introduction to System Programming 234122 Set Implementation Version 1 Masha Nikolski, CS Department, Technion 1 // Version 1.0 2 // Header file for set class. 3 // In this implementation set is a container

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

Chapter 12: Searching: Binary Trees and Hash Tables. Exercises 12.1

Chapter 12: Searching: Binary Trees and Hash Tables. Exercises 12.1 Chapter 12: Searching: Binary Trees and Hash Tables Exercises 12.1 1. 4, 6 2. 4, 1, 2, 3 3. 4, 6, 5 4. 4, 1, 0 5. 4, 6, 7, 8 6. template linearsearch(elementtype x[], ElementType

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information