Chapter 4 Introduction to Control Statements

Slides:



Advertisements
Similar presentations
Chapter 8 Improving the User Interface
Advertisements

Programming with Microsoft Visual Basic th Edition
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
CS0004: Introduction to Programming Repetition – Do Loops.
Chapter 4 Introduction to Control Statements
Objectives In this chapter, you will learn about:
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
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.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
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.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
Chapter 6 Control Statements Continued
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
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.
Fundamentals of Python: From First Programs Through Data Structures
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Fundamentals of Python: First Programs
1 Chapter 7 Control Statements Continued Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 6 Looping.
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 12: How Long Can This Go On?
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Logic and Design Fifth Edition, Comprehensive
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.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
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 6 Looping CS185/09 - Introduction to Programming Caldwell College.
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.
Visual Basic Programming
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
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.
Chapter 3: Assignment, Formatting, and Interactive Input.
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.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Pascal Programming Pascal Loops and Debugging. Pascal Programming Pascal Loops In our first brush with the while do loops, simple comparisons were used.
Chapter 6 Control Statements Continued
Lesson 4: Introduction to Control Statements
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Chapter 4 Introduction to Control Statements Fundamentals of Java.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
Loop Structures.
Java Programming: Guided Learning with Early Objects
Chapter 4 – Control Structures Part 1
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

Chapter 4 Introduction to Control Statements Fundamentals of Java

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

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

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

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

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

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

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

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

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

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

A Visit to the Farm Fundamentals of Java

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Graphics and GUIs: I/O Dialog Boxes and Loops A convenient way to accept input from a user is to pop up an input dialog box. Use JOptionPane.showInputDialog(). Figure 4-4: Input dialog box Fundamentals of Java

Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) If expected input is a number, must use Integer.parseInt() or Double.parseDouble() To output a message, use a message dialog box. JOptionPane.showMessageDialog( anObserver, aString) Fundamentals of Java

Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Example 4.5: CircleArea with dialog I/O Fundamentals of Java

Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Figure 4.5: Dialog I/O user interface for the circle area program Fundamentals of Java

Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Setting up multiple panels: Can use a loop to initialize and install panels Setting the preferred size of a panel: Use JPanel class’s setPreferredSize() method. JFrame class’s pack() method will cause the window to adjust its size to exactly fit the preferred size of any contained panels. Fundamentals of Java

Graphics and GUIs: I/O Dialog Boxes and Loops (cont.) Example 4-7: Color panel whose background is a color provided by the client. A client-specified preferred size is optional. Fundamentals of Java

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

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

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

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

Summary (cont.) The comparison operators, such as ==, <=, and >=, 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

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 Fundamentals of Java