Chapter 4 Introduction to Control Statements Fundamentals of Java.

Slides:



Advertisements
Similar presentations
Chapter 4 Introduction to Control Statements
Advertisements

Objectives In this chapter, you will learn about:
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 6 Control Statements Continued
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
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
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.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Logic and Design Fifth Edition, Comprehensive
Loops and Iteration for Statements, while Statements and do-while Statements.
Computer Science 12 Mr. Jean May 2 nd, The plan: Video clip of the day Review of common errors in programs 2D Arrays.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
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.
Fundamentals of Java Text by: Lambert and Osborne Slides by: Cestroni.
4.1 Additional Operators Extended Assignment Operators –The assignment operator can be combined with the arithmetic and concatenation operators to provide.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Chapter 6 Control Statements Continued
Lesson 4: Introduction to Control Statements
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 4 Introduction to Control Statements
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Loop Structures.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Control Structures - Repetition
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Chapter 6: Repetition Statements
Computing Fundamentals
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Chapter 4 Introduction to Control Statements Fundamentals of Java

Warm-up Write a for-loop that repeats 10 times and prints out every number from 1 to 10 Fundamentals of Java 2

3 Objectives Use the increment and decrement operators. Use standard math methods. Use if and if-else statements to make choices.

Fundamentals of Java 4 Objectives (cont.) Use while and for loops to repeat a process. Construct appropriate conditions for control statements using relational operators. Detect and correct common loop errors.

Fundamentals of Java 5 Vocabulary Control statements Counter Count-controlled loop Entry-controlled loop Flowchart Infinite loop

Fundamentals of Java 6 Vocabulary (cont.) Iteration Off-by-one error Overloading Sentinel Task-controlled loop

Fundamentals of Java 7 Additional Operators Extended assignment operators – Assignment operator combined with arithmetic and concatenation operators

Fundamentals of Java 8 Additional Operators (cont.) Increment operator: ++ – Increase value of operand by 1 Decrement operator: -- – Decrease value of operand by 1

Fundamentals of Java 9 Standard Classes and Methods: The Math Class Table 4-1: Seven methods in the Math class

Fundamentals of Java 10 Standard Classes and Methods: The Math Class (cont.) The two abs() methods are overloaded. – Overloaded: Multiple methods in the same class with the same name Using sqrt() method example:

Fundamentals of Java 11 Standard Classes and Methods: The Math Class (cont.) Math class methods example:

Fundamentals of Java 12 Standard Classes and Methods: The Random Class Random number generator: Returns numbers chosen at random from a pre- designated interval Table 4-2: Methods in the Random class

Fundamentals of Java 13 A Visit to the Farm

Fundamentals of Java 14 The if and if-else Statements Principal forms:

Fundamentals of Java 15 The if and if-else Statements (cont.) Additional forms:

Fundamentals of Java 16 The if and if-else Statements (cont.) Better to over-use braces than under-use them – Can help to eliminate logic errors Condition of an if statement must be a Boolean expression – Evaluates to true or false A flowchart can be used to illustrate the behavior of if-else statements.

Fundamentals of Java 17 The if and if-else Statements (cont.) Figure 4-1: Flowcharts for the if and if-else statements

Fundamentals of Java 18 The if and if-else Statements (cont.) Examples of if statements:

Fundamentals of Java 19 The if and if-else Statements (cont.) Table 4-3: Relational operators

Fundamentals of Java 20 The if and if-else Statements (cont.): Checking Input for Validity Example 4.1: Computes the area of a circle if the radius >= 0 or otherwise displays an error message

Fundamentals of Java 21 The while Statement Provides a looping mechanism – Executes statements repeatedly for as long as some condition remains true

Fundamentals of Java 22 The while Statement (cont.) Figure 4-2: Flowchart for a while statement

Fundamentals of Java 23 The while Statement (cont.) Example: Counter-controlled loop: – cntr is the counter – Loop repeats a determined number of times

Fundamentals of Java 24 The while Statement (cont.) Tracing: Track value of variables through each iteration of the loop Table 4-4: Trace of how variables change on each iteration through a loop

