6. Debugger

The execution of programs by hand provides insight into mechanics of any new program we encounter. Even the best programmers like to use it in order to better understand some complicated pieces of code. A debugger is a tool that provides a more sophisticated, computer-assisted way of doing pretty much the same thing, including a few nice bonuses, too.

Since execution by hand plays an important role in this chapter, we kindly ask you to revisit it now by manually executing the program given below. This process will also help you understand how the given program works. So, pick up the usual accessories: a paper, a pencil and an eraser.

#include <iostream>
using namespace std;

int main() 
{ 
    double sum=0;
    cout << "Let us start out with the number 0." << endl;
    
    for (double i=1; i<=5; i++)
        {
        sum = sum+i;
        cout << "After adding the number " << i << endl;
        cout << "the total sum will be " << sum << "." << endl;
        }
}

Before you begin executing this program, divide the piece of paper into three parts: one for the standard input, one for the standard output and one for the memory. Just to remind you what this process looks like, we will execute the first statement of the function main:

STDINSTDOUTMEMORY
sum    0

As you can see, this program has no values given on the standard input. This is not a problem, as it will not be reading any (as can be deduced from the absence of the cin statements in the source code).

One additional note: if you find yourself confused by this statement

        sum = sum+i;

then go back to the chapter Variables, where we have covered this particular case in the section "X Becomes x Plus 3".

Roll up your sleeves! All is ready now for execution by hand.
Ready, steady, go!

As the result of executing this program by hand, the following text should appear on your standard output:

STDOUT

Let us start out with the number 0.
After adding the number 1
the total sum will be 1.
After adding the number 2
the total sum will be 3.
After adding the number 3
the total sum will be 6.
After adding the number 4
the total sum will be 10.
After adding the number 5
the total sum will be 15.

Upon completing the execution by hand, under memory section you should have the following values for the variables sum and i:[*]

sum   15
i      5

As promised, we will now execute this program again statement by statement, but this time with the help of a computer. To make this possible, you should now type this program in your IDE. A tool called a debugger enables execution of a program one statement at a time.