1. (30 points) TRUE or FALSE
2. (0 points) Given the class String, (partially) defined as follows:
class String { private: char letters[80]; public: char String::letter(int n); // Returns the nth letter in the string void String::operator=(char S[]); };
void String::operator=(char S[]) { int i; for(i = 0; (i < 79) && (S[i] != 0); i++) letter[i] = S[i]; letter[i] = 0; }
String Foo; Foo = "This is a test, this is only test";
3. (30 points) Show how you would use an fstream object to open a file called "numbers", write the numbers 1 through 100 in it, each on a seperate line, then close the file.
int i; fstream nfile; nfile.open("numbers", ios::out); for(i = 1; i <= 100; i++) nfile << i << endl; nfile.close();
4. (10 points) Write a recursive function called count_ones() that takes an integer n as a parameter and returns the number of ones in the binary representation of n.
int count_ones(int n) { if(n == 0) // Anchor case: there are no 1's in 0 return(0); else // Recursive case: lowest bit + count_ones( the rest ) return( (n & 1) + count_ones(n >> 1) ); }OR
int count_ones(int n) { if(n == 0) // Anchor case: there are no 1's in 0 return(0); else // Recursive case: lowest bit + count_ones( the rest ) return( (n % 2) + count_ones(n / 2) ); }