Winter 2020

PIC 10A: Introduction to Programming

Discussion Section 3A

Wonjun Lee



Week9

Tuesday and Thursday

Many problems related to vector

Exercise P6.1.

Write a function

double scalar_product(vector< double > a, vector< double > b)

that computes the scalar product of two vectors. The scalar product is

a0 b0 + a1 b1 + ... + an-1 bn−1

Solution
#include < iostream >
#include < vector >

using namespace std;

double scalar_product(vector< double > a, vector< double > b)
{
  double sum = 0;
  for(int i = 0; i < a.size(); ++i)
  {
    sum += a[i] * b[i];
  }
  return sum;
}

int main()
{
  vector< double > a = {1, 2, 3};
  vector< double > b = {2, 1, -1};

  double answer = scalar_product(a,b);

  cout << answer << endl; // Expect to print out 1
}

            
Exercise P6.2.

Write a function that computes the alternating sum of all elements in a vector. For example, if alternating_sum is called with a vector containing

1 4 9 16 9 7 4 9 11

then it computes

1 − 4 + 9 − 16 + 9 − 7 + 4 − 9 + 11 = −2

Solution
#include < iostream >
#include < vector >

using namespace std;

int alternating_sum(vector< int > a)
{
  int sum = 0;
  for(int i = 0; i < a.size(); ++i)
  {
    sum += pow(-1,i) * a[i];
  }
  return sum;
}

int main()
{
  vector< int > a = {1,4,9,16,9,7,4,9,11};

  int answer = alternating_sum(a);

  cout << answer << endl; // Expect to print out -2
}

            
Exercise P6.3.

Write a procedure reverse that reverses the sequence of elements in a vector. For example, if reverse is called with a vector containing

1 4 9 16 9 7 4 9 11

then the vector is changed to

11 9 4 7 9 16 9 4 1

Solution
#include < iostream >
#include < vector >

using namespace std;

void reverse(vector< int >&  a) // Important : I am using passing by reference here.
{
  for(int i = 0; i < a.size()/2; ++i)
  {
    int tmp = a[i];
    a[i] = a[a.size() - i];
    a[a.size() - i] = tmp;
  }
}

int main()
{
  vector< int > a = {1,4,9,16,9,7,4,9,11};

  reverse(a);

  for(int i = 0; i < a.size(); ++i){
    cout << a[i] << ", ";
  }
  cout << endl;
}

            
Exercise P6.4.

Write a function

vector< int > append(vector< int > a, vector< int > b)

that appends one vector after another. For example, if a is

1 4 9 16

and b is

9 7 4 9 11

then append returns the vector

1 4 9 16 9 7 4 9 11

Solution
#include < iostream >
#include < vector >

using namespace std;

vector< int > append(const vector< int >&  a, const vector< int >&  b)
{
  // Create a new vector c (which is empty when initialized)
  vector < int > c;

  // push back all of items in a
  for(int i=0; i < a.size(); ++i)
  {
    c.push_back(a[i]);
  }

  // push back all of items in b
  for(int i=0; i < b.size(); ++i)
  {
    c.push_back(b[i]);
  }

  return b
}

int main()
{
  vector< int > a = {1,4,9,16};
  vector< int > b = {9,7,4,9,11};

  vector< int > c = append(a, b);

  for(int i = 0; i < a.size(); ++i){
    cout << c[i] << ", ";
  }
  cout << endl;
}