Created
February 22, 2011 05:14
-
-
Save Zren/838261 to your computer and use it in GitHub Desktop.
Loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For loops are a simple way to count numbers in a pattern. In this case the pattern is that all numbers | |
// increase by one each cycle through the loop. The first cycle will start with the variable i (which | |
// is an integer (a number, but not a fraction)) as the number 0. Then the next cycle, it's 1, then 2 ... | |
// All the way until the last cycle where it's 9, then when you add by 1 and make i = 10 | |
for (Assign local seed value; exit conditional; increment or modify the variable) { | |
System.out.println(i); | |
} | |
// The whole time, whenever the cycle forced us to increment the number (+1), then it was also checking the | |
// exit conditional (i < 10). When i = 1, it checked to make sure (1 < 10), which was a true statement. | |
// At the point where i = 10, the exit conditional (i < 10) would be shown as (10 < 10). A statement which | |
// is false. Since the exit conditional is false, it exits the loop. | |
for (int i = 0; i < 10; i++) { | |
System.out.println(i); | |
} | |
// While loops are more customizable, but more dangerous if you don't know what your doing. As you can make | |
// infinite loops really easily. | |
while (true) {} | |
// There is one main difference from the for loop, it will check the exit condition (the part inside the | |
// brackets) first before cycling though the loop. | |
int i = 0; // We need to make the counter variable ourselves. | |
while (true) { | |
System.out.println(i); | |
// We need to increment the counter ourselves | |
i += 1; | |
if (i >= 10) { // We need to check the exit conditional ourselves. When this statement is true ... | |
break; // Exit the loop | |
} | |
} | |
int i = 0; | |
// We could also move the conditional here. However we must have the condition be a true | |
// statement for it to run, and then become a false statement for it to exit. | |
while (i < 10) { | |
System.out.println(i); | |
i += 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment