1 / 10

Enhanced for loop (for each loop)

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

edithyoung
Download Presentation

Enhanced for loop (for each loop)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Enhanced for loop(for each loop) 7.2-7.3

  2. 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.

  3. Syntax • for(type name: array) • Example: int[]values = {… }; int total = 0; for(int a : values) //for each int a in array values { total += a; }

  4. This will not work for(int a : values) { a = 0; }

  5. What does it do? for(int a : values) { if(a%2 = 0) count++; }

  6. Finding Min/Max Value

  7. Linear SearchFind the first occurrence a value

  8. 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]; }

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

  10. 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.

More Related