For loop - Java Basics
For loops are the most abundantly used loops, their importance derives from its easy implementation to its overall effectiveness. A common task in programming is to repeat a task, and with for loops this can be achieved.
Unlike while and do loops, for loops [in my opinion] are easiest to implement. Without having to increment the dependent variable inside the loops body, or declare the variable within a scope reachable, the for loop accomplishes this all, in its parameters.
For loops can have multiple for loops nested within each other, this is a perfect setup for traversing 2 dimensional arrays or analyzing images (however they're linear so they're not great for images)
- Step 1 - Basics of a for loop
For loops have three basic components, in parameter order:
- A declared variable
- A limit to incrementally reach
- A set amount to increment
for(int i = 0 ; i < 10 ; i++)
//print a line
The three components are separated by two semi-colons. The first declaration int i = 0 creates a variable i and initializes it to 0. The second declaration tells the loop when to stop "looping". It's comparison based so only comparitor operators can be used: <, >, <=, >=, ==. And the third and final component tells the loop at what increment it will increase or decrease by for every loop(++ is incrementing by 1).
- Step 2 - Converting the for Loop into other Types of Loops
Java has three types of loops:
- for loop
- while loop
- do loop
Recusrion can also be used as a loop, however it's primarly reserved for more complex issues.
Loops can be easily converted from one to another. All loops have the same three components as mentioned above.
- how to plan a for loop.
- how to convert the for loop into the while and do loops.
Questions or Comments? Hit the "Questions/Help" tab