Lec 21 More Fun with Arrays: For Loops
Agenda Some backfill for Lab 20: For Loops vs While loops Using an array in an applet or class array instance variables For Loops vs While loops not that big a deal Nested for Loops For Loops and Arrays more ways to process Plotting data on the screen
For loops Demo While loop that prints the numbers 1 to 10 For loop that does the same thing While loop that adds the numbers from 50 to 60 Declaring the loop counter in the for header scope limited to loop "body" Changing the loop increment Ascending or descending loops Nested for loops – used to draw a grid of squares
Arrays – Using for loops For loops are a more compact way of processing arrays Instead of this: System.out.print(a[0]); System.out.print(a[1]); System.out.print(a[2]); System.out.print(a[3]); System.out.print(a[4]); System.out.print(a[5]); You can do this: for (k=0; k<6; k++) System.out.print(a[k]);
For Loop and Array Demo Assigning a sequence of values to an array suppose we want data to have 10,20,30,40,50 Putting a set of random values into an array Defining array cell k using previous cell k-1 new value = old value / 2 Counting how many 3's are in an array
Searching for a value in an array Suppose you want to know if 13 is in the data array. Naive approach: for (int k=0; k<11; k++){ if (data[k]==13) output "found 13 at cell" + k else output "13 not found" } the problem ? if data[0] doesn't match, you can't tell after looking at one cell that it's not there
A solution? assume value 13 is not in the array boolean found = false; visit each cell in the array, if there's a match display "found 13 at cell " + k, set found to true otherwise, do nothing (no else) but continue to check next cell After loop, if found is still false, say "not found"
Finding the max in the array: set max = 0 visit every cell using counter k if data cell k is bigger than max set max to data cell value at position k set maxindex equal to k (to remember the k value) when the loop ends, max will have largest value in array, maxindex will tell you which cell it was in
Quiz Determine the values generated and stored in the following array int [] data = new int[8]; data[0] = 5; for (k=1; k<8; k++) data[k]= data[k-1]*2;
Quiz 2. Determine the values generated and stored in the following array int [] data2 = new int[8]; for (k=0; k<8; k++) data2[k]=k+100;
Final Project