Tracing Examples


Trace the program below, showing memory and output.
int main ()
{
	int i = 0, tot = 0;
	while (i < 4)
	{
	   i++;
	   cout << i << i * 2 << endl; 
	   tot += i;

	}
	cout << "tot is " << tot;
	return 0;
}

Memory  i:  0 1 2 3 4 
	tot: 0 1 3 6 10
Output:
	1  2
	2  4
	3  6
	4  8
	tot is 10
// usually the variables are shown going down the board

Example of tracing a function:

double fun1(double b, int c);

double fun1(double b, int c)
{
	double k;
	cout << "here" << endl;
	k = b * c;
	cout << " k is " << k << endl;
	return k;
}
int main ()
{
	double x, y, m;
	int r = 2;
	cout << "in main " << endl;
	x = 5.0;
	y = 3;
	m = fun1 (x, r);
	cout << "in main m =  "<< m << endl;
	m = fun1 (y, r);
	cout << " in main now m = " << m << endl;
	return 0;
}

Trace:
Memory:
	x: 5.0
	y: 3.0
 	r: 2
	k: 10.0  6.0 

during fun1
	b: 5.0
	c: 2
	k: 10.0

during fun1
	b: 3.0
	c: 2
	k: 6.0
	
Output:
in main
here
 k is 10.0
in main m = 10.0
here
 k is 6.0
in main now m = 6.0