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

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 6, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
COMP 14 Introduction to Programming Mr. Joshua Stough February 21, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Chapter 5: Control Structures II (Repetition)
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
Chapter 5: Control Structures II (Repetition)
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
Chapter 5 Loops.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
CiS 260: App Dev I Chapter 4: Control Structures II.
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
Outline Altering flow of control Boolean expressions
Control Statements Loops.
What output is produced by the following fragment?
Control Statements Loops.
Presentation transcript:

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

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

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

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

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

The while Loop while (expression) statement

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: All done!

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

In-Class Exercise Write a while loop that prints the odd numbers between 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; }

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

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

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

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

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

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

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: All done!

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!");

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

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++);

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 * *

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?

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: final int MAX = 20; int i = 0; while (i < MAX) { System.out.println (i); i += 3; }

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);

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

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

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

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: All done!

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!");

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

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:

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

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 =

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

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)

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

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.

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

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

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

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

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.

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!

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

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

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(sample ); Print a random number in {-1, 0, 1}. System.out.println ((int) (Math.random() * 3) - 1);

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);

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; }

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