Enhancing a for loop with an array

This is a specialized way of looping through all the elements of an array to do something with each element.

class jamesprogram {

	public static void main(String args[]){

		int james[]={2,4,6,8,10}; // array initializer
		int total=0;
		
		for (int count: james){
			
			total+=count;
			System.out.println(total);
			
		}
	}
}

The program here declared, ‘int count’ is the type and identifier, what variable you are going to store the array values in, and declare the array you are working with ‘james’.

This program outputs:

2
6
12
20
30

Leave a Reply