Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.

Similar presentations


Presentation on theme: "COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218."— Presentation transcript:

1 COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218

2 Announcements Mid-Term Exam - March 9 –covers Chapters 1-5 –look at previous mid-term, homework exercises, in-class exercises, words in bold print in textbook Monday –sit with your recitation group –each group should have laptop, textbook, and lab manual

3 Loops Allow us to repeat statements some number of times Must use a loop control variable –controls how many times to loop 4 Parts to Every Loop –initialization - set loop control variable before condition –condition - when to stop –update - change to the loop control variable –body - actions to repeat

4 Typical Uses of Loops Repeat a section of code a specified number of times - counter-controlled Repeat a section of code (reading input) until the a specific value is read - sentinel-controlled Repeat a section of code (reading input) until a valid value is entered - input validation Repeat a section of code (reading from a file) until the end of the file is reached - EOF-controlled Repeat a section of code until a boolean variable becomes false - flag-controlled

5 Questions What type of while loop should be used? 1. Read every line in a file until the number -99 is read. 2. Read every line in a file where the length of the file is unknown. 3. Make sure that the user enters a lowercase letter. 4. Print the even numbers between 0 and 50. sentinel-controlled EOF-controlled input validation counter-controlled

6 The while Loop while (expression) statement

7 The while Loop final int LIMIT = 3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); boolean condition loop body update initialization Output: 0 1 2 All done!

8 In-Class Exercise Write a while loop that prints 2 4 6 8 int i = 2; while (i <= 8) { System.out.println (i); i += 2; } int i = 1; while (i <= 4) { System.out.println (i*2); i++; }

9 In-Class Exercise Write a while loop that prints the odd numbers between 0-100. int i = 0; while (i < 100) { if ((i % 2) == 1) { System.out.println (i); } i++; } int i = 1; while (i <= 99) { System.out.println (i); i+=2; }

10 Question What is the loop control variable in the following while loop? int count = 0, num; num = Integer.parseInt(keyboard.readLine()); while (num < 0) { System.out.println (num); num = Integer.parseInt(keyboard.readLine()); count++; } num

11 Today in COMP 14 The for loop The do...while loop break and continue Nested loops Textbook Reference: Ch 5 (pgs. 229- 247)

12 The for Loop Specialized form of while loop Simplifies the writing of count-controlled loops Basic Form: for (initialization; condition; update) { statement(s); }

13 The for Loop Execution 1. initial statement executes 2. loop condition evaluated 3. If loop condition evaluates to true, execute for loop statement and execute update statement 4. Go back to step 2 and repeat until loop condition is false

14 The for Loop Syntax for ( initialization; condition; update ) { loop body; } Reserved word The initialization is executed once before the loop begins The loop body is executed until the condition becomes false The update portion is executed at the end of each iteration The condition-loop body-update cycle is executed repeatedly

15 for vs. while A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { loop body; update; }

16 The for Loop Example final int LIMIT = 3; int count; for (count=0; count<LIMIT; count++) { System.out.println (count); } System.out.println (“All done!”); boolean condition loop body update initialization Output: 0 1 2 All done!

17 Comparing while and for While Loop final int LIMIT=3; int i = 0; while (i < LIMIT) { System.out.println (i); i++; } System.out.println (“All done!”); For Loop final int LIMIT=3; int i; for (i=0; i<LIMIT; i++) { System.out.println (i); } System.out.println ("All done!");

18 The for Loop Like a while loop, the condition of a for statement is tested prior to executing the loop body The body of a for loop will execute zero or more times It is well suited for executing a loop a specific number of times that can be determined in advance Anything you can do in a for loop, you can do in a while loop

19 The for Loop Does not execute if initial condition is false Update expression changes value of loop control variable, eventually making it false If loop condition is always true, result is an infinite loop for statement ending in semicolon is empty; does not affect program for (count=0; count<LIMIT; count++);

20 Examples for (i=1; i<=5; i++) { System.out.println ("Hello"); System.out.println ("*"); } for (i=1; i<=5; i++) System.out.println ("Hello"); System.out.println ("*"); for (i=1; i<=5; i++); System.out.println ("*"); Hello * Hello * Hello * Hello * Hello * Hello * *

21 Multiples.java Example Ask the user for a positive number Ask the user for a limit Print all of the multiples of the positive number up to limit What happens if the user enters a negative number?

22 In-Class Exercise for vs. while Loops final int MAX = 20; int i; for (i = 0; i<MAX; i+=3) { System.out.println (i); } Predict the output Translate this to a while loop. Output: 0 3 6 9 12 15 18 final int MAX = 20; int i = 0; while (i < MAX) { System.out.println (i); i += 3; }

23 The do…while Loop Statements executed first, then expression evaluated Statement(s) executed at least once then continued if expression is true Basic Form: do { statement(s); } while (expression);

24 The do...while Loop Syntax do { loop body; } while ( condition ); do and while are reserved words The loop body is executed once initially, and then the condition is evaluated The loop body is executed repeatedly until the condition becomes false

25 do…while Loop (Post-test Loop) do { statement(s); } while (expression);

26 The do...while Loop Like a while loop, but its condition is at the end of the loop Loop body always executes at least once Must also be checked for termination (not an infinite loop) Anything you can do with a do...while loop, you can do with a while loop

