For loops and Arrays

advertisement
Lec 21
More Fun with Arrays:
For Loops
Agenda
• Some backfill for Lab 20:
– Using an array in an applet or class
– array instance variables
– using Math.random() just like you did in Lab5
• index = Math.round(Math.random()*adjectives.length );
• For Loops vs While loops
– not that big a deal
• For Loops and Arrays
– more ways to process
• Frogs and Toads – Pad class
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
– For loop that does the same thing
• 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]);
4
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
• Draw the following arrays
int [] data = new int[8];
data[0] = 5;
for (k=1; k<8; k++) data[k]= data[k-1]*2;
int [] data2 = new int[8];
for (k=0; k<8; k++) data2[k]=k+100;
9
Final Project
Each Week
• We'll spend Thursdays going over another aspect of
the final project
• You'll get more out of these sessions if you foray
ahead on your own before hand
• Extra credit: 1 point for each day you hand in early!!
up to 20 max
• DO NOT hand your solutions to another student—
you'll both get zero for whole project (one grade
lower for class)
• It's supposed to be a challenge—do your best
– I expect you to refer to previous labs/solutions for help
Download