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;
	    }

	    System.out.println("factorial of " + n + " is " + fact);
	}
 
}


Example of arrays:

public class Array1 {
    public static void main(String [] args) {
	int [] a = new int[5]; // declaring an array

	// initializing some elements:
	a[0] = 1;
	a[1] = 3;
	a[2] = 5;

	// priniting the array
	for (int i = 0; i < a.length; i++) {
	    System.out.println("a[" + i + "] = " + a[i]);
	}
    }
}


This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.