27 The do...while Loop Example final int LIMIT = 3; int count = 0; do { System.out.println (count); count++; } while (count < LIMIT); System.out.println (“All done!”); boolean condition loop body update initialization Output: 0 1 2 All done!

28 Comparing while and do...while while Loop final int LIMIT=3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); do...while Loop final int LIMIT=3; int count = 0; do { System.out.println (count); count++; } while (count < LIMIT); System.out.println ("All done!");

29 while vs. do...while i = 11; while (i <= 10) { System.out.print (i + " "); i += 5; } System.out.println(); i = 11; do { System.out.print (i + " "); i += 5; } while (i <= 10); System.out.println(); [blank line] 11

30 In-Class Exercise The do...while Loop int x = 0, y = 0; do { System.out.println (x*y); if (y < x) { y += 2; } x++; } while (x < 5); Predict the output of the loop xy0 Output: 1 2 0 0 4 6 16 2 3 4 4 5

31 break Statements Used to exit early from a loop Used to skip remainder of switch structure Can be placed within if statement of a loop – If condition is met, loop exited immediately

32 break Example int i; for (i=0; i<5; i++) { System.out.print ("i = "); if (i == 2) { break; } System.out.println (i); } i = 0 i = 1 i =

33 continue Statements Used in while, for, and do...while structures When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop When executed in a while/do…while structure, expression evaluated immediately after continue statement In a for structure, the update statement is executed after the continue statement; then the loop condition executes

34 continue Example int i; for (i=0; i<5; i++) { System.out.print ("i = "); if (i == 2) { continue; } System.out.println (i); } i = 0 i = 1 i = i = 3 i = 4 int i=0; while (i<5) { System.out.print ("i = "); if (i == 2) { continue; } System.out.println (i); i++; } i = 0 i = 1 i = i = i =... (infinite loop)

35 Nested Control Structures Provides new power, subtlety, and complexity if, if…else, and switch structures can be placed within while loops for loops can be found within other for loops –each time through the outer loop, the inner loop goes through its full set of iterations

36 Nested Control Structures Example for (int row = 1; row <= 5; row++) { for (int star = 1; star <= row; star++) { System.out.print(“*”); } System.out.println(); } Output: * ** *** **** ***** Can't use the variable row outside the outer for loop. Can't use the variable star outside the inner for loop.

37 Flips.java Example Flip a coin 5 times –choose a random number Print the total number of heads and tails

38 Loop Features loop initialization (outside / header) number of loop body executions update (inside / header) conditional (beginning / end) whileoutside0 or moreinsidebeginning dooutside1 or moreinsideend forheader0 or moreheaderbeginning

39 Choosing a Loop Structure while –you don't know how many times to execute the loop body do...while –you don't know how many times to execute the loop body, but it's at least once for –you know exactly how many times to execute the loop body

40 Loops 4 parts of every loop 1.initialization 2.condition 3.loop body 4.update Order while and for 1. initialization 2. condition 3. loop body 4. update do...while 1. initialization 2. loop body 3. update 4. condition

41 Program 3 Rock-Paper-Scissors-Spock-Lizard –variation on Rock-Paper-Scissors Have the computer choose one of the 5 shapes. –Hint: Math.random Ask the user to choose one of the 5 shapes or 'q' to quit. Decide who wins. After the user quits, print out a tally of the user wins, losses, and ties.

42 Program 3 You must print the title of the game. You must make sure the user knows what to enter to choose a particular shape. Allow the user to enter invalid input and prompt them for valid input. You do not have to use letters for selecting the shapes. Start early!

43 Program 3 Break Program into Smaller Steps 1. Print out welcome message, options, and directions to user 2. Write a loop that allows the user to enter a character and end the loop if the user enters 'q' (or 'Q') 3. Write code that will print out the shape (rock, paper,...) based on what the user entered 4. Write code that will make the computer choose a shape 5. Write code that will print out what shape the computer chose

44 Program 3 Break Program into Smaller Steps 6. Write code that decides if the computer or the user won 7. Write code that will keep up with the number of wins, losses, and ties for the user 8. Write code that will print out the number of wins, losses, and ties after the user chooses to quit

45 Math.random Example double randomNum; int sample012; // Math.random() will return [0.0, 1.0) randomNum = Math.random(); // sample012 will be {0, 1, 2} sample012 = (int) (randomNum * 3); // print out {-1, 0, 1} System.out.println(sample012 - 1); Print a random number in {-1, 0, 1}. System.out.println ((int) (Math.random() * 3) - 1);

46 In-Class Exercise Random Write a code fragment to choose a random number in {0, 1, 2, 3}. Print 'A' if the number chosen is 0, 'B' if the number is 1, 'C' if the number is 2, and 'D' if the number is 3. –Hint: a switch statement would be appropriate here sample = (int) (Math.random() * 4);

47 int sample; // sample will be {0, 1, 2, 3} sample = (int) (Math.random() * 4); switch (sample) { case 0: System.out.println("A"); break; case 1: System.out.println("B"); break; case 2: System.out.println("C"); break; case 3: System.out.println("D"); break; }

48 Next Time in COMP 14 Programming Session Sit with your recitation group Each group should have a laptop, textbook, and lab manual


Download ppt "COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218."

Similar presentations


Ads by Google