Fundamentals of Java 25 The while Statement (cont.) Counting backward:

Fundamentals of Java 26 The while Statement (cont.) Task-controlled loop: Continues to execute until some task is accomplished

Fundamentals of Java 27 The while Statement (cont.) Common structure of a while loop:

Fundamentals of Java 28 The while Statement (cont.) Example 4.2: Compute and display the factorial of n

Fundamentals of Java 29 The for statement Combines counter initialization, condition test, and update into a single expression Easy to create count-controlled loops

Fundamentals of Java 30 The for statement (cont.) Example:

Fundamentals of Java 31 The for statement (cont.) Count-controlled input:

Fundamentals of Java 32 The for statement (cont.) Better to declare the loop control variable within the loop header – Only visible within the loop – Variable name can be reused later in other loops

Fundamentals of Java 33 The for statement (cont.) Both for loops and while loops are entry- controlled loops. – Condition tested at top of loop on each pass Choosing a for loop versus a while loop is often a matter of style. – for loop advantages: Can declare loop control variable in header Initialization, condition, and update in one line of code

Fundamentals of Java 34 Nested Control Statements and the break Statement Control statements may be nested.

Fundamentals of Java 35 Nested Control Statements and the break Statement (cont.) break statement: Prematurely end a loop

Fundamentals of Java 36 Nested Control Statements and the break Statement (cont.) Sentinel-controlled input: Continue a loop until a sentinel variable has a specific value

Fundamentals of Java 37 Using Loops with Text Files Advantages of using text files versus input from a human user: – Data sets can be much larger. – Data input quickly, with less chance of error. – Data can be used repeatedly. Data files can be created by hand in a text editor or generated by a program.

Fundamentals of Java 38 Using Loops with Text Files (cont.) Text file format: – If data is numerical, numbers must be separated by white space. – Must be an end-of-file character Used by program to determine whether it is done reading data When an error occurs at run-time, the JVM throws an exception. – IOException thrown if error occurs during file operations

Fundamentals of Java 39 Using Loops with Text Files (cont.) Example 4.3: Computes and displays the average of a file of floating-point numbers

Fundamentals of Java 40 Using Loops with Text Files (cont.) Example 4.4: Inputs a text file of integers and writes these to an output file without the zeroes

Fundamentals of Java 41 Errors in Loops May occur in initializing statements, terminating conditions, body statements, or update statements Initialization error: Failure to initialize or initializes to incorrect value Off-by-one error: Loop iterates one too many or one too few times

Fundamentals of Java 42 Errors in Loops (cont.) Infinite loop: Error in the terminating condition – Loop never terminates Errors in loop body affect whether the loop completes its task correctly or at all. Update error: Update statements in wrong place may affect calculations – Failing to update at all results in an infinite loop.

Fundamentals of Java 43 Errors in Loops (cont.) Effects of limited floating-point precision: When using floating-point variables as loop control variables, you must understand that not all values can be represented. – Better not to use == or != in condition statement under these conditions

Fundamentals of Java 44 Errors in Loops (cont.) Debugging loops: – If an error is suspected, make sure that: Variables are initialized before entering the loop The terminating condition stops the iterations when the test variables have reached the intended limit The statements in the body are correct

Fundamentals of Java 45 Errors in Loops (cont.) Debugging loops (cont.): – If an error is suspected, make sure that: The update statements are positioned correctly and modify the test variables so that they eventually pass the limits tested in the terminating condition

Fundamentals of Java 46 Design, Testing, and Debugging Hints Most errors involving selection statements and loops are not syntax errors. The presence or absence of the {} symbols can seriously affect the logic of a selection statement or loop. When testing programs that use if or if- else statements, use test data that forces the program to exercise all logical branches.

Fundamentals of Java 47 Design, Testing, and Debugging Hints (cont.) Use an if-else statement rather than two if statements when the alternative courses of action are mutually exclusive. When testing a loop, be sure to use limit values as well as typical values. Be sure to check entry conditions and exit conditions for each loop.

