Tracing Functions View Code

Tracing code is an excellent way to help you think in programming. By doing so you can see the processes of the program better, and you can check for bugs more easily. To trace code it is recommend that you have a physical copy of it in front of you, a pencil, and a sheet of scratch paper. (Faulty print outs make great scrap.)

Back to Functions and Libraries

Blocks

cout << "Print variables";
int A, B;
A = 5;  B = 2; 
cout << "The sum is " << A+B;
B *= 3
Print variableThe sum is 6

A: 5 13
B: 2

If you couldn't tell, the left block is the example code, this is the scratch work, and the right is the thought process.
  1. Print to the screen "Print variables".
  2. Make variables A and B.
  3. A has value 5, and B has value 2.
  4. Print to screen, same place, "The sum is·".
  5. B has value of 2*3.

Logic

int A = 4, B = 3;
char ch = '4';
if ( A <= B )
   ch = 't';
else
{
   int c = 4 / b * 2 - 1;
   cout << c << B+A << endl;
}
cout << "A+B" << ch;
17¶
A+B4

A: 4
B: 3
ch: 4
c: 1
  1. Declare variables A with value 4, and B with 3.
  2. Declare a character ch with value '4'.
  3. Check if A is less than B. It is not skip to the else.
  4. Declare c with value 4/3*2-1 = 1*2-1 = 2-1 = 1
  5. Print the value of c, 1, then value of B+A, 7, then a new line.
  6. Print the string, "A+B", then the value of ch, '4'.

Functions

void swap(int& A, int& B)
{
   int temp = A;
	 A = B;
	 B = temp  
}
void swap2(int A, int B)
{
   int temp = A;
   A = B;
   B = temp  
}
int f(int c, int v)
{
   return c + c * v;
}
int main()
{
   double g = 1.98, t = .09;
   int num = 3, x = 3, y = 1;
   cout << "Total" << f(g, t) << endl;
   swap(x, y); swap2(num, y)
   cout << num << ' ' << x << ' ' << y;  
}
Total2.1582¶
5 1 3

g: 1.98
t: .09
num: 5
x: 31 (after swap())
y: 13 (after swap())

f()
c:1.98
v:.09

swap()
A(ref): 31
B(ref): 13
temp: 3

swap2()
A: 32
B: 23
temp: 3

Since this simple block involves a lot of calls, the explanation is below.

  1. Declare double's g as 1.98 and t as .09.
  2. Declare ints num as 5, x as 3, and y as 1.
  3. Print "Total" then call f(g, t)
    1. Declare variables "by value" c and v with the values of f an g.
    2. Return the value of the expression, 1.98 + 1.98 * .09 = 2.1582
  4. With the return value of 2.1582 print it screen, then a new line.
  5. Call swap with x and y.
    1. Declare variables "by reference" A and B with the values of x an y.
    2. Declare temp with value of A.
    3. Assign B to A, then temp to B.
  6. Copy the value of A and B to x and y, since they were by reference.
  7. Call swap2 with num and y.
    1. Declare variables "by value" A and B with the values of num an y.
    2. Declare temp with value of A.
    3. Assign B to A, then temp to B.
  8. Print out num, space x, space, then y.

Back to Functions and Libraries

Prev -- Back to Portal -- Next