
The For Loop
So far, we have introduced one loop statement which is the while loop. Now, we will introduce another iteration method which is the for loop. This loop is mainly used like a while loop but it differs in syntax. Let's take a look at an abstract view of the for loop.
for(expression1; condition; expression2)
expression3
Now that is a lot of new stuff. Let's explain step by step and you will notice how easy and convenient a
for loop is. Check the list below which explains everything about the previous for loop.
expression1is executed only once and that is at the beginning of aforloop. This is usually used to set a counter.conditionis similar to that of awhileloop. If the condition is false, terminate theforloop.expression2is executed at the end. Note that it is executed afterexpression3. This expression usually handles the counter.expression3is the code you want to execute at every iteration.
Let's look at the for loop with a real code example. We will just print to screen the numbers from one to ten.
public class PrintNumbers
{
public static void main(String args[])
{
for(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Let's explain this program using the list we introduced.
expression1: (int i = 0;
condition: i <= 10;
expression2: i++)
expression3: System.out.println(i);
At each iteration, the program checks if i is less than or equal to ten. If so, it will print i to screen THEN it will be incremented by one.
Factorial Example
Let's write a code that takes an integer from the user and computes the factorial of that integer using a for loop. The factorial of a number (denoted by an exlamation mark) is that number multiplied by every positive number that precedes it. For example, the factorial of five is
5! = 5 x 4 x 3 x 2 x 1 = 125
By convention, 0! is equal to one. Now enough math talk and let's take a look at the code.
import java.util.Scanner;
public class Factorial
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int result = 1;
for(int i = 2; i <= n; i++)
{
result *= i;
}
System.out.println(n+"! = "+result);
}
}
Output
5
5! = 120
In the previous program, we are reading an integer n from the user and we want to compute the factorial of that number. Then, we are creating another integer which will contain the result. We initialized result to one so that if the user enters a zero or a one, the output will be one and will be correct according to the factorial theorem. Then, we create a for loop to compute the result.
First of all, the for loop starts from two so that if a user enters zero or one, the for loop will not execute. The condition of the for loop is that i should be less than or equal to the number entered by the user. Finally, i will get incremented by one at the end.
Now let's take a look at the body of the for loop. What we are doing is multiplying result by i in every iteration and by doing so, result will contain the value of the factorial of n at the end. Take a look at sequence of execution of the for loop.
Step 1: Initialize i to 2
Step 2: Check if i is less than or equal to n
Step 3: Multiply result by i
Step 4: increment i by one
Step 5: repeat from step 2
Nesting for Loops
Now we will cover the concept of nesting which is a fairly simple concept. Nesting means putting a for loop inside another one (same concept applies to a while loop). Nothing explains this better than coding. Take a look at the following program, it will display the multiples up to ten of the numbers from two to five.
public class Multiples
{
public static void main(String args[])
{
for(int i = 2; i <= 5; i++)
{
System.out.print("Multiples of "+i+": ");
for(int j = 1; j <= 10; j++)
{
System.out.print((i*j)+" ");
}
System.out.println();
}
}
}
Output:
Multiples of 2: 2 4 6 8 10 12 14 16 18 20
Multiples of 3: 3 6 9 12 15 18 21 24 27 30
Multiples of 4: 4 8 12 16 20 24 28 32 36 40
Multiples of 5: 5 10 15 20 25 30 35 40 45 50
Congratulations
You now know how to use a for loop and how to nest it. Try editing the Multiples program by allowing the user to enter the range of the for loops instead of a constant value. Then, move on to the next tutorial but first check the following important notes.
Important Notes
Infinite Looping
The same issue of infinite looping can occur when using a for loop. Therefore, always check your code so that you don't encounter an infinite loop.
Nesting
When dealing with nested loops, always make your code tidy and easy to read so that you don't have trouble debugging or fixing errors. Nesting needs practice and a programmers should always know when and how to nest loops.
Naming Standards
You maybe wondering why we use i and j as counters in the for loop. This is a naming standard used by most of the programming languages. It is always i, then j, and if you have a third nested loop , we use the letter k.
Love the for Loop
Yes love the for loop and adore it. You will be using mostly this kind of loop in any of the programs you will write in the future. Moreover, it is the loop used when dealing with arrays which you will also use a lot in your programming life. Always remember, for and array are married to each other.