Chapter 4 Introduction to Control Statements. Fundamentals of Java

Similar documents
JavaScript: Control Statements I

Visual Logic Instructions and Assignments

Chapter One Introduction to Programming

WAYNESBORO AREA SCHOOL DISTRICT CURRICULUM INTRODUCTION TO COMPUTER SCIENCE (June 2014)

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

VB.NET Programming Fundamentals

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Computer Programming I

Java (12 Weeks) Introduction to Java Programming Language

Computer Programming I & II*

1.3 Conditionals and Loops

#820 Computer Programming 1A

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT,

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Moving from CS 61A Scheme to CS 61B Java

River Dell Regional School District. Computer Programming with Python Curriculum

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Flowchart Techniques

Unit 6. Loop statements

Exercise 4 Learning Python language fundamentals

Lecture 2 Notes: Flow of Control

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Fundamentals of Java Programming

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Programming and Software Development (PSD)

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Chapter 2: Elements of Java

Introduction to Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Informatica e Sistemi in Tempo Reale

Database Programming with PL/SQL: Learning Objectives

PYTHON Basics

Sources: On the Web: Slides will be available on:

Exercise 1: Python Language Basics

Programming and Software Development CTAG Alignments

AP Computer Science Java Subset

Object Oriented Software Design

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

The While Loop. Objectives. Textbook. WHILE Loops

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

ALGORITHMS AND FLOWCHARTS

Iteration CHAPTER 6. Topic Summary

Object Oriented Software Design

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

High School Pathway Program Options: Benefits of successfully completing Griffith InfoTech

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Computing Concepts with Java Essentials

Fundamentals of Programming and Software Development Lesson Objectives

Basic Programming and PC Skills: Basic Programming and PC Skills:

Two-way selection. Branching and Looping

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

VHDL Test Bench Tutorial

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Assignment # 2: Design Patterns and GUIs

Syllabus for CS 134 Java Programming

MATLAB Programming. Problem 1: Sequential

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

ChE-1800 H-2: Flowchart Diagrams (last updated January 13, 2013)

Computer Programming I

LOOPS CHAPTER CHAPTER GOALS

Pseudo code Tutorial and Exercises Teacher s Version

Chapter 7D The Java Virtual Machine

Curriculum Map. Discipline: Computer Science Course: C++

The C Programming Language course syllabus associate level

1 Description of The Simpletron

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

EMC Publishing. Ontario Curriculum Computer and Information Science Grade 11

Statements and Control Flow

Lecture 1 Introduction to Java

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT,

Programming MS Excel in Visual Basic (VBA)

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

Introduction to LogixPro - Lab

6. Control Structures

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

VIRTUAL LABORATORY: MULTI-STYLE CODE EDITOR

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Java Basics: Data Types, Variables, and Loops

Instruction Set Architecture (ISA)

Example of a Java program

Computational Mathematics with Python

TIP: To access the WinRunner help system at any time, press the F1 key.

Chapter 5. Selection 5-1

Essentials of Computer Programming. Computer Science Curriculum Framework

Java Application Developer Certificate Program Competencies

COMPUTER SCIENCE TRIPOS

Writing Control Structures

Chapter 13: Program Development and Programming Languages

Transcription:

Chapter 4 Introduction to Control Statements

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

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. 3

Vocabulary Control statements Counter Count-controlled loop Entry-controlled loop Flowchart Infinite loop 4

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

Additional Operators Extended assignment operators Assignment operator combined with arithmetic and concatenation operators 6

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

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

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: 9

Standard Classes and Methods: The Math Class (cont.) Math class methods example: 10

Standard Classes and Methods: The Random Class Random number generator: Returns numbers chosen at random from a predesignated interval Table 4-2: Methods in the Random class 11

A Visit to the Farm 12

The if and if-else Statements Principal forms: 13

The if and if-else Statements (cont.) Additional forms: 14

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. 15

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

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

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

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

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

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

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

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

The while Statement (cont.) Counting backward: 24

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

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

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

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

The for statement (cont.) Example: 29

The for statement (cont.) Count-controlled input: 30

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 31

The for statement (cont.) Both for loops and while loops are entrycontrolled 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: 32 Can declare loop control variable in header Initialization, condition, and update in one line of code

Nested Control Statements and the break Statement Control statements may be nested. 33

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

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

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. 36

Using Loops with Text Files (cont.) 37 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

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

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

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 40

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. 41

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 42

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 43

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 44

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 45

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) 46

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

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

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. 49

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

Design, Testing, and Debugging Hints 51 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 ifelse statements, use test data that forces the program to exercise all logical branches.

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. 52

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. 53

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. 54

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. 55

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 56