Note- This video is really hard, the next video is way easier to understand than this one… sorry about that, I got excited

Topics Discussed: For loops, nested for loops, nested for loop structure, nested loops

Source Code Available Here

For loops
For loops are similar in idea to a while statement, except that it contains a few other parts that need to be talked about after I give an example of the syntax and use of for loops:

for(int i=0; i<10; i++){ System.out.println(i); }

The above code does 4 things, one of which is apparent, the println() statement, so we won't talk about that. But the for statement can be a little confusing, but when we break it into parts it will make a lot more sense.

Parts of a for loop
Every loop has three parts, which are as follows:

  1. The initializer: This part of the loop is where we set or declare some variable for use. Typically you'll see something set to 0 here if you're counting up to a variable.
  2. The conditional:The conditional is the same as with a while loop. It should be a statement that evaluates to a true, false, or boolean(t/f) statement.
  3. The iterator:The iterator is the part of the for loop in which we increase, decrease, or otherwise change some aspect of the loop, usually to make the loop get closer to it's conclusion.

Additional considerations of for loops
The syntax and usage of for loops can be a little tricky overall:

for(int i=0; i<10; i++){ //null } System.out.println(i); //This will error

The above is an example of an error that I see quite often among my peers in college. Despite the initializer coming before the scope bracket, it is considered part of the scope of the loop. Therefore we can thing of the scope of a for loop being like this:

for{(int i=0; i<10; i++) //do stuff }
rather than its existing structure.

Nested for structure
Nested for's actually share syntax with nested if statements in terms of scoping and complexity. Granted there aren't any else statements to take into consideration.

Last modified: October 14, 2013