1 iterative structures --- loops zyou can alter the sequential control of flow from 1 statement to...

49
1 Iterative Structures --- LOOPS You can alter the sequential control of flow from 1 statement to the next by: Calling a function Iterative Statements(loops) Conditional Expressions (if- else) Switch Statements

Upload: berniece-scott

Post on 18-Jan-2018

223 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 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)

1

Iterative Structures --- LOOPSYou can alter the sequential control

of flow from 1 statement to the next by: Calling a function Iterative Statements(loops) Conditional Expressions (if-else) Switch Statements

Page 2: 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)

2

There are THREE iterative statements:

while for do-While

Page 3: 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)

3

Loops or iterative statements repeat a fragment of code x times or as long asA certain condition holds true.

Algorithm – procedural steps required to solve a problem

Page 4: 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)

4

Iterations are often used in conjunction with arrays to:

Iterate over each element of an array with minimal Code.

To get the largest value of an array, sort an array, get the sum of its values.

Loops are best with FILE Processing

Page 5: 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)

5

While Loop:

while (condition){ Do stuff;}

Page 6: 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)

6

While Loop...

While conditions can be any arithmetic or logical expression

The While loop contains statements in the body of the loop.

Page 7: 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)

7

While Loop…Requires: Initializing of variables Testing of the condition Incrementing of the variable in the condition.

Otherwise a while loop can go into an infinite loop.

Page 8: 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)

8

While Loop…

The while condition is tested BEFORE each pass through the loop

So it is possible for the statements of the loop to never be executed.

Page 9: 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)

9

While Loop…

NEVER place a semi-colon after the while condition or the loop will not execute any code !!!

Page 10: 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)

10

While Loop… Examples

returns 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;

Page 11: 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)

11

while (i <= n){ sum += i; i++;}

return sum; }

What does “addupto” return if addupto(5);

Page 12: 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)

12

static int whileLoop(int numTimes){

int result = 0, oneScore = 0, ctr = numTimes;String input;

Page 13: 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)

13

while(ctr > 0){

input = JOptionPane.showInputDialog("Enter Score for Round: " + (numTimes - ctr + 1));

oneScore = Integer.parseInt(input);result += oneScore;ctr--;}

Page 14: 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)

14

return result / numTimes;}

Page 15: 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)

15

For Loop: for (initialization; condition;

increment){ do stuff;}

Page 16: 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)

16

For Loop... Shorthand version of the

while loop.

Combines the initialization, conditional check and increment.

Page 17: 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)

17

For Loop... The initialization is always hit

at the start of the loop. The condition is tested before

each passThe increment is executed at

the end of each pass.

Page 18: 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)

18

For Loop... for (i=0; i < n; i++)

{ do stuff;

} set 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

Page 19: 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)

19

For Loop... the 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;}

Page 20: 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)

20

For Loop... The for(;;) loop will repeat the statements in the loop until a break or return is used

for(;;) loops are good for iterating through arrays, specifically if the array varies in length.

Page 21: 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)

21

Examplesint sum = 0; for (int i=1; i < n; i++)

{ sum += 1;}

return sum;What is the value of sum after

the loop terminates if n = 5 ?

Page 22: 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)

22

Examples

4That is how many iterations

occurred in that for loop

Page 23: 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)

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

Page 24: 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)

24

Do - While Loop:

Do {dostuff;

} while (condition);

the body, dostuff; , executes as long as the condition remains true

Page 25: 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)

25

Do - While Loop … Exampleint sum = 0, i=1; do {

sum += 1; i++; }

while( i < n);

return sum; // if n = 5, 4 is // returned !!!

Page 26: 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)

26

Break and Continue:

Break and continue are reserved words

Can only be used within the body of a loop (break can be used in switch statement)

Page 27: 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)

27

Break and Continue:

Break – immediately break out of the loop and execute 1st stmt after the loop

Continue – skip the rest of the iteration and start at the top of the loop

Both need to be put inside an if statement

Page 28: 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)

28

Break and Continue:

Return – breaks out of loop and function (multiple returns in a function is not good coding style)

Page 29: 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)

29

Examplesint b = 10;for (int a = 0; a < b; a++) { if (a * b > 85)

{ break;

} } for loop ends when a*b exceeds 85

Page 30: 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)

30

int b = 10;for (int a = 0; a < b; a++) { if (a * b == 80)

{ continue;

} } for loop code bypassed for iteration where a*b = 80 BUT THE FOR LOOP CONTINUES

Page 31: 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)

31

Break and Continue:

Continue statements in a while loop can be a problem if it prevents the increment of the iterative variable

As seen in the following loop (infinate loop)

Page 32: 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)

32

Break and Continue:

int p = 2;while (p <= n) {

if (!IsPrime(p))continue; // for n >= 4 p will

neversum += p; // get incremented afterp++; } // prime #3 is encountered

Page 33: 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)

33

INVARIANTS AND VARIANT ASSERTIONS

Assertion - a Logical Statement that is either TRUE or FALSE

In a program, an assertion made at a particular code point expresses a logical condition that should be TRUE if the program is working properly

Page 34: 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)

34

INVARIANTS AND VARIANT ASSERTIONS

AssertionFor 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

in the String:assert(s != null); // string is not // null

Page 35: 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)

35

INVARIANTS AND VARIANT ASSERTIONS

loop invariant - A statement that is TRUE throughout ALL iterations of the loop (An assertion that is true for this iterative part of the program)

Page 36: 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)

36

INVARIANTS AND VARIANT ASSERTIONS

example, in the for loop int sum = 0;for(int a=1; a <= num; a++){

if (a % 2==1)sum++;

}

Page 37: 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)

37

INVARIANTS AND VARIANT ASSERTIONS

a loop invariant assertion could state that:

sum is a non negative number and will equal the count of odd numbers from 1 to “num”

Page 38: 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)

38

Nested Iterations:

Nested for loops to process all elements of a two dimensional array (we will discuss arraysIn a few lectures)

Page 39: 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)

39

Example: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;}}

Page 40: 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)

40

Static functions vs Classes:

As we have seen in previous lectures, you can write static functions in your java application

Page 41: 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)

41

Static functions vs Classes:

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

Page 42: 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)

42

Static functions vs Classes:

With a class, you can write the class in the same file as SPVM / wrapper class OR

You can write the class in a new file and IMPORT the class in your wrapper program

Page 43: 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)

43

Static functions vs Classes:

Writing static functions

Writing classes (in same file and

in different files)

Page 44: 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)

44

Static functions vs Classes:

Lets look at these 2 methods with the following programs (already seen in previous lectures):

modVars.javaweekday.java

Page 45: 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)

45

TPS (2):

1. Write a Static Function called getAverageRound That:accepts the “par” scoreprocesses “x” scores of a roundof golfmaintains a running average displays the gross over/under parreturns the overall average score

Page 46: 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)

46

TPS(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.8Golfers gross result was 1 under par

Page 47: 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)

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 is GREATER than 1 million

Page 48: 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)

48

Projects:Update to Fast FoodRecipricol SquaresFactorialAdd CubesHeads / TailsFortune CookieStudent AverageFibonacciSignsPrime NumbersGuess the NumberBlack Jack

Page 49: 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)

49

TEST IS THE DAY AFTER THE PROJECT IS

DUE !!!