Example of a for loop:
public class Factorial {
public static void main(String[] args) {
int n = 4; // compute the factorial of n
int fact = 1; // initial value
for(int i = 1; i <= n; i++) {
fact = fact * i; // loop body
}
System.out.println("factorial of " + n + " is " + fact);
}
}
This loop is exactly the same as this 'while' loop:
public class Factorial {
public static void main(String[] args) {
int n = 4; // compute the factorial of n
int fact = 1; // initial value
int i = 1; // initialization
while (i <= n) {
fact = fact * i; // loop body
i++; // increment
}
System.out.println("factorial of " + n + " is " + fact);
}
}
This is an example from CSci 2101 course.