Programming and Graphics

(Kiana) #1

112 Introduction to C++ Programming and Graphics


#include <iostream>
using namespace std;

const int n=2;
void trace (double[][n], double&);

//---------------- main -----------------

int main()
{
double a[n][n] ={{0.1, 0.2},{0.9, 0.5}};
double Trace;
trace (a, Trace);
cout << "Trace: " << Trace << endl ;
return 0;
}

//---------------- trace -----------------

void trace (double a[][n], double& Trace)
{
Trace= 0.0;
for(int i=0; i<=n-1; i++)
{
Trace = Trace + a[i][i];
}
}

Running the core prints on the screen:


Trace: 0.6

An alternative implementation of thetracefunction that passes the trace
through the function return is:


double trace (double a[][n])
{
Trace=0.0;
for(int i=1; i<=n-1; i++)
{
Trace = Trace + a[i][i];
}
return Trace;
}

In this case, the function call is:


double Trace = trace (double a[][n]);
Free download pdf