Fundamentals of Java 48 Design, Testing, and Debugging Hints (cont.) For a loop with errors, use debugging output statements to verify the values of the control variable on each pass through the loop. Text files are convenient to use when the data set is large, when the same data set must be used repeatedly with different programs, and when these data must be saved permanently.

Fundamentals of Java 49 Summary Java has operators for extended assignment and for increment and decrement. The Math class provides several useful methods, such as sqrt and abs. The Random class allows you to generate random integers and floating-point numbers. if and if-else statements are used to make one-way and two-way decisions.

Fundamentals of Java 50 Summary (cont.) The comparison operators, such as ==, =, return Boolean values that can serve as conditions for control statements. The while loop allows the program to run a set of statements repeatedly until a condition becomes false. The for loop is a more concise version of the while loop.

Fundamentals of Java 51 Summary (cont.) Other control statements, such as an if statement, can be nested within loops. A break statement can be used with an if statement to terminate a loop early. Many kinds of logic errors can occur in loops. – Off-by-one error – Infinite loop

While Loops Fundamentals of Java 52 A while loop has a boolean test and a body containing statements, like this: int count = 0; while (count < 100) { // test: boolean test within (..) System.out.println("count:" + count); // body: statements within {..} count = count + 1; } System.out.println("all done!");

While Loops An if-statement looks at the test one time and then maybe executes the body once. The while-loop extends this idea, executing the body again and again, checking the test each time. The while-loop follows these steps: 1. Check if the test is true or false. If false, the loop "exits" and does not execute the body. If the test is true, continue with step Execute the body statements, starting at the top and proceeding down through them all. 3. Go back to step 1 and check the test again. If it is true, run the body again. Each time the body finishes, "loop around" and check the test again. Each run of the body is called an "iteration" of the loop. Eventually the test is false, the loop exits, and the program continues with the line after the while-loop Fundamentals of Java 53

How To Write a While Loop To write a while-loop, we think about three parts Test 2. Work 3. increment Fundamentals of Java 54

TEST test -- a boolean test of what should be true before each iteration. Or put another way, the test is the "green light" condition that says that each iteration can go ahead. Eventually, the test should become false and the loop can exit. Think about the precondition that describes the state before each iteration runs -- how are things arranged, what is true? Fundamentals of Java 55

WORK work -- code in the body that does something for each iteration such as printing or drawing something. Some loops do not have any identifiable work in the body. In the above example, the work is the println() that prints something out for each iteration. Fundamentals of Java 56

Increment increment -- code in the body that advances things so we are closer to making the test false. At the end of the body, the code will loop around to the top of the body. Sometimes, some cleanup is required at the end of the body to set things up for the next iteration. In the above example, the line "count = count + 1;" accomplishes the increment. That can also be written as "count++;". Fundamentals of Java 57

While Loop Example Here's a while loop example that uses a loop to see how man times you can divide a number by 2: // Given a num, returns how many times can we divide it by 2 to get down to 1. int count2Div(int num) { int count = 0; // count how many divisions we've done while (num >= 1) { num = num / 2; count++; } return count; } Fundamentals of Java 58

