CSE 114 Computer Science I Iteration Cape Breton, Nova Scotia
What is Iteration? Repeating a set of instructions a specified number of times or until a specific result is achieved How do we repeat steps? Imagine 3 instructions A, B, & C Instruction C can be jump A, meaning go back to A Iteration might result in: Execute A Execute B Execute C Execute A
Why use iteration? To make our code more practical and efficient To make our code more flexible and dynamic
For Example How would we write code to print N! (factorial), where N is a number entered by the user? Without iteration (or recursion) this would be impractical! We do not know N, when we are about to write the program.
Is this practical? Without iteration or recursion: System.out.print("Enter N: "); int N = Keyboard.readInt(); int factorial = 1; if ((N == 1) (N == 0)) factorial = 1; else if (N == 2) factorial = 2 * 1; else if (N == 3) factorial = 3 * 2 * 1; else if (N == 4) factorial = 4 * 3 * 2 * 1; else if (N == 5) factorial = 5 * 4 * 3 * 2 * 1; System.out.println(factorial); Inefficient coding!
import java.util.scanner; public class FactorialPrinter public static void main(string[] args) Scanner input = new Scanner(System.in); System.out.print("Enter N: "); int N = input.readint(); int factorial = calculatefactorial(n); System.out.println(factorial); return type Using Iteration and Methods Method argument type and name public static int calculatefactorial(int n) int count = n; int fact = 1; while (count > 0) fact *= count--; return fact; return value Helper method
Can Anyone guess what 1000! is? 4023872600770937735437024339230039857193748642107146325437999104299385123986290205920442084869694048004799886 1019719605863166687299480855890132382966994459099742450408707375991882362772718873251977950595099527612087497 5462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323 9584630755574091142624174743493475534286465766116677973966688202912073791438537195882498081268678383745597317 4613608537953452422158659320192809087829730843139284440328123155861103697680135730421616874760967587134831202 5478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810 2130927612448963599287051149649754199093422215668325720808213331861168115536158365469840467089756029009505376 1647584772842188967964624494516076535340819890138544248798495995331910172335555660213945039973628075013783761 5307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892 1879602238389714760885062768629671466746975629112340824392081601537808898939645182632436716167621791689097799 1190375403127462228998800519544441428201218736174599264295658174662830295557029902432415318161721046583203678 6906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958 6526822728070757813918581788896522081643483448259932660433676601769996128318607883861502794659551311565520360 9398818061213855860030143569452722420634463179746059468257310379008402443243846565724501440282188525247093519 0620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814 9001407673104466402598994902222217659043399018860185665264850617997023561938970178600408118897299183110211712 2984590164192106888438712185564612496079872290851929681937238864261483965738229112312502418664935314397013742 8531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602 7898643211390835062170950025973898635542771967428222487575867657523442202075736305694988250879689281627538488 6339690995982628095612145099487170124451646126037902930912088908694202851064018215439945715680594187274899809 4254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105 9339838357779394109700277534720000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000 Impossible to calculate using Java s primitive data types, instead we would have to use the BigInteger class double type can estimate up until 170! (7.257415615308004 E306)
Any exceptions? All programs need iteration one and done programs Why do they all need iteration? because the start up, then wait for the user to act Most programs work as follows: 1. Initialize variables 2. Present options to user 3. Wait for user input 4. Respond to user input 5. Go back to step 2
GUIs and Iteration Think of a GUI. How does it work? 1. Draw the GUI 2. Check for input from user 3. Respond to user input, if any 4. Go back to Step 1
Java and iteration We have 3 types of iterative statements a while loop a do while loop a for loop All 3 can be used to do similar things Which one should you use? a matter of individual preference/convenience
The while Statement Syntax Diagram: while ( boolean Expr ) Statement Statement Flowchart: false true boolean Expr Statement(s) Loop Condition Loop Body
Bracketing is again important Use either: while (boolean expression) statement; Or: Be careful NOT to put a semicolon, ;, here while (boolean expression) statement; statement;
while statement example What does this method do? public static String whatdoesthisdo(int x, char c) // null character "" String result = ""; while (x > 0) result = result + c; x--; return result; What do we get if we call: String s; s = whatdoesthisdo(5,'a'); System.out.println(s); s = whatdoesthisdo(0,'a'); System.out.println(s); AAAAA
while statement example 2 What does this method do? public static String whatdoesthisdo2(int x, char c) String result = ""; while (x > 0) result = result + c; x--; c++; return result; What do we get if we call: String s; s = whatdoesthisdo2(5, 'A'); System.out.println(s); ABCDE
while statement example 3 What does this method do? public static String whatdoesthisdo3(int x, char c) String result = ""; while (x > 0) result = c + result; x--; c++; return result; What do we get if we call: String s; s = whatdoesthisdo3(5, 'A'); System.out.println(s); EDCBA
Using a flag A flag is a boolean loop control boolean flag = true; How does it work? flag used as loop condition inside the loop, test for ending condition when condition is reached, turn flag off once turned off, loop ends
flag example public static int factorial(int N) boolean moreworkflag = true; int factorial = 1; while (moreworkflag) factorial *= N; N--; if (N == 1) moreworkflag = false; return factorial; What do we get if we call: int fact; fact = factorial(5); System.out.println(fact); 120
The do-while Statement Syntax Diagram: do Statement Statements while ( boolean Expr ) ; Flowchart: Loop Body Statement(s) Loop Condition boolean Expr false true
Bracketing is again important Use either: do statement; while (boolean expression); Or: do You MUST put a semicolon, ;, here statement; statement; while (boolean expression); NOTE: though they can be used to do similar operations, while statements and do-while statements are different Java constructs.
do while statement example What does this method do? public static String whatdoesthisdowhiledo( String result = ""; do result += c; x--; while (x > 0); return result; int x, char c) What do we get if we call: String s; s = whatdoesthisdowhiledo(5,'a'); System.out.println(s); s = whatdoesthisdowhiledo(0,'a'); System.out.println(s); AAAAA A
How could we fix this? public static String whatdoesthisdowhiledo String result = ""; if (x > 0) do result += c; x--; while (x > 0); return result; (int x, char c) Now what s the output? String s; s = whatdoesthisdowhiledo(5,'a'); System.out.println(s); s = whatdoesthisdowhiledo(0,'a'); System.out.println(s); AAAAA
Why use do while? So what s the point? For when you have a loop body that must execute at least once Example: a program menu
Console Program Menu Example String selection; PrintStream out = System.out; Scanner in = new Scanner(System.in); int counter = 0; do out.println("choose a Menu Option:"); out.println("p) Print Counter"); out.println("q) Quit"); out.print("enter: "); selection = in.nextline(); if (selection.touppercase().equals("p")) out.println("counter: " + counter++); while(!selection.touppercase().equals("q")); out.println("goodbye!");
Choose a Menu Option: P) Print Counter Q) Quit ENTER: P Counter: 0 Choose a Menu Option: P) Print Counter Q) Quit ENTER: A Choose a Menu Option: P) Print Counter Q) Quit ENTER: P Counter: 1 Choose a Menu Option: P) Print Counter Q) Quit ENTER: Q An Example Session
The for Statement Syntax Diagram: for ( Init. Operation ; boolean Expr ; Update Operation ) Statement Statement
Flowchart: The for Statement Initialization false Boolean Expr Update true Statement(s)
A for loop example public static int indexof(string s, char c) for (int i = 0; i < s.length(); i++) if (s.charat(i) == c) return i; return -1; 3-1 2 What s the output? String word = "London Calling"; int index = indexof(word, 'd'); System.out.println(index); index = indexof(word, 'x'); System.out.println(index); index = indexof(word, 'n'); System.out.println(index);
for loops and counting for loops are popular for counting loops through the indices of a string through the indices of an array (later) through iterations of an algorithm Good for algorithms that require a known number of iterations counter-controlled loops
Do you understand the order of operations? for (int i = 0; i < 10; i++) System.out.print(i); 1) int i = 0; 2) i < 10; 3) System.out.print(i); 4) i++; 5) i < 10; 6) System.out.print(i); 7) i++; 8) i < 10; 9) System.out.print(i); 10) i++; 11) i is 0 i is 1 i is 2 i is 3
Examples of for Statements int sum = 0; for (int i=1; i<=4; i++) sum = sum + i; sum i 0 1 1 2 3 3 6 4 10 5 int sum = 0; for (int j=1; j<=4; j++) sum = sum + j; j++; sum j 0 1 1 3 4 5 Be careful not to double the update of your counting variable
Examples of for Statements int product = 1; for (int i=1; i<4; i+=1) product *= i; Can be used equivalently in many cases int product = 1; for (int j = 1; j<= 3; j+=1) product *= j; product i 1 1 1 2 2 3 6 4 product j 1 1 1 2 2 3 6 4
Equivalence of Loops for ( INIT ; BOOL_EXPR; UPDATE ) LOOP_BODY INIT if ( BOOL_EXPR ) INIT while ( BOOL_EXPR ) LOOP_BODY UPDATE do LOOP_BODY UPDATE while ( BOOL_EXPR );
Are these loops equivalent? int sum = 0, count = 0; while (count < x) sum += y; count++; System.out.println("sum is " + sum); int sum = 0, count = 0; for (count = 0; count < x; count++) sum += y; System.out.println("sum is " + sum); int sum = 0, count = 0; do sum += y; count++; while (count < x); System.out.println("sum is " + sum); Test using: x = 5, y = 3 OUTPUT: Sum is 15 Sum is 15 Sum is 15 x = 0, y = 3 OUTPUT: Sum is 0 Sum is 0 Sum is 3 Not Equivalent!
Syntax Diagram: WATCH OUT! ; The empty statement if (score > 21); System.out.println("Bust! You Lose"); if (score > 21 ) System.out.println("Bust! You Lose"); else; System.out.println("Hit or Stay?"); ; This is a valid line of code that does nothing, but can create unexpected problems.
The empty statement (cont d) int sum = 0; for (int i = 1; i <= 4; i++); sum = sum + i; int sum = 0, i = 1; while (i <= 4); Infinite loop! sum = sum + i; i = i + 1; Compiler Error
Nested Loops for (int i = 1; i <= 10; i++) for (int j = 1; j <= 10; j++) int product = i*j; System.out.print(product + ); System.out.print( \n ); 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
Beware Improper Nesting int sum = 0, count = 0; if (x > 0) do sum += y; count++; while (count < x); System.out.println(sum); IS NOT int sum = 0, count = 0; if (x > 0) do sum += y; count++; while (count < x); System.out.println(sum); This loop is regarded as a single statement
Advice: Align your brackets Indenting properly is really important: if (flag) if (flag) if (y > 0) if (y > 0) x = 0; x = 0; GOOD BAD
Local Variables and Blocks A block (a compound statement) is the set of statements between a pair of matching braces (curly brackets) A variable declared inside a block is known only inside that block it is local to the block, therefore it is called a local variable when the block finishes executing, local variables disappear references to it outside the block cause a compiler error
Local Variables and Blocks (cont d) Some programming languages (e.g., C and C++) allow the variable name to be reused outside the local block it is confusing and not recommended, nevertheless, it is allowed However, a variable name in Java can be declared only once for a method although the variable does not exist outside the block, other blocks in the same method cannot reuse the variable's name
When and Where to Declare Variables Declaring variables outside all blocks but within the method definition makes them available within all the blocks Good programming Practice: declare variables just before you use them initialize variables when you declare them do not declare variables inside loops it takes time during execution to create and destroy variables, so it is better to do it just once for loops) OK to declare loop counters in the Init field of for loops, e.g. for(int i=0; i < 10; i++) the Init field executes only once, when the for loop is first entered
Java Comments Important for you and for others wishing to use your code. Always specify author, version. For classes, explain what the class is and how it is to be used. For methods, explain what it does. For programs, explain the input and output. 2 ways to add comments // Everything after the double slashes is ignored /* Everything inside the slash star is ignored */