Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Iterative Structures --- LOOPS zYou can alter the sequential control of flow from 1 statement to the next by: yCalling a function yIterative Statements(loops)

Similar presentations


Presentation on theme: "1 Iterative Structures --- LOOPS zYou can alter the sequential control of flow from 1 statement to the next by: yCalling a function yIterative Statements(loops)"— Presentation transcript:

1 1 Iterative Structures --- LOOPS zYou can alter the sequential control of flow from 1 statement to the next by: yCalling a function yIterative Statements(loops) yConditional Expressions (if-else) ySwitch Statements

2 2 zThere are THREE iterative statements: xwhile x for x do-While

3 3 zLoops or iterative statements repeat a fragment of code x times or as long as A certain condition holds true. zAlgorithm – procedural steps required to solve a problem

4 4 zIterations are often used in conjunction with arrays to: y Iterate over each element of an array with minimal Code. y To get the largest value of an array, sort an array, get the sum of its values. zLoops are best with FILE Processing

5 5 zWhile Loop: while (condition) { Do stuff; }

6 6 zWhile Loop... yWhile conditions can be any arithmetic or logical expression yThe While loop contains statements in the body of the loop.

7 7 zWhile Loop… Requires: yInitializing of variables yTesting of the condition yIncrementing of the variable in the condition. yOtherwise a while loop can go into an infinite loop.

8 8 zWhile Loop… zThe while condition is tested BEFORE each pass through the loop zSo it is possible for the statements of the loop to never be executed.

9 9 zWhile Loop… zNEVER place a semi-colon after the while condition or the loop will not execute any code !!!

10 10 zWhile Loop… Examples zreturns the sum of all integers from 1 to n if n is >= 1 OTHERWISE the function will return 0 public int addupto (int n) { int sum = 0, i = 1;

11 11 while (i <= n) { sum += i; i++; } return sum; } What does “addupto” return if addupto(5);

12 12 static int whileLoop(int numTimes) { int result = 0, oneScore = 0, ctr = numTimes; String input;

13 13 while(ctr > 0) { input = JOptionPane.showInputDialog("En ter Score for Round: " + (numTimes - ctr + 1)); oneScore = Integer.parseInt(input); result += oneScore; ctr--; }

14 14 return result / numTimes; }

15 15 zFor Loop: for (initialization; condition; increment) { do stuff; }

16 16 zFor Loop... zShorthand version of the while loop. zCombines the initialization, conditional check and increment.

17 17 zFor Loop... zThe initialization is always hit at the start of the loop. zThe condition is tested before each pass zThe increment is executed at the end of each pass.

18 18 zFor Loop... for (i=0; i < n; i++) { do stuff; } yset i to 0, then as long as i is less than n, do stuff, after the code is executed, increment i by 1 and recheck the condition

19 19 zFor Loop... ythe initialization and increment statements can have several statements seperated by a comma. for (i=0, sum = 0; i < n; i++) //declare I & sum { sum += 1; }

20 20 zFor Loop... yThe for(;;) loop will repeat the statements in the loop until a break or return is used yfor(;;) loops are good for iterating through arrays, specifically if the array varies in length.

21 21 zExamples int sum = 0; for (int i=1; i < n; i++) { sum += 1; } return sum; zWhat is the value of sum after the loop terminates if n = 5 ?

22 22 zExamples 4 zThat is how many iterations occurred in that for loop

23 23 static int forLoop(int numTimes, int avg) { int result = 0; int baseScore = 71; for(int sub = 0; sub < numTimes; sub++) { result += (avg - baseScore); } return result; }

24 24 zDo - While Loop: Do { dostuff; } while (condition); ythe body, dostuff;, executes as long as the condition remains true

25 25 zDo - While Loop … Example int sum = 0, i=1; do { sum += 1; i++; } while( i < n); return sum; // if n = 5, 4 is // returned !!!

26 26 zBreak and Continue: yBreak and continue are reserved words yCan only be used within the body of a loop (break can be used in switch statement)

27 27 zBreak and Continue: yBreak – immediately break out of the loop and execute 1 st stmt after the loop yContinue – skip the rest of the iteration and start at the top of the loop yBoth need to be put inside an if statement

