Sunday, January 2, 2011

Java Tutorial #18

0
Java’s enhanced for Loop
Java developed a special for loop for array application is it is called the enhanced for loop. The enhanced for loop will take two arguments unlike the traditional for loop which is taking three arguments. Java developed a special for loop for array application. Its general equation is:

for (type identifier: name_array)

Where: type is the data type, identifier is a variable that will store value in the array every time the loop is going through. For example

input[ ] = {6, 2, 3, 4, 5};

identifier will hold 6, then it will hold 2, and later it will hold 3. Everytime the loop is going through, it hold the value in the array one at a time. For example

for (int var: input);

var is the identifier of the array input.

Consider this program:


First, I declare an array named “"input" and I declare a variable then initialize it to zero.
"sum" will hold the value each time the values are added. I created an enhanced for loop. I use "var" to hold each element in the array and I included the name of the array. The formula will add 0 to the first value in the array, then it will add the outcome of the previous operation to the second value in the array. Later, It will add the outcome of the previous operation to the third value until it reach the last value in the array. At last, it will display the sum of all the values in the array. This is the output.





No Response to "Java Tutorial #18"

Post a Comment