100 likes | 116 Views
Enhanced for loop (for each loop). 7.2-7.3. Enhanced for loop. An enhanced for loop allows you to cycle through every element in an array without using the index
E N D
Enhanced for loop(for each loop) 7.2-7.3
Enhanced for loop • An enhanced for loop allows you to cycle through every element in an array without using the index • Important to note that a For Each loop will not allow you to change the values stored in the array. It will only allow you to access them.
Syntax • for(type name: array) • Example: int[]values = {… }; int total = 0; for(int a : values) //for each int a in array values { total += a; }
This will not work for(int a : values) { a = 0; }
What does it do? for(int a : values) { if(a%2 = 0) count++; }
Removing an element from an array If I want to remove the element at index pos for(inti = pos+1; i<values.length; i++) { values[i-1]=values[i]; }
Insert an element at pos(given the array is not full) intcurrentSize = … //#of indexes used If(currentSize < values.length) { for(int I = currentSize – 1; i>pos; i--) values[i] = values[i-1] values[pos]=newElement; }
Homework • Create an integer array with 10 random integers from 1 to 20. Use an enhanced for loop to calculate the average of those elements. Display the result. • Create an integer array with 10 random integers. Put the array in order from least to greatest. Print the result.