Repetition Statements

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 6 Repetition Statements Animated Version.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Chapter 6 Repetition Statements. Objectives Understand repetition control (loop ) statements in Java: while statement. do-while statement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
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.
©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 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©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.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 6 – Repetition Statements : Objectives After you have read and studied this chapter, you should be able to Implement repetition control in a program.
Loops and Iteration for Statements, while Statements and do-while Statements.
Chapter 5 Loops.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
CMSC 150 LOOPS CS 150: Fri 20 Jan Representing DNA AGTCCAGTGTCAA.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
Discussion 4 eecs 183 Hannah Westra.
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Loops.
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Java Review Most of these slides are based on
Repetition-Counter control Loop
CSS 161: Fundamentals of Computing
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Looping and Repetition
MSIS 655 Advanced Business Applications Programming
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Do … Loop Until (condition is true)
Java Review Most of these slides are based on
Repetition Statements
Chap 7. Advanced Control Statements in Java
Chapter 3 Debugging Section 3.4
CSS161: Fundamentals of Computing
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
Loops and Iteration CS 21a: Introduction to Computing I
Chapter 7 Repetition Statements
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Looping and Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Repetition Statements Chapter 6 Repetition Statements CS 180 Recitation 27/28 September 2007 Department of Computer Science Purdue University

Announcements Project 4 due 3 October 2007 If you haven't started the second part, you should. (Projects now require starting on time) Level of cooperation Do not look at someone else's code or talk to someone else about specific code for a project. You may discuss general problem solving approaches. Talking to a TA about code is fine. We will study two forms of repetition statements in this lesson. They are while and do-while statement.

Announcements Mid Semester Evaluations Deadline is Monday, October 01... Monday To participate: https://portals.cs.purdue.edu/ log in using your Purdue career account ID and password, click on "Course Evaluations", and then click on "Mid-Semester Evaluations".

Syntax for the while Statement while ( <boolean expression> ) <statement block> Boolean Expression while ( number <= 100 ) { sum = sum + number; number = number + 1; } Statement (loop body) Here’s the general syntax of a while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body may not be executed at all.

Control Flow of while true false sum = sum + number; previous statement; int sum = 0, number = 1 number <= 100 ? true sum = sum + number; number = number + 1; This flowchart shows the control flow of the while statement. If the <boolean expression> is true, the loop body is executed and the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this while statement. false next statement;

Syntax for the do-while Statement <statement> while ( <boolean expression> ) ; do { sum += number; number++; } while ( sum <= 1000000 ); Statement (loop body) Here’s the general syntax of a do-while statement. As long as the <boolean expression> is true, the loop body is executed. Notice that the loop body is executed at least once. Boolean Expression

Control Flow of while true false sum += number; number++; previous statement; int sum = 0, number = 1 sum += number; number++; This flowchart shows the control flow of the while statement. If the <boolean expression> is true, the loop body is executed and the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this while statement. number <= 100 ? true false next statement;

for statement syntax for ( <initialization>; <boolean expression>; <increment> ) <statement> Initialization Boolean Expression Increment for ( i = 0 ; i < 20 ; i++ ) { number = scanner.nextInt(); sum += number; } Statement (loop body) This shows the general syntax for the for statement. The <initialization> component also can include a declaration of the control variable. We can do something like this: for (int i = 0; i < 10; i++) instead of int i; for (i = 0; i < 10; i++)

Control flow of for false true i < 20? sum += number; number++; previous statement; i=0; i < 20? false true This flowchart shows the control flow of the while statement. If the <boolean expression> is true, the loop body is executed and the control returns to the top. If the <boolean expression> is false, then the control flows to the next statement that follows this while statement. sum += number; number++; next statement; i++;

Query Are the different forms of loops equivalent? Could you use code to write them in terms of each other?

Watch Out for Pitfalls Watch out for the off-by-one error (OBOE). Move your loop condition towards termination. Make sure the loop repeats exactly the correct number of times.

