Chapter 4 Introduction to Control Statements

Similar documents
Unit 1 Lesson 4. Introduction to Control Statements

SUMMARY. Y Xi ~ In this chapter, you learned: 1 I Xi. while (x > O){ while (x > O) x = x - 1 i

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java Coding 3. Over & over again!

Control Structures II. Repetition (Loops)

Pace University. Fundamental Concepts of CS121 1

COMP 202 Java in one week

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 2: Using Data

Chapter Goals. Contents LOOPS

Computer Programming I - Unit 5 Lecture page 1 of 14

Introduction to the Java Basics: Control Flow Statements

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Principles of Computer Science I

STUDENT LESSON A12 Iterations


Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Repetition, Looping. While Loop

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

AP Programming - Chapter 6 Lecture

COMP 202. Java in one week

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

COMP 202 Java in one week

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

PIC 10A Flow control. Ernest Ryu UCLA Mathematics


Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Loops (while and for)

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

1.3 Conditionals and Loops

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Course Outline. Introduction to java

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Programming Using Java (98-388)

Chapter 4: Loops and Files

Chapter 4: Loops and Files

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Chapter 5: Loops and Files

1.3 Conditionals and Loops

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Loops. CSE 114, Computer Science 1 Stony Brook University

Introduction. C provides two styles of flow control:

Programming for Engineers Iteration

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Full file at

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Repetition, Looping CS101

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011

Dept. of CSE, IIT KGP

Assignment 2.4: Loops

Problem Solving With Loops

AP CS Unit 3: Control Structures Notes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Iteration statements - Loops

Chapter 2: Functions and Control Structures

1.3 Conditionals and Loops

Full file at

Zheng-Liang Lu Java Programming 45 / 79

Chapter 2: Using Data

Chapter 4 C Program Control

JME Language Reference Manual

Multiple Choice Questions ( 1 mark)

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

BASIC ELEMENTS OF A COMPUTER PROGRAM

Microsoft Visual Basic 2005 CHAPTER 6. Loop Structures

CS 106 Introduction to Computer Science I

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Chapter 7. Iteration. 7.1 Multiple assignment

Introduction to Java Applications

! Sequence of statements that are actually executed in a program. ! Conditionals and loops: enable us to choreograph control flow.

CS112 Lecture: Repetition Statements

Arithmetic Compound Assignment Operators

CS 106 Introduction to Computer Science I

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Introduction to Java & Fundamental Data Types

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Transcription:

Introduction to Control Statements Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1

Objectives 2 How do you use the increment and decrement operators? What are the standard math methods? How do you use if and if-else statements to make choices? How do you use while and for loops to repeat a process? How do you construct appropriate conditions for control statements using relational operators?

Objectives How do you detect and correct common errors involving loops? How do you create I/O dialog boxes and loops in a GUI? 3

Vocabulary control statements counter count-controlled loop entry-controlled loop flowchart infinite loop iteration off-by-one error overloading random number generator sentinel task-controlled loop 4

Additional Operators 5 Extended Assignment Operators: An assignment operator combined with arithmetic and concatenation operators. variable op= expression; variable = variable op expression; Increment (++) and Decrement(--): Operators increase or decrease a variable s value by one.

Standard Classes and Methods The Math Class: Range of common mathematical methods. Overloading: having two methods with the same name (abs). The sqrt method sends a message to the class instead of to an object because the Math class is static. 6

Standard Classes and Methods (continued) Seven methods in the Math class 7

Standard Classes and Methods (continued) 8 The Random Class: Supports programs that incorporate random numbers. Programs are used to simulate random events: Coin toss, stock market, etc. Random number generator returns numbers chosen at random from a predesigned interval.

Standard Classes and Methods (continued) The Random Class (cont): Programs that use Random class must import java.util.random. The output from codes using the Random class is different every time it is generated. 9 Methods in the Random class

A Visit to the Farm if-else and while are control statements. while means to repeat the action as long as the set condition holds true. If means to do one thing is the condition is true, and another if the condition is false. 10

The if and if-else Statements 11 Java is programmer-friendly because it combines English phrasing with algebraic notations. if and if-else are examples. Required elements: Semicolons: do not follow a closing brace. Braces: always in pairs; better to overuse than underuse. The exact format of the text depends on the programmer.

The if and if-else Statements (continued) Principal Forms: 12

The if and if-else Statements (continued) Additional Forms: The braces can be dropped if a single statement follows if or else. The condition in an if statement must be a Boolean expression. Returns the value true or false. 13

The if and if-else Statements (continued) Flowcharts for the if and if-else statements. 14

The if and if-else Statements (continued) Relational Operators: Greater than (>), equal to (==), less than or equal to (<=), not equal to (!=), etc. == distinguishes the equal-to operator from the assignment operator. In the not-equal-to operator,! is read as no. These values will either be true or false. 15

The if and if-else Statements (continued) Checking Input for Validity: if-else statements are commonly used to check user inputs before processing them. For example, if a user enters a negative number for a circle s radius. Program checks to see if the radius is >= 0. If >= 0, the radius is computed. If < 0, an error message displays. 16

The while Statement 17 Provides a looping mechanism that executes statements repeatedly as long as some condition remains true. Flowchart for a while statement

The while Statement (continued) 18 Count-Controlled Loops: The variable cntr controls how many times the loop executes. For example, a program that computes and displays the sum of the integers between 1 and 100. Each pass of the loop is an iteration. Trace of how variables change on each iteration through a loop

The while Statement (continued) Adding Flexibility: Could vary the starting value, ending value, and increment, or ask for user input for those values. Task-controlled loop: Executes until a task is accomplished. Example: find the first integer for which the sum 1+2.+n is over 1 million. The factorial of a given number (n) is the product of the numbers between 1 and n (1*2*3* *n). 19

The while Statement (continued) Common Structure: All of these examples share a common structure. For the loop to terminate, each iteration must move the variables closer to satisfying the condition. 20

The for Statement Combines counter initialization, a condition test, and an update in a single expression. When the statement is executed, the counter is initialized. As long as the test yields true, the loop continues. The counter is updated at the bottom of the loop, after the statements in the body have been executed. 21

The for Statement (continued) Count-Controlled Input: Programs often need to read and process repeating inputs. Example: computing the average of a list of numbers. List length can vary. 22

The for Statement (continued) Declaring the Loop Control Variable in a for Loop : The for loop allows the programmer to declare the loop control variable outside of and above the loop header. Within the loop header is preferable: Only visible in the body of the loop where it s being used. The same name can be declared again in other for loops in the same program. 23

The for Statement (continued) Choosing a while Loop or a for Loop: Both are entry-controlled loops. A continuation condition is tested at the top of the loop on each pass to determine if the loop continues (true) or terminates (false). There are two advantages to choosing a for loop. All of the loop information (initial setting of loop control variable, its update, and the continuation test) is within the loop header. The loop control variable of a for loop can be declared in its header. 24

Nested Control Statements and the break Statement Control statements can be nested. Printing the divisors of a number, excluding 1 and the number. Determining if a number is prime. The break statement is used to get out of a loop before the condition is false. Sentinels are values that mark the end of a list. Use the do-while and continue statements. 25

Using Loops with Text Files Instead of user input from the keyboard, programs can also read input from a text file. Software object stored on a permanent medium, such as disk, CD, or flash memory. Advantages of input data from a file: Data set can be larger. Data can be input faster and with less chance of error. Data can be reused within the same or other programs. 26

Using Loops with Text Files (continued) 27 Text Files and Their Format: A text file can be created, saved, and viewed with a text editor, such as Notepad. Characters, words, numbers, or lines of text. Whitespace characters: space, tab, or newline. Must be used to separate numbers. Must include a special character that marks the end of a file. A sentinel for program loop.

Using Loops with Text Files (continued) The Scanner and File Classes: Scanner class can be used for text file input. Create a scanner object by opening it in a file object. File objects are instances of the File class. new File(aFileName) afilename is the pathname or name of the file. 28

Using Loops with Text Files (continued) Files and Exceptions: Missing or corrupted file. I/O exception is thrown. A checked exception: must acknowledge that they might be thrown and do something to recover from them. Use throws IOException to instruct the JVM to halt execution with an error message. 29

Using Loops with Text Files (continued) Output to Text Files: Use the class PrintWriter. Class includes print and println methods. After outputs are completed, must close the PrintWriter by adding writer.close(); If the output file is not closed, no data will be saved to it. 30

Errors in Loops Logic errors in loops can be avoided by understanding a typical loop structure. Initializing statements: initialize variables. Terminating condition: tested before each pass to determine if another iteration is needed. Body statements: execute with each iteration and implement the calculation in question. Update statements: change the values of the variables tested in the termination condition. 31

Errors in Loops (continued) Initialization Error: When you forget to initialize the variable product. Off-by-One Error: When a loop goes around one too many or one to few times. Infinite Loop: An error in the terminating condition. Detected when a program runs slower than expected. Stop by pressing Ctrl+C. 32

Errors in Loops (continued) 33 Error in Loop Body: Occurs in body of the loop, such as using the wrong operator. Update Error: When an update statement is in the wrong place. Effects of Limited Floating-Point Precision: Double numbers have 18 decimal points of precision. Causes problems for number such as 1/3, which is.3333 and never ends.

Errors in Loops (continued) 34 Debugging Loops: Inspect the code and make sure the following are true. Variables are initialized before entering the loop. Terminating condition stops when the variables have reached the limit. Statements in the body are correct. Update statements are positioned correctly and modify the variables so that they pass the limits in the terminating condition.

Errors in Loops (continued) Debugging Loops (cont): Use <, <=, >, >= rather than == or!=. If you cannot find an error by inspection, use System.out.println to dump key variables into the terminal window. Immediately after the initialization statements. Inside the loop at the top. Inside the loop at the bottom. 35

Graphics and GUIs: I/O Dialog Boxes and Loops I/O Dialogs: A small window that contains: A message. A text field for entering input or accepting a default. Command buttons, such as OK or Cancel. The class JOptionPane in the package javax.swing includes varieties of showinputdialog for input dialog boxes. 36

Graphics and GUIs: I/O Dialog Boxes and Loops (continued) If the user clicks OK, the dialog box closes and returns the string in the text input field. If the user clicks Cancel, the dialog box closes and returns the value null. If the value is a number, it must be converted to int or double. 37 An input dialog

Graphics and GUIs: I/O Dialog Boxes and Loops (continued) To output a message, use a message dialog box. JOptionPane.showMessageDialog(anObserver, astring) Setting Up Lots of Panels: Example: a program that sets up a quilt pattern. User chooses dimensions of the grid (number of rows and columns) and the initial size of the application window. The program displays them in panels. 38

Graphics and GUIs: I/O Dialog Boxes and Loops (continued) Setting the Preferred Size of a Panel: The preferred size of a panel can be done in different ways. The main window class sets its dimensions at program startup. Give each panel a preferred size and ask the program to shrink-wrap its dimensions to accommodate all of the panels. 39

Graphics and GUIs: I/O Dialog Boxes and Loops (continued) Setting the Preferred Size of a Panel (cont): Use the setsize method to ask the window to wrap itself around the minimal area necessary to display all of the its components at their preferred size. If a panel does not set its own preferred size, the default is 0 by 0. 40

Graphics and GUIs: I/O Dialog Boxes and Loops (continued) Drawing Multiple Shapes: Example: a bulls-eye. Draw the oval with current color, corner point, and size. Adjust the corner point by subtracting the thickness from each coordinate. Adjust the size by subtracting twice the thickness from each dimension. Adjust the color (white to red or vice versa). 41

Design, Testing, and Debugging Hints Most errors involving selection statements and loops are caught at compile time. Proper use of braces { } affect the logic of a selection statement or loop. When testing if or if-else statements, use test data to exercise the logical branches. Use an if-else statement rather than two if statements if the alternative courses of action are mutually exclusive. When testing a loop, use limit values and typical values. 42

Design, Testing, and Debugging Hints (continued) Check entry and exit conditions for each loop. For a loop with errors, use debugging output statements to verify the values of the control variable on each iteration. Check the value before the loop is initially entered, after each update, and after the loop is exited. Text files are convenient when the data set is large or is used with different programs, and when the data must be permanently saved. 43

Summary In this chapter, you learned: Java has some useful operators for extended assignment, such as +=, 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. 44

Summary (continued) if and if-else statements are used to make one-way and two-way decisions. The comparison operators, such as ==, <=, and >=, return Boolean values that serve as conditions of control statements. The while loop allows the program to run a set of statements repeatedly until a condition becomes false. 45

Summary (continued) 46 The for loop is a more concise version of the while loop. Other control statements, such as an if statement, can be nested within loops. A break statement can be used in conjunction with an if statement to terminate a loop early. There are many kinds of logic errors that can occur in loops. Examples are the off-by-one error and the infinite loop.