15
Fundamentals of Softw are Development I Programming patterns involvin g iteration 1 Programming patterns Programming patterns involving iteration involving iteration Overview Loops Overview Loops We’ll also see how loops are We’ll also see how loops are often combined with arrays often combined with arrays (officially your next topic), (officially your next topic), e.g., -- e.g., --

Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Embed Size (px)

Citation preview

Page 1: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

1

Programming patterns Programming patterns involving iterationinvolving iteration

• Overview LoopsOverview Loops• We’ll also see how loops are often We’ll also see how loops are often

combined with arrays (officially your combined with arrays (officially your next topic), e.g., --next topic), e.g., --

Page 2: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

2

Programming patterns Programming patterns involving iterationinvolving iteration

• We’ll review loops – We’ll review loops – – some of the important variations, and some of the important variations, and – ways you can use them toward certain ends.ways you can use them toward certain ends.

• We’ll also see how loops are often We’ll also see how loops are often combined with arrays (officially your next combined with arrays (officially your next topic), e.g., --topic), e.g., --– Processing every member of an arrayProcessing every member of an array– Searching for things in an arraySearching for things in an array– Loops within loops for multi-dimensional Loops within loops for multi-dimensional

tablestables

Page 3: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

3

LoopsLoops• A A looploop is: is:

– a block of code that executes a block of code that executes repeatedly while some condition repeatedly while some condition holds true.holds true.

• Java provides three forms for Java provides three forms for explicit loops:explicit loops:– whilewhile– forfor– do..whiledo..while

• The The conditionsconditions in loops are in loops are written as in written as in ifif statements statements

• The The breakbreak statement breaks statement breaks out of the loop that it is withinout of the loop that it is within

• Some loop examples followSome loop examples follow

while (while (conditioncondition) {) { statement; statement; … … statement;statement;}}

for (start; for (start; condition; stepcondition; step) {) { statement; statement; … … statement;statement;}}

do {do { statement;statement; … … statement;statement;} while (} while (conditioncondition););

Page 4: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

4

forfor loops versus loops versus whilewhile loops loops• for (for (int i = 0int i = 0; ; i < 7i < 7; ; i++i++) {) { System.out.println (i + " " + i*i); System.out.println (i + " " + i*i);}} is equivalent tois equivalent to

• int i = 0int i = 0;;while (while (i < 7i < 7) {) { System.out.println (i + " " + i*i); System.out.println (i + " " + i*i); i++i++;;}}

• Typically we use:Typically we use:– forfor when we know in advance how many times the loop will when we know in advance how many times the loop will

executeexecute– whilewhile when something that happens in the loop determines when when something that happens in the loop determines when

the loop exitsthe loop exits– do..whiledo..while when we want a when we want a whilewhile loop that always does at least loop that always does at least

one iterationone iteration

Page 5: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

5

Loop patternsLoop patterns

• The next few slides present loop The next few slides present loop patternspatterns that are often useful, that are often useful, including:including:– Do N timesDo N times

• Do N times, changing per loop variableDo N times, changing per loop variable

– CountCount– Sum, minimum, maximumSum, minimum, maximum– Find-firstFind-first– Do-foreverDo-forever– Wait-untilWait-until

Page 6: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

6

Loop pattern: “do N Loop pattern: “do N times”times”

Example: Example: print print kk and and kk55 to the to the consolconsole e windowindow a w a given given numbenumber of r of times:times:

