Help with manually stepping through these loops
Hey everyone, I was wondering if you could explain the 'best approach' in manually stepping through the following lines of code. It has two loops but the main problem in understanding the code is when the variables change. I want to be able to follow line for line but I loose track of the current value and so I was wondering how you keep track of the updating variables.
Code :
public static int pascalsTriangle(int n){
int[][] pt = new int[n][];
for(int i=0; i<n; i++){
pt[i] = new int[i+1];
pt[i][0]=1;
for(int j=1; j<1; j++){
pt[i][j] = pt[i-1][j-1]+pt[i-1]+pt[j];
}
pt[i][i]=1;
}
return pt;
}
This is a method for the pascal triangle. As you can see, the variables of i (in the first loop) and j(in the second loop) are updating. How do you keep track with the changing variables to see what is going on?
Thanks!
Re: Help with manually stepping through these loops
Take a copy and pencil, start from the first line and use your copy page as the stack or heap and your pencil as a pointer to store values in stack and heap. Now keep on tracing the code. Forexample;
Code :
for(int i=0;i<3;i++){
System.out.println(i);
}
First, i must know what for loop do, so i know that it iterates the body until it's condition gets false.
Now i=0 and condition is if 0<3 that is true, it will go to the body, print the i value, increment the i value to 1 and again check the condition 1<3, true again, body will be executed again, i will be incremented and so on.....