Programming and Graphics

(Kiana) #1

110 Introduction to C++ Programming and Graphics


The following main program contained in the file prj.cccalls a user-
defined function to compute the inner product (projection) of two vector arrays:


#include <iostream>
using namespace std;

void prj (double[], double[], int, double&);

//--- main ---

int main()
{
const int n=2;
double a[n] ={0.1, 0.2};
double b[n] ={2.1, 3.1};
double prod;
prj (a,b,n,prod);
cout << "inner product: " << prod << endl;
return 0;
}

//--- prj ---

void prj (double a[], double b[], int n, double& prod)
{
prod = 0.0;
for (int i=0;i<=n-1;i++)
prod = prod + a[i]*b[i];
}

Running this program prints on the screen:


inner product: 0.83

Constant arguments


To deny a user-defined function the privilege of changing the values of a
communicated array, we declare the array as “constant” in the function call. If
the function attempts to change the values of this array, an error will be issued
during compilation. Consider the following working code:


#include <iostream>
#include <cmath>

using namespace std;
Free download pdf