28 28 zBreak and Continue: yReturn – breaks out of loop and function (multiple returns in a function is not good coding style)

29 29 zExamples int b = 10; for (int a = 0; a < b; a++) { if (a * b > 85) { break; } yfor loop ends when a*b exceeds 85

30 30 int b = 10; for (int a = 0; a < b; a++) { if (a * b == 80) { continue; } yfor loop code bypassed for iteration where a*b = 80 BUT THE FOR LOOP CONTINUES

31 31 zBreak and Continue: zContinue statements in a while loop can be a problem if it prevents the increment of the iterative variable zAs seen in the following loop (infinate loop)

32 32 zBreak and Continue: int p = 2; while (p <= n) { if (!IsPrime(p)) continue; // for n >= 4 p will never sum += p; // get incremented after p++; } // prime #3 is encountered

33 33 zINVARIANTS AND VARIANT ASSERTIONS zAssertion - a Logical Statement that is either TRUE or FALSE zIn a program, an assertion made at a particular code point expresses a logical condition that should be TRUE if the program is working properly

34 34 zINVARIANTS AND VARIANT ASSERTIONS zAssertion zFor example, before a function is called or a loop is executed, the program asserts to be true that a file exists and is opened for input zin the String: assert(s != null); // string is not // null

35 35 zINVARIANTS AND VARIANT ASSERTIONS zloop invariant - A statement that is TRUE throughout ALL iterations of the loop (An assertion that is true for this iterative part of the program)

36 36 zINVARIANTS AND VARIANT ASSERTIONS zexample, in the for loop int sum = 0; for(int a=1; a <= num; a++) { if (a % 2==1) sum++; }

37 37 zINVARIANTS AND VARIANT ASSERTIONS za loop invariant assertion could state that: sum is a non negative number and will equal the count of odd numbers from 1 to “num”

38 38 zNested Iterations: zNested for loops to process all elements of a two dimensional array (we will discuss arrays In a few lectures)

39 39 zExample: int rows = 10, cols = 8; int grid[][] = new int[rows][cols]; for(row = 0; row < rows; row++) { for(col = 0; col < cols; cols++) { grid[row][col] = 0; }

40 40 zStatic functions vs Classes: zAs we have seen in previous lectures, you can write static functions in your java application

41 41 zStatic functions vs Classes: zYou can also, if your program lends itself to the creation of a self contained entity (math calculations for example) that can also be used in another application, create a CLASS to handle the processing.

42 42 zStatic functions vs Classes: zWith a class, you can write the class in the same file as SPVM / wrapper class OR zYou can write the class in a new file and IMPORT the class in your wrapper program

43 43 zStatic functions vs Classes: z Writing static functions zWriting classes (in same file and in different files)

44 44 zStatic functions vs Classes: zLets look at these 2 methods with the following programs (already seen in previous lectures): modVars.java weekday.java

45 45 zTPS (2): 1.Write a Static Function called getAverageRound That: accepts the “par” score processes “x” scores of a round of golf maintains a running average displays the gross over/under par returns the overall average score

46 46 zTPS(2): For Example, suppose the PAR score for a round of golf was 72, and there were 5 golfers who played and represented their scores as follows: 71, 73, 68, 81, 66 Overall Average = 71.8 Golfers gross result was 1 under par

47 47 TPS(3): Write the following 2 Methods: 1.using a loop, display the square root of the following numbers: 25, 20, 15, 10 & 5 2.using a loop, display the FIRST value “n” for which 1 + 2 + 3 + n isGREATER than 1 million

48 48 zProjects: Update to Fast Food Recipricol Squares Factorial Add Cubes Heads / Tails Fortune Cookie Student Average Fibonacci Signs Prime Numbers Guess the Number Black Jack

49 49 TEST IS THE DAY AFTER THE PROJECT IS DUE !!!


Download ppt "1 Iterative Structures --- LOOPS zYou can alter the sequential control of flow from 1 statement to the next by: yCalling a function yIterative Statements(loops)"

Similar presentations


Ads by Google