Overflow An infinite loop often results in an overflow error. An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. With integral types, the value “wraps around” and becomes a negative value. With floating point, precision will determine whether or not true overflow occurs. (either infinite or unchanging) [See Overflow.java] When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false.

CAUTION: Empty loops! An inadvertent semi-colon can mean an empty loop! while ( name != null ); { someInt = JoptionPane.showInputDialog(null, “Enter Int”); i = someInt.parseInt(someInt); } for ( int i=0; i<10; i++ ); { name = JoptionPane.showInputDialog(null, ”Enter Int"); j += name.parseInt(name); }

Example 1 The charAt( int ) method of the String class returns the character at the given index of an instance. public String someMeth1( String str ) { String result = ""; for ( int index = str.length() - 1; index >= 0; --index ) result += str.charAt( index ); } return result; When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. What is the result of: someMeth1( "somewhere i have never traveled" )

Example 2 How does the above compare to using a while loop? public void someMeth2() { String name = ""; Scanner keyboard = new Scanner( System.in ); do System.out.print ("Please enter a name or \"quit\" to exit: "); name = keyboard.next(); System.out.println( "Howdy "+name+"!" ); } while ( !name.equals( "quit" ) ); } When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. How does the above compare to using a while loop? Is a for loop appropriate?

Example 3 Does the above loop terminate? public void someMeth3() { String name = ""; Scanner keyboard = new Scanner( System.in ); while ( true ) System.out.print ("Please enter a name or \"quit\" to exit: "); name = keyboard.next(); if ( !name.equals( "quit" ) ) System.out.println( "Howdy "+name+"!" ); else break; } When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. Does the above loop terminate? How does this compare to someMeth2?

Example 4 Notice that this has a cleaner flow than example 3. public void someMeth4() { S.o.p( "Please enter a name or 'quit' to exit: " ); Scanner keyboard = new Scanner( System.in ); String name = keyboard.next(); while ( !name.equals("quit") ) S.o.pln( "Howdy "+name+"!" ); S.o.p("Please enter a name or 'quit' to exit: "); name = keyboard.next(); } When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. Notice that this has a cleaner flow than example 3. Priming the loop can avoid extra cases and bugs.

Example 5 How does this loop behave when 7 is entered? 3? 0? public void someMeth5() { Scanner keyboard = new Scanner( System.in ); while ( true ) switch( keyboard.nextInt() ) case 0: case 1: case 2: System.out.println( "In here" ); break; case 3: case 4: case 5: System.out.println( "Somewhere else" ); continue; } System.out.println( "After Switch" ); When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false. How does this loop behave when 7 is entered? 3? 0?

Example 6 Notice how loops within loops can interact. public void someMeth6() { for ( int i = 0; i < 5; ++i ) for ( int j = 5-i; j > 0; --j ) System.out.print( "*" ); System.out.println(); } Notice how loops within loops can interact. What does each loop correspond to? Notice how using a table can help you execute this manually. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value “wraps around” and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false.

Example 7 What happens here? Where is the mistake? public void someMeth7() { for ( int i = 0; i < 5; ++i ) for ( int j = 5-i; j > 0; --i ) System.out.print( "*" ); System.out.println(); } What happens here? Where is the mistake?

Example 8 How does this behave? public void someMeth8() { for ( int i = 0; i < 5; ++i ) for ( int j = 5-i; j > 0; --j ) System.out.print( "*" ); --i; System.out.println(); } How does this behave?

Example 9 How does this behave? What have we forgotten? public void someMeth9() { int sum = 0; for ( int count = 1; count < 5; count++) System.out.println( “Count” + count” ); sum = sum + count; System.out.println( “Sum: ” + sum ); } How does this behave? What have we forgotten?

Exercise How would you write a function to print out the powers of 3 less than n? e.g. For 1000: 1 3 9 27 81 243 729 http://www.cs.purdue.edu/~cs180/slides/Power.java.html