A Deeper Look into Step-by-step Execution (Loops)
Learn to execute the code using the GNU Debugger.
Working of a loop (step-by-step execution)
Look at the animation below and observe the changes in the state of the program (by looking at the local variables section).
The code in the animation above contains a for
loop. In the right-hand side panel of the animation above, we can see the value of the variable Time
as it changes during the for
loop execution. This debugging feature will be especially helpful as we write some complex code in the upcoming lessons.
Run the code below by following the steps in the animation above.
#include<iostream> using namespace std; int main() { for(int Time=1; Time<=5; Time++) { cout << Time<< ": hello" << endl; } return 0; }
Varying the variable’s value: Pausing on a specific iteration
During execution, we can change the value of the variables during runtime.
Below is one example where we change the value of the variable debug
. We use this trick to execute in debug mode and pause the program on a specific iteration of the loop.
Look at the animation below.
In the code above, the if
condition would never have been true if we didn’t explicitly change the value of the debug
variable.
To get to the 180th iteration directly, we make debug
equal to 180
and place a breakpoint inside the if
block ( line 18). This way, we get to the 180th iteration with t = 180
.
From the animation above, we saw that we can change a variable’s value during runtime. If there are a large number of iterations in the code, we can jump to any particular iteration we want by changing the value of the variable.
Run the code below to repeat the steps in the animation above and make the same changes:
#include<iostream> using namespace std; int main() { int Table, Start, End, debug = -1; cout << "Table: "; cin>>Table; cout <<"Start: "; cin>>Start; cout <<"End: "; cin>>End; for(int t=Start; t<=End; t++) { if(t == debug) { debug++; debug--; } cout << Table<< " x " << t << " = "<< Table*t << endl; } return 0; }