View
223
Download
0
Category
Preview:
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
Citation preview
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
2
There are THREE iterative statements:
while for do-While
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
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
5
While Loop:
while (condition){ Do stuff;}
6
While Loop...
While conditions can be any arithmetic or logical expression
The While loop contains statements in the body of the loop.
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.
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.
9
While Loop…
NEVER place a semi-colon after the while condition or the loop will not execute any code !!!
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;
11
while (i <= n){ sum += i; i++;}
return sum; }
What does “addupto” return if addupto(5);
12
static int whileLoop(int numTimes){
int result = 0, oneScore = 0, ctr = numTimes;String input;
13
while(ctr > 0){
input = JOptionPane.showInputDialog("Enter Score for Round: " + (numTimes - ctr + 1));
oneScore = Integer.parseInt(input);result += oneScore;ctr--;}
14
return result / numTimes;}
15
For Loop: for (initialization; condition;
increment){ do stuff;}
16
For Loop... Shorthand version of the
while loop.
Combines the initialization, conditional check and increment.
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.
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
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;}
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.
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 ?
22
Examples
4That is how many iterations
occurred in that for loop
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
Do - While Loop:
Do {dostuff;
} while (condition);
the body, dostuff; , executes as long as the condition remains true
25
Do - While Loop … Exampleint sum = 0, i=1; do {
sum += 1; i++; }
while( i < n);
return sum; // if n = 5, 4 is // returned !!!
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)
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
28
Break and Continue:
Return – breaks out of loop and function (multiple returns in a function is not good coding style)
29
Examplesint b = 10;for (int a = 0; a < b; a++) { if (a * b > 85)
{ break;
} } for loop ends when a*b exceeds 85
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
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)
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
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
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
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)
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++;
}
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”
38
Nested Iterations:
Nested for loops to process all elements of a two dimensional array (we will discuss arraysIn a few lectures)
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;}}
40
Static functions vs Classes:
As we have seen in previous lectures, you can write static functions in your java application
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.
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
43
Static functions vs Classes:
Writing static functions
Writing classes (in same file and
in different files)
44
Static functions vs Classes:
Lets look at these 2 methods with the following programs (already seen in previous lectures):
modVars.javaweekday.java
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
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
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
48
Projects:Update to Fast FoodRecipricol SquaresFactorialAdd CubesHeads / TailsFortune CookieStudent AverageFibonacciSignsPrime NumbersGuess the NumberBlack Jack
49
TEST IS THE DAY AFTER THE PROJECT IS
DUE !!!
Recommended