CPSC170A
Fundamentals of Computer Science II

Lab 20

Arrays

Trace Arrays

For each of the follwing, what will be printed when it is run. If it produces a compile or runtime error, just put error. If prints something, but it can’t be predicted, put unknown.

  1. int main() {
      int array[3];
      for (int i = 0; i < 3; i++) {
        array[i] = i;
      }
      std::cout << array[0] << std::endl;
      std::cout << array[1] << std::endl;
      std::cout << array[2] << std::endl;
      std::cout << array[3] << std::endl;
      return 0;
    }
  2. void func(int array[]) {
      array[0]++;
    }
    
    int main() {
      int array[] = {1};
      std::cout << array[0]  << std::endl;
      return 0;
    }
  3. int main() {
      int array[] = {1, 2, 3};
      int* p1 = array;
      int* p2 = &array[0];
      int* p3 = &array[1];
      std::cout << *p1 << " " << *p2  << " " << *p3 << std::endl;
      return 0;
    }
  4. int main() {
      int array[3];
      int* p = array;
      for (int i = 0; i < 3; i++) {
        *p = i;
        p++;
      }
      std::cout << array[0] <<  " " << array[1] << " " << array[2] << std::endl;
      return 0;
    }
  5. int main() {
      const char* str = "hello";
      int n = 0;
      while(*(str++) != '\0') {
        n++;
      }
      std::cout << n << std::endl;
      return 0;
    }
  6. int main() {
      int matrix[2][2] = {{1, 2}, {3, 4}};
      int x = matrix[0][1];
      int* p = matrix[0] + 2;
      std::cout << x << " " << *p  << std::endl;
      return 0;
    }


Sort

Write the C++ function void sort(int array[], int size) that sorts the array in place. That is, it doesn’t create a second array to help sort the input array. Instead it repeatedly uses the swap function you wrote for the last lab to change the order of the elements. The function should use a for loop to find a pointer to the smallest element and then swap the first element with the smallest. Repeat this with each remaining element until the list is sorted.