For Loops
For loops are the most complicated kind of loop, but they are probably used the most often. Many times you use a loop counter to keep track of how many times the loop has executed. If you use a while loop, you initialize the loop counter before the loop, have a while loop with a certain condition, and then update the loop counter somewhere in the loop code. A for loop combines those three steps.
For loop syntax
Here is the syntax of a for loop:
for (initialization; condition; update)
{
//statements
}Example: while loop vs for loop
Here is a while loop that adds the numbers from 1 to 4 and then prints the sum:
int sum = 0;
int count = 1;
while (count < 5)
{
sum = sum + count;
count = count + 1;
}
System.out.printf("Sum: %d%n", sum);In this example, our loop counter is count. We could rewrite our example using a for loop instead:
int sum = 0;
for (int count = 0; count <= 5; count++)
{
sum += num;
}
System.out.printf("The sum is %d%n", sum);Another for loop example
Here’s another example, that prints out all odd numbers between 1 and 100. Notice that we increment the loop counter by 2 so we can immediately step to the next odd number:
for (int num = 1; num <= 100; num+=2)
{
System.out.println(num);
}