Zero Loop Iterations Since the while-loop checks the test before every iteration, it is possible for the body to not run even once: int count = 100; while (count < 100) { // the test is false the very first time count = count + 1 // this line never runs } Fundamentals of Java 59

Infinite Loop The most famous sort of bug you can get with loops is an "infinite loop", where through some mis-arrangement, running the loop body fails to get any closer to making the test false. Typically, this comes down to some sort of logical disconnect between the body and the test. For example, suppose the body fails to make the count bigger by accident: int count = 0; while (count < 100) { System.out.println("count:" + count); count = count * 1; // OOPS, does not change count } Fundamentals of Java 60

Infinite Loops Suppose we forget to put in the count line entirely, so the loop just spins in place with count stuck at zero: int count = 0; while (count < 100) { System.out.println("count:" + count); // OOPS, forget to put in a line that changes count at all } Fundamentals of Java 61

Inifinite Loops In some cases, we want the code to run on and on without stopping. In that case, we might write an infinite loop on purpose by giving true as the test: while (true) { // deliberate infinite loop } Fundamentals of Java 62

While-break With the while-break, we have the power of a while loop, but now we can position the test anywhere we want instead of just at the top. In fact, a standard while loop of this form: while (test) { body } Is equivalent to a while-break loop where the break is positioned at the very top: while (true) { if (!(test)) { break; } body } Fundamentals of Java 63

For Loops The for-loop is a variant of the while-loop, specialized to deal with a particular looping problem. The for-loop is specialized for the case where we want to step a variable through a series of values. For example, the following for-loop steps the variable "i" through the values 0, 1, 2,... 99: for (int i=0; i<100; i++) { System.out.println("i:" + i); } Fundamentals of Java 64

For Loop Header The for-loop has four parts -- init, test, increment, and body -- separated by semi- colons (;) for ( init ; test ; increment ) { body } Fundamentals of Java 65

Init The init code runs once to set things up at the very start of the loop. Typically, this looks like "int i = 0", declaring a variable to use for the counting, and setting its start value. The variable exists only within the loop (down through the } of the body). Although we avoid single-letter variable names for general purpose storage, this use of "i" is standard in a for-loop like this. Indeed, this pattern is so standard that other programmers would likely be a little confused if you used a variable name other than "i" in a for-loop. The convention extends to using the names "j", and "k" for loop variables if "i" is already in use. Never use lowercase L "l", since it looks just like the digit one "1" in many fonts. Fundamentals of Java 66

2. Test The boolean test is evaluated. If it is true the loop body will execute (green light, just like a while-loop). Typically, the test is a boolean expression such as "i<100", showing what should be true for the loop to continue. Fundamentals of Java 67

3. Loop-body If the test was true, the body runs once. The body is a series of statements, just like in a while-loop. The loop body will very often make some use of the loop variable, such as "i" in this example. Fundamentals of Java 68

4. Increment Finally, the increment code executes just after the body, and then the program loops back to the test, (step 2). The increment advances the state of things in preparation for the next iteration. The increment code advances the state, and then the test (2) looks at the state. Eventually, we advance the state so far that the test is false and the loop exits. This is analogous to the "increment" idea in the while- loop. In the while-loop, the increment is just a conceptual goal, but in the for-loop, the increment has its own slot in the syntax. When writing a for-loop, we are less likely to forget to do the increment, since the syntax has an explicit slot for it. Fundamentals of Java 69

For Loop Examples /*Classic for-loop counting up from 0 to 99 0, 1, 2, 3, init int i = 0 -test i<100 -increment i++ */ for (int i=0; i<100; i++) { System.out.println(i); } Fundamentals of Java 70

For Loop Examples /* For-loop to print the values 0, 2, 4, 6, increment by i+=2, instead of i++ (same as i = i + 2) */ for (int i=0; i<100; i+=2) { System.out.println(i); } Fundamentals of Java 71

For Loop Examples /* For-loop from 99 down to 0 99, 98, 97, init i=99 - test i>=0 -increment i-- */ for (int i=99; i>=0; i--) { System.out.println(i); } Fundamentals of Java 72

For Loop Examples /* For-loop from 0 to 100 by 5's 0, 5, 10, 15, test i<=100 -increment i+=5 */ for (int i=0; i<=100; i+=5) { System.out.println(i); } Fundamentals of Java 73

For vs. While Loops The for-loop can actually be understood as equivalent to a while-loop version, like this: init while (test) { body increment } So for example, we could write the standard loop like this, although for real code we would prefer the for-loop in this problem: int i = 0; while (i<100) { System.out.println(i); i++; } Fundamentals of Java 74

For vs. While Loops As a matter of style, if we are solving a series-of-values 0, 1, 2, 3, type problem, then the for-loop is preferable. If the looping problem does not fit into the series-of-values pattern, then the standard while-loop is best. Fundamentals of Java 75