CSCI 1300
Introduction to Computing


Quiz #3

1. (30 points) TRUE or FALSE

  1. FALSE - 2D arrays take up twice as much memory as 1D arrays.
    A 2D array 2darray[m][n] takes up n times as much memory as a 1D array 1darray[n].

  2. TRUE - C++ arrays start with the 0th element.

  3. FALSE - Class constructors can't take parameters.
    Constructors can take parameters

  4. TRUE - Overloading is defining multiple functions with the same name but different parameters.

  5. FALSE - After you create a file, you can't change the size.
    After you create a file, you can change the size by writing or appending to it.

  6. TRUE - If you open an fstream object for writing, you can't read from it.

  7. FALSE - In graphics mode, the screen is just a big array of pixels with (0,0) in the lower left.
    (0,0) is in the upper left

  8. FALSE - Linear search is faster and more efficient than Binary search.
    In general, Binary search is faster and more efficient.

  9. TRUE - Binary search only works on sorted lists.

  10. FALSE - Functions cannot call themselves.
    Functions can call themselves. This is recursion.

 

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[]);
  };
  1. Write the String::operator=() function.
      void String::operator=(char S[])
      {
        int i;
    
        for(i = 0; (i < 79) && (S[i] != 0); i++)
          letter[i] = S[i];
    
        letter[i] = 0;
        
      }
    
  2. Show how you would use the = operator to initialize an object of type String.
      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) );
  }