|
for (x = 1, 2, 3, ..., n) do
{
if ( n is divisible by x )
{
print x; // x is a divisor of n
}
}
|
The variable x takes on the values 1, 2, 3, ..., n one at a time
For each value, we check whether n is divisible by x
If so, we print the value x (and obtain all divisors)
|
for ( var = START_VALUE ; var <= STOP_VALUE ; var = var + INCR )
{
/* for-body (statements) */
}
|
Meaning:
|
public class For01
{
public static void main(String[] args)
{
int a;
// Example "for-statement"
for ( a = 1 ; a <= 10 ; a = a + 1 )
{
System.out.println(a); // Print a
}
System.out.println("Done");
}
}
|
Output: 1 2 (1+1×1) 3 (1+2×1) 4 (1+3×1) 5 (1+4×1) 6 (1+5×1) 7 (1+6×1) 8 (1+7×1) 9 (1+8×1) 10 (1+9×1) Done |
Notice that in the for-statement:
|
How to run the program:
|
public class For01
{
public static void main(String[] args)
{
int a;
// Changing the starting value:
for ( a = 5; a <= 10; a = a + 1 )
{
System.out.println(a); // Print a
}
System.out.println("Done");
}
}
|
Output: 5 6 (5+1×1) 7 (5+2×1) 8 (5+3×1) 9 (5+4×1) 10 (5+5×1) Done |
Notice that in the for-statement:
|
public class For01
{
public static void main(String[] args)
{
int a;
// Changing the continuation condition:
for ( a = 1; a <= 3; a = a + 1 )
{
System.out.println(a); // Print a
}
System.out.println("Done");
}
}
|
Output: 1 2 (1+1×1) 3 (1+2×1) Done |
Notice that in the for-statement:
|
public class For01
{
public static void main(String[] args)
{
int a;
// Changing the increment statement:
for ( a = 1; a <= 10; a = a + 2 )
{
System.out.println(a); // Print a
}
System.out.println("Done");
}
}
|
Output: 1 3 (1+1×2) 5 (1+2×2) 7 (1+3×2) 9 (1+4×2) Done |
Notice that in the for-statement:
|
public class For01
{
public static void main(String[] args)
{
int a;
// Changing the increment statement:
for ( a = 4; a <= 14; a = a + 3 )
{
System.out.println(a); // Print a
}
System.out.println("Done");
}
}
|
Answer:
4 7 (4 + 1×3) 10 (4 + 2×3) 13 (4 + 3×3) Done |
Because:
|
Explanation:
|
|
|
|
(I have used colors to highlight the correspondence of the pieces in the Java language syntax and in the flow chart)
|
|
In this case, the for-statement will:
|
|
In this case, the for-statement will:
|
for ( a = 1 ; a <= 10 ; a++ )
{
System.out.println(a);
}
System.out.println("Done");
|
Flow chart of this program:
|
Note: this is the same flow chart we saw before belonging to this program fragment:
a = 1;
while ( a <= 10 )
{
System.out.println(a);
a++;
}
System.out.println("Done");
|
|
|
|
|
|
|
|
How to "read" the diagram:
|