K-12 CS Teacher Professional Development Workshop
Reading
This is what a for loop from integers 0-2 looks like (// denotes a comment, which is basically a line that the program skips while compiling. If you want to comment multiple lines, you use /* and */):
for (int i = 0; i < 2; i = i + 1) {
//info
}
How to trace this loop: int i = 0 is a variable declaration. The loop checks if i < 2. If it is, then the program runs and executes whatever is inside the curly braces. Once it has reached the closing curly brace, it returns to the for loop head and adds 1 because of the i = i + 1. Now i equals 1. It then checks if i < 2. If it is, the loop runs again. After it is done running, it adds 1 to i. Now i equals 2. i is no longer less than 2, so the for loop ends.
This is what a while loop from integers 0-2 looks like:
int i = 0;
int b = 2;
while (i < b) {
i = i + 1;
//You could also replace the line above with i++; or i+=1; They all mean the same thing. These two lines
//are shortcuts to adding implemented to reduce the amount you have to type.
}
How to trace this loop: It is traced similarly to the while loop, except the variables must be declared before the loop for there to be a condition in the while loop. First, we declare our two comparison variables. i is initialized to be 0 and b is initialized to be 2. A while loop is created which only runs if i < b. As long as this condition is true, the loop will run endlessly. Once the condition is checked, then 1 will be added to i as specified by i = i + 1. i is now 1. The condition of i < b is checked again to see if i < b. i is 1 and b is 2, so it runs once again. i is incremented by 1. i is now 2. After the code is ran, it returns to the condition. i is no longer less than b, so the while loop ends.