CS101 Computer Programming I Chapter 4 Extra Examples.

Slides:



Advertisements
Similar presentations
Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Chapter 7 More Flow of Control. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Introduction Using Boolean Expressions.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
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.
©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.
© 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.
©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.
For Loops Programming. COMP102 Prog Fundamentals I: for Loops/Slide 2 The for Statement condition action true false initialization update.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Java Programming: From the Ground Up
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Chapter 5 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
1 Three C++ Looping Statements Chapter 7 CSIS 10A.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 5: Control Structures II
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Programming with Loops. When to Use a Loop  Whenever you have a repeated set of actions, you should consider using a loop.  For example, if you have.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Loops.
Chapter 5: Control Structures II
Loop Structures.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
CS1010 Programming Methodology
Repetition-Counter control Loop
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.
Chapter 4 Control structures and Loops
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Chapter 3 Even More Flow of Control 1
Algorithm Discovery and Design
Chapter 6: Repetition Statements
Loop Strategies Repetition Playbook.
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 3 Flow of Control Loops in Java.
Chapter 4: Loops and Iteration
Presentation transcript:

CS101 Computer Programming I Chapter 4 Extra Examples

while Loop Example  Write a while loop to print all the even integers between 0 and 20. int i = 0; while ( i <= 20 ) { if ( i % 2 = 0 ) System.out.printf( "%d ", i ); i++; } 2

Slide 3- 3 for/while Loop Comparison Write a code to add the numbers from 1 to 10.  Using a while loop: sum = 0; n = 1; while(n <= 10) // add the numbers { sum = sum + n; n=n+1; //n++; }  Using a for loop: sum = 0; for (n = 1; n <= 10; n++) //add the numbers sum = sum + n;

Slide 3- 4 while loop: Exit on Flag Caution  Consider this loop to identify a student with a grade of 90 or better to find a tutor for week students. (We assume the method compute_grade() has already been defined) (In this example the variable grade serves as the flag) int n = 1; grade = compute_grade(n); while (grade < 90) { n=n+1; //n++; grade = compute_grade(n); } System.out.printf( “Student number %d may be a tutor.\nThis student has a score of %f", n, grade );

Slide 3- 5 The Problem  The loop on the previous slide might not stop at the end of the list of students if no student has a grade of 90 or higher It is a good idea to use a second flag to ensure that there are still students to consider The code on the following slide shows a better solution

Slide 3- 6 The Exit On Flag Solution  This code solves the problem of having no student grade at 90 or higher : int n=1; grade = compute_grade(n); while (( grade = 90) System.out.printf( “Student number %d may be a tutor.\nThis student has a score of %f", n, grade ); else cout << "No student has a high score.";

Slide 3- 7 List Ended With a Sentinel Value nonnegative integers nonnegative integersA while loop is typically used to end a loop using the list ended with a sentinel value method. cout > number; while (number > =0) { sum = sum + number; cout > number; } Notice that the sentinel value is read, but not processed i.e.  -1 is read but not added to sum

Slide 3- 8 Debugging Loops  Common errors involving loops include Off-by-one errors in which the loop executes one too many or one too few times Infinite loops usually result from a mistake in the Boolean expression that controls the loop

Slide 3- 9 Fixing Off By One Errors  Check your comparison: should it be < or <=?  Check that the initialization uses the correct value  Does the loop handle the zero iterations case? (  in case, if the loop may sometimes be iterated zero times)

Slide Fixing Infinite Loops  Check the direction of inequalities: ?  Test for rather than equality (= =) Remember that doubles are really only approximations

Slide More Loop Debugging Tips  Be sure that the mistake is really in the loop  Trace the variable to observe how the variable changes Tracing a variable is watching its value change during execution Many systems include utilities to help with this cout statements can be used to trace a value

Slide Debugging Example containing the product of the numbers through 5  The following code is supposed to conclude with the variable product containing the product of the numbers 2 through 5 int next = 2, product = 1; while (next < 5) { next = next+1; //next++ product = product * next; }

Slide 13 Tracing Variables  Add temporary print statements to trace variables int next = 2, product = 1; while (next < 5) { next = next+1; //next++ product = product * next; System.out.printf( “next= %d product= %d.\n", next, product ); } next = 3 product = 3 next = 4 product = 12 next = 5 product = 60 Press any key to continue... Required was from 2 to 5 not from 3

Slide First Fix  The cout statements added to the loop show us that the loop never multiplied by 2 Solve the problem  by moving the statement next++ int next = 2, product = 1; while (next < 5) { product = product * next; System.out.printf( “next= %d product= %d.\n", next, product ); next = next+1; //next++ } There is still a problem! next = 2 product = 2 next = 3 product = 6 next = 4 product = 24 Press any key to continue...

Slide Second Fix  Re-testing the loop  shows us that now the loop never mulitplies by 5 The fix is to use <= instead of < in our comparison int next = 2, product = 1; while (next <= 5) { product = product * next; System.out.printf( “next= %d product=%d.\n", next, product ); next = next+1; //next++ } next = 2 product = 2 next = 3 product = 6 next = 4 product = 24 next = 5 product = 120 Press any key to continue...

Slide Loop Testing Guidelines  Every time a program is changed, it must be retested. Changing one part may require a change to another.  Every loop should at least be tested using input to cause: Zero iterations of the loop body One iteration of the loop body One less than the maximum number of iterations The maximum number of iterations

Slide Infinite Loops  Loops that never stop are infinite loops.  The loop body should contain a line that will eventually cause the Boolean expression to become false.  If you make a mistake and write your program so that the Boolean expression is always true, then the loop will run forever.  A loop that runs forever is called an infinite loop.

Slide Infinite Loops (Cont.)  Example: Print the positive even numbers less than 12. x = 2; while (x != 12) { System.out.println( x ); x = x + 2; }  Print the positive odd numbers less than 12. x = 1; while (x != 12) { System.out.println( x ); x = x + 2; }  This will create an infinite loop since the value of x goes from 11 to 13 and it’s never equal to 12.  Better to use this comparison: while ( x < 12)

Slide Example  Show the output of this code if x is of type int? int x = 10; while ( x > 0) { System.out.println( x ); x = x - 3; }  Show the output of the previous code using the comparison x 0? int x = 10; while ( x < 0) { System.out.println( x ); x = x - 3; }