Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1
Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2
Motivation Name banner: user enters name and repeats. Program prints. E.g. for Mavs and 3, it will print: Go Mavs! Go Mavs! Go Mavs! ** Check if all characters in a string (given as name) are English letters. Variation: count how many are English letters or spaces. String printing: Reverse to simulate a mirroring effect. Stacking effect (vertical print) in Microsoft Word. One letter per line Problem solving: decouple components: index generation ** Repeat animation for a certain number of times, without hardcoding 3 times (like in hw we hardcoded 3 circles). Guess a number or recognize a password. M o t i v a t i o n Computer player in a guessing game: the computer will have to guess. Print a weekly/monthly schedule (or To Do list). May give what day of week the 1 st of the month is to show day names (e.g. Feb 1 st 2018 was a Thursday) M o t i v a t i o n 3
Loops 2 kinds of repetition: until something happens or For a specific number of times (known when the repetition starts) Loop statements implement repetition. There are 3 types of loops in Java: while loops Good for cases when waiting for an event to happen. E.g. Enter numbers until value 0 is entered convenient for getting user input for arrays. Ask for the password until a matching one was entered. NOTE: it will not stop as soon as the even happened, but when the condition is checked. for loops Good when we need to repeat a set of actions a certain number of times. E.g.: Examine every character in a string (to print, or see if English letter or to count vowels) Print the first 10 prime numbers. Compute homework average grade for each student (in a collection). Can be set-up to behave as while loops as well: stop when an event happens. do while loops - NOT COVERED (and not needed) break & continue - covered, but not recommended. Types of problems 4
Practice: basic iteration Algorithm and problem solving Loop control: infinite loop and loop that never executes Create a program that iterates as long as the user wants to continue (asked after each iteration) 10 times N times (N entered by the user) Generate numbers 1,2,., N (e.g. model a machine giving line tickets like at the DMV office) N, N-1, 3,2,1 (e.g. model a count-down) Even numbers: Generate and print even numbers (e.g. part of a math application for kids) Generate all numbers, but print only the even ones Generate all numbers, take different action based on a property Draw the flow of control diagram. Be aware of the sequence of numbers generated by each branch. Print N stars Name banner (adjusts to name length, vertical or horizontal orientation). Strings: Print string letters Print string letters with a certain property Check that all symbols are English letters. 5
Problem type: Cumulative operations Algorithm, typical setup (counter, accumulator) Separate the process of generating the values from the process of computing the cumulative operation. Practice: compute the following values: Sum: 1 + 2 + + N N!: 1 * 2 * 3 * 4 *... * N sum of even and product of odd numbers. 6
Deeper understanding Do you see what the general problem corresponding to each of the specific examples above? What general problems have we seen? 7
Problem type: property in a collection Check if a collection (of values/objects) has a certain property. Example: The user enters x and y, with x < y. Print True if any (at least one) number in that range (including x and y) is divisible by 13. Print False otherwise (note: this is the difficult part!). Extra: if x > y, swap their values. 8
More practice: combine problems Keep asking for user input (an integer) until the number they enter would be a leap year. 9
The for loop 10
for loop The for loop has the loop control instructions at the top. Syntax: for (init; condition; update){ line 1 line 2 line n } body or suite of the for loop header 11
Example: for loop over a string Draw flowchart Variable i is called a counter. Initialize the counter. int i; Condition involving the counter. String s = "Hello there!"; for(i=0; i<s.length(); i=i+1){ char c = s.charat(i); Update the counter. System.out.printf("i=%d, letter: %c\n", i, c); System.out.println("---"); } 12
Example: for loop over a string What will this code do? Trace the value of the variables throughout the program execution. i c int i; String s = "Hello there!"; for(i=0; i<s.length(); i=i+1){ char c = s.charat(i); System.out.printf("i=%d, letter: %c%n", i, c); System.out.println("---"); } 13
Loop - variations Loop mechanism: as long as condition is true, repeat body of the loop. Examples with counter: Counter goes up in increments: +1, +5, *2 Is +variable allowed? E.g. for(j=0; j<n;j=j+x) Counter goes down: -1, -3, /4 Example without counter: E.g. Until user enters specific number or string, until certain random number is produced, Variations in syntax : Missing init Missing update Condition can also be missing, but we are NOT DOING THAT. Issues/bugs Infinite loop not marking the body of the loop, Semicolon after header: for(.); Same issue as with: if ( ); 14
Example 2: for loop with a string 1. Print string characters in reversed order. 2. Count the number of vowels in text entered by the user. 3. Check is all characters in a string are English letters. 4. Print banners (with any name, not just the one from the example) ************* * alex stef * ************* ************* * alex stef * ************* ***** * a * * l * * e * * x * * * * s * * t * * e * * f * ***** ***** * a * * l * * e * * x * * * * s * * t * * e * * f * ***** 15
Towards writing a password program We want to write a program that does this: Has a hardcoded string representing a saved password. Asks the user to enter their password until there is a match. First, let s solve the simpler version: get only one string from the user (they have only one chance to enter their password) Pseudocode Flowchart Code Next: solve the original problem 16
while loop 17
while loop execution while (boolean_expression){ line 1 line 2 line n } first line after loop body of the while loop. Loop execution: Step 1: evaluate boolean_expression. header of the while loop. Step 2: If boolean_expression is false, go to the first line after the loop. Step 3: If boolean_expression is true, execute the body of the while loop, and go back to step 1 (evaluate the boolean expression). 18
while loop with sentinel Example: keep asking for user input until they enter 0. int N = 1; while (N!= 0){ System.out.printf("Enter an integer: "); N = in.nextint(); } System.out.println("Done with the while loop."); 19
while loop with counter What does this code do? Trace the execution on paper (fill in table on the right). Use the debugger check your answers from above. System.out.println("Enter N: "); int N = in.nextint(); // assume user enter 5 i N int i = 0; while (i <= N){ System.out.printf("i = %d\n", i); i = i + 1; } System.out.println("Done with the while loop."); 20
while loop with counter What does this code do? Trace the execution on paper. Use the debugger check your answers from above. System.out.println("Enter N: "); int N = in.nextint(); int i = 0; Variable i is called a counter. Initialize the counter. while (i <= N){ Condition involving the counter. System.out.printf("i = %d\n", i); i = i + 1; Update the counter. } System.out.println("Done with the while loop."); 21
Designing a for/while loop The loop must terminate exactly when needed (not too early or too late). 1. Define a test (boolean expression), that determines when to stay in the loop and when to exit. 2. Initialize and update variables that control the loop, as needed. 3. Test border cases in the condition do this after step 2. 22
Nested loops One loop in the body of another loop /* What does the following program print? How many times does each line execute? */ int i = 1; while (i < 4){ // outer loop System.out.printf("i =%d\n", i); int k = 1; while (k < 6){ // inner loop System.out.printf(" i = %d, k = %d\n", i, k); k = k + 1; } i = i + 1; } System.out.printf("Bye"); 23
Last instruction before loop False cond True False... cond True 1 st instruction after loop 24
Extra 25
More on Loops: break and continue Loop behavior discussed so far last instruction before loop False True cond New: 2 special jumps At the beginning After the loop...... 1 st instruction after loop 26
Normal loop last instruction before loop Loop with break or continue last instruction before loop False cond True False cond True............ continue break 1 st instruction after loop 1 st instruction after loop 27
Loop with break last instruction before loop False cond True.... The break instruction must be in a branch of an if-statement. Otherwise there is NO loop: it will break after the first iteration.... break break 1 st instruction after loop 28
Loop with continue last instruction before loop False cond True continue The continue instruction must be in a branch of an if-statement. Otherwise there is NO loop: it will break after the first iteration... continue... 1 st instruction after loop 29
continue last instruction before loop last instruction before loop False cond True False cond True...... continue...... 1 st instruction after loop 1 st instruction after loop 30
The break statement break forces termination of the current loop. Syntax: while (condition){ if (condition){ } } break # after this line it moves to the next instruction after while 31
The break statement Split opinions on the usage of break Example: print the first number >= N that is divisible by 13. 32
The break statement Example: print the first number >= N that is divisible by 13. System.out.println("Enter N: "); int N = in.nextint(); int i = N; while (true){ } if (i % 13 == 0){ System.out.print("first i>=%d,divisible by 13 is:%d", N,i); break; //after this line it moves to the next instr after while } i = i+1; 33
The continue statement continue skips the rest of the body of the loop and goes back to the header of the loop (which will cause it to execute the next iteration, or to terminate). Syntax: while (condition){ if (condition){ } continue; } 34
The continue statement Example: print numbers between 1 and N that are divisible by 13. 35
The continue statement Example: print numbers between 1 and N that are divisible by 13. System.out.println("Enter N: "); int N = in.nextint(); int i = 0; while (i < N){ i = i+1; if (i % 13!= 0){ //not divisible by 13, continue; } System.out.println("%d is divisible by 13", i); } 36
Practice: break and continue Pb1: Repeat a certain operation until the user enters a specific value: As long as user enters values greater or equal to 0: show letter grade based on score If strictly negative: finish Pb2: Same letter grade problem, but stop only when user enters -1. Skip scores out of range (maybe print a message), print letter grade for scores in range. Variation: in addition to printing the letter grade, also concatenate it into a string 37