320 likes | 474 Views
CSE 131 Computer Science 1 Module 3: Iteration. Quiz 1 Statistics Basic concepts While loop and for loop Loop invariants and correctness Recursion and iteration. Vinoo Ganesh. Quiz 1 Statistics. 90-100: 235 80-89: 26 70-79: 7 60-69: 2 50-59: 1 40-49: 2 30-39: 0 20-29: 0 10-19: 0 0-9: 12.
E N D
CSE 131 Computer Science 1Module 3: Iteration Quiz 1 Statistics Basic concepts While loop and for loop Loop invariants and correctness Recursion and iteration Vinoo Ganesh
Quiz 1 Statistics 90-100: 23580-89: 2670-79: 760-69: 250-59: 140-49: 230-39: 020-29: 010-19: 00-9: 12 • Max: 100 • Min: 0 • Median: 100 • Standard Deviation: 20.82 • Average: 91.77 • If you didn’t do as well as you had hoped, consider changing your study methods or consider joining a recitation
Recitations • Sign-ups are open again and will close on Tuesday Sept 20th, at 11:59 pm • You can sign up here: http://tinyurl.com/recitationsignup • Your leader will contact you THIS WEEK with more information
Note about JUnit Test • You must have an “@Test” above the method containing your assertEquals() in order for that test to be run!
Bit about recursion • Demo searching “recursion” on Google
Exercise • Take out a pen and a piece of paper and do the following exercise: • Calculate the sum of 1+2+3+4+…+30=
Who thought that was fun? • Everyone raising their hand, stop lying.
Iteration • Definition of “iterate”: • it·er·ate/ˈitəˌrāt/ • Verb: Perform or utter repeatedly. • Definition of “–tion” • tion • Suffix: Forming nouns of action, condition, etc., such as completion, relation. • In Comp Sci, we do this with things called loops
Iteration • Programs frequently involve repeating the same steps over-and-over again (usually with small variations) • Repetitive program segments can be implemented using loops • Loops typically include the following components(usually, but not always in this order) • initialization • test for termination condition • repeated set of actions • modification to “loop variable” • Correctness of a loop is based on loop invariant • a statement that is true after each loop iteration that can be used to show the loop produces desired result
Doing the exercise with a loop int sum=0; int k= 1; while(k<30){ sum=sum+k; } return sum;
While Loop • While Loop Structure: <initializing statement, ex. assign a variable a value> while(<condition>){ <do something until condition is met> <update so condition can eventually be met> } • Example: intnumber = 1; // initialize while(number <= 10){ // loop boundary conditionSystem.out.println(number); number++; // increment/decrement}
Computer Science Hint • If you’re ever overwhelmed by code, take a step back and read the code out loud while imagining that you are someone who just barely knows how to speak English • Read it out, and then try to make sense of it.
Computer Science Hint Continued. intnumber = 1; //means I probably have an //integer with the value of 1 while(number <= 10){ //while this number is //less than 10 condition Etc…
A little about the termination condition • The loop boundary/termination condition is the boolean expression that evaluates as true or false. We must consider two aspects as we devise the loop boundary. • It must eventually become false, which allows the loop to exit. • It must be related to the task of the loop. When the task is done, the loop boundary must become false.
What happens if the termination statement is never true? • What will be the output of the following: while(false){ System.out.println(“hi”); } • NOTHING! It will never execute!
For Loops • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. • A for loop is useful when you know how many times a task is to be repeated. for(<init>; <condition>; <update>) { <body> } <rest of program>
Updating a variable • If you have int a = 5; you can modify the value of a in many ways. • Add 1: • a=a+1; • a++; • ++a; • Subtract 1: • a=a-1; • a--; • --a; These are all the same!! These are all the same!!
For Loops vs. While Loops • Essentially the same. For the most part, what you can write with a while loop, you can write with a for loop While Loop: inta=3; // this is the <init> while(a>=1) // the parameter is the<condition> { System.out.println(“hi”); //this is the <body> a--; // this is the <update>, same as a=a-1; } For Loop: for(int a=3; a>=1; a--)//this line contains init, cond., update { System.out.println(“hi”); //this line has the <body> }
Writing a loop to a popular song! Baby baby baby ohLike baby baby baby noLike baby baby baby oh
Let’s write it! • String lyrics=“”; • intnumOfRuns=0; • booleansongOver=false; • while(songOver==false){ • for(inta=0; a< 3; a++){ • lyrics=lyrics+” baby ”; • } • if(numOfRuns==0){ • lyrics=lyrics+”oh /n Like”;} • if(numOfRuns==1){ • lyrics=lyrics+”no /n Like”;} • if(numOfRuns==2){ • lyrics=lyrics+”oh”; • songOver=true; • } • numOfRuns++; • } baby baby baby ohLike baby baby baby noLike baby baby baby oh http://ideone.com/1FuWH
Nested Loops • As you saw in the last example: while(songOver==false){ for(int a=0; a< 3; a++){ } } • You can put loops inside of other loops! This is called “nesting”
Where is nesting helpful? Steps: • Lets say you wanted to print this: ******************************** for(introw = 1; row <= 4; row++){for(intcol=1; col <= 8; col++){System.out.print("*"); }System.out.println( );} We need to initialize a row variable 2. We need to initialize a column variable 3. We want to iterate through until there are 8 columns and print a star on each row 4. We want to iterate through until there are 4 columns
Talking is great… but let’s do another demo • Example: • Find the list of numbers divisible by 2 from 1 to 1000 • http://ideone.com/
Loop Invariants • A condition that is true at the start of every iteration • so, true after initialization • true on loop exit • May be untrue temporarily during an iteration • but truth must be restored by the end of the loop • Useful for thinking about correctness • because the invariant, together with the termination condition of the loop implies the desired result • steps in proving correctness • show that invariant is true after initialization • show that loop maintains the truth of the invariant • show that invariant and termination condition implies correctness
Recursion vs. Iteration • Recursive algorithms are often most straight-forward way to solve a problem • frequently, based directly on a true mathematical statement • makes it relatively easy to get the program right • but, can lead to inefficient programs • Iterative programs are often more efficient • less likely to be involve significant re-computation • avoids the overhead of method call-return • but reasoning about correctness can be more difficult • Both styles have important roles • computations that have natural iterative structure are best solved using loops • problems involving search in a complex data structure are often best implemented using recursion
One Last Hint • Use the API!! Contains troves of useful information!