Java For Loops
for (initialization; condition; update) { // repeats until test condition is false }
Example 1: Simple for loop
for (int i=0; i<=10; i++) System.out.print(i);
The outout will be:
012345678910
Example 2: Printing single digit numbers with spaces
for (int i=0; i<10; i++) System.out.print(i+" ");
Output:
0 1 2 3 4 5 6 7 8 9
Example 3: Tricky for loop example
for (int i=0; i<10; i++) System.out.print(i+" "); System.out.print("+");
0 1 2 3 4 5 6 7 8 9 +
What to learn from this example?: scope of for loops is only 1 line (one line below). If we need to repeat more than one line of code block, we need to use { } to expand the scope of for loop.
Example 4: Re-write of Example 3 with expanded scope
for (int i=0; i<10; i++) { System.out.print(i+" "); System.out.print("+"); }
0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +
Example 5: We can use for loops inside of other for loops
for (int i=0; i<10; i++) { for (int j=0; j<10; j++) { System.out.print(" i="+i+" j="+j); } System.out.println(""); }
i=0 j=0 i=0 j=1 i=0 j=2 i=0 j=3 i=0 j=4 i=0 j=5 i=0 j=6 i=0 j=7 i=0 j=8 i=0 j=9 i=1 j=0 i=1 j=1 i=1 j=2 i=1 j=3 i=1 j=4 i=1 j=5 i=1 j=6 i=1 j=7 i=1 j=8 i=1 j=9 i=2 j=0 i=2 j=1 i=2 j=2 i=2 j=3 i=2 j=4 i=2 j=5 i=2 j=6 i=2 j=7 i=2 j=8 i=2 j=9 i=3 j=0 i=3 j=1 i=3 j=2 i=3 j=3 i=3 j=4 i=3 j=5 i=3 j=6 i=3 j=7 i=3 j=8 i=3 j=9 i=4 j=0 i=4 j=1 i=4 j=2 i=4 j=3 i=4 j=4 i=4 j=5 i=4 j=6 i=4 j=7 i=4 j=8 i=4 j=9 i=5 j=0 i=5 j=1 i=5 j=2 i=5 j=3 i=5 j=4 i=5 j=5 i=5 j=6 i=5 j=7 i=5 j=8 i=5 j=9 i=6 j=0 i=6 j=1 i=6 j=2 i=6 j=3 i=6 j=4 i=6 j=5 i=6 j=6 i=6 j=7 i=6 j=8 i=6 j=9 i=7 j=0 i=7 j=1 i=7 j=2 i=7 j=3 i=7 j=4 i=7 j=5 i=7 j=6 i=7 j=7 i=7 j=8 i=7 j=9 i=8 j=0 i=8 j=1 i=8 j=2 i=8 j=3 i=8 j=4 i=8 j=5 i=8 j=6 i=8 j=7 i=8 j=8 i=8 j=9 i=9 j=0 i=9 j=1 i=9 j=2 i=9 j=3 i=9 j=4 i=9 j=5 i=9 j=6 i=9 j=7 i=9 j=8 i=9 j=9
An upper loop iteration increases as the inner loop ends. We are using System.out.println("") to create a new line at the end of each line.
Example 6: We can use for loops for iterating Arrays.
String[] languages = {"C", "C Sharp", "Java", "C++", "Visual Basic"}; for (String lang : languages) { System.out.println(lang); }
C C Sharp Java C++ Visual Basic