for (int k = 0; k < 5; k++) {for (int k = 0; k < 5; k++) { System.out.print(k + ″ System.out.print(k + ″ ″″);); System.out.println( Math.pow((double) k, 5.0) );System.out.println( Math.pow((double) k, 5.0) );

String s; int start, stop;String s; int start, stop;

s = JOptionPane.showInputDialog(″Start at?”)s = JOptionPane.showInputDialog(″Start at?”)start = Integer.parseInt(s);start = Integer.parseInt(s);

s = JOptionPane.showInputDialog(″Stop after?”)s = JOptionPane.showInputDialog(″Stop after?”)stop = Integer.parseInt(s);stop = Integer.parseInt(s);

for (int k = start; k <= stop; k++) {for (int k = start; k <= stop; k++) { System.out.print(k + ″ ″);System.out.print(k + ″ ″); System.out.println(System.out.println( Math.pow((double) k, 5.0)) Math.pow((double) k, 5.0))};};

Page 7: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

7

Loop pattern: “count”Loop pattern: “count”• Counts how many times a given character Counts how many times a given character

appears in a string:appears in a string:

public static int charCount(String s, char c) {public static int charCount(String s, char c) {int count = 0;int count = 0;

for (k = 0; k < s.length(); k++) {for (k = 0; k < s.length(); k++) {if (s.charAt(k) == c) {if (s.charAt(k) == c) {

++ count;++ count;}}

}}

return count;return count;}}

Page 8: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

8

Loop pattern: “sum”Loop pattern: “sum”• Sums the digits in a string of digits:Sums the digits in a string of digits:

public static int digitSum(String s) {public static int digitSum(String s) { int digit;int digit;

int sum = 0;int sum = 0;

for (k = 0; k < s.length(); k++) {for (k = 0; k < s.length(); k++) { digit = Integer.parseInt(s.substring(k, k+1));digit = Integer.parseInt(s.substring(k, k+1)); sum = sum + digit;sum = sum + digit; }}

return sum;return sum;}}

Page 9: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

9

Loop pattern: Loop pattern: “maximum”“maximum”• Finds the largest digit in a string of digits:Finds the largest digit in a string of digits:

public static int digitMax(String s) {public static int digitMax(String s) { int digit;int digit;

int max = Integer.parseInt(s.substring(0, 1));int max = Integer.parseInt(s.substring(0, 1));

for (k = 1; k < s.length(); k++) {for (k = 1; k < s.length(); k++) { digit = Integer.parseInt(s.substring(k, k+1));digit = Integer.parseInt(s.substring(k, k+1)); if (digit > max) {if (digit > max) { max = digit;max = digit; }} }}

return max;return max;}}

Page 10: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

10

Loop Pattern: “find-first”Loop Pattern: “find-first”

• Find the first place where a given character appears in Find the first place where a given character appears in a string.a string.Return -1 if the character does not appear.Return -1 if the character does not appear.

• public int findChar(String s, char c) {public int findChar(String s, char c) { int i = 0;int i = 0;

while (i < s.length()) {while (i < s.length()) { if (s.charAt(i) == c) {if (s.charAt(i) == c) { return i;return i; }} i++;i++; }} return -1;return -1; // Not found// Not found

}}

for (i=0; i < s.length(); i++) {for (i=0; i < s.length(); i++) {if (s.charAt(i) == c) {if (s.charAt(i) == c) {

return i;return i;}}

}}

Page 11: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

11

Loop Pattern: “do-Loop Pattern: “do-forever”forever”

• Our instruction-followers often Our instruction-followers often go “forever”:go “forever”:

while (true) {while (true) { System.out.println( System.out.println(""hihi"");); ... ... } }

for (; true;) {for (; true;) {System.out.println(System.out.println(""hihi");");

}}

Page 12: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

12

Loop pattern: “break in Loop pattern: “break in middle”middle”

while (true) {while (true) {

......

if (...) {if (...) {

break;break;

}}

......

}}

Page 13: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

13

How loops are combined How loops are combined with arrayswith arrays

• This is a preview of what you’ll really This is a preview of what you’ll really be studying next!be studying next!

• Example: Processing every member Example: Processing every member of an array:of an array:

for (int k = 0; k < maxDepth; k++) {for (int k = 0; k < maxDepth; k++) {

myArray[k] = 0; // Clear out whole myArray[k] = 0; // Clear out whole array!array!

}}

Page 14: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

14

How loops are combined How loops are combined with arrayswith arrays

• Preview, cntd:Preview, cntd:• Searching for things in an arraySearching for things in an arrayint k;int k;for (k = 0; k < maxDepth; k++) {for (k = 0; k < maxDepth; k++) {

if (myArray[k] = 0) {if (myArray[k] = 0) { break; // Find an empty slot in break; // Find an empty slot in array!array! }} }}

Page 15: Fundamentals of Software Development IProgramming patterns involving iteration1 Overview LoopsOverview Loops We’ll also see how loops are often combined

Fundamentals of Software Development I

Programming patterns involving iteration

15

How loops are combined How loops are combined with arrayswith arrays

• Preview, cntd:Preview, cntd:• Loops within loops for multi-dimensional Loops within loops for multi-dimensional

tablestables

for (int k = 0; k < maxDepth; k++) {for (int k = 0; k < maxDepth; k++) {

for (int m=0; m<maxWidth; m++) {for (int m=0; m<maxWidth; m++) {

myTable[k][m] = 0; // Clear out 2-dim myTable[k][m] = 0; // Clear out 2-dim table!table!

}}

}}