Chapter 4 Control Structures –Decisions –Loops. Chapter 4 selection structures This chapter begins a new path in our programming ability Basically we.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

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.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
CS 201 Selection Structures (2) and Repetition
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Logical Operators and Conditional statements
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Fundamentals of Python: From First Programs Through Data Structures
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
19/5/2015CS150 Introduction to Computer Science 1 Announcements  1st Assignment due next Monday, Sep 15, 2003  1st Exam next Friday, Sep 19, 2003  1st.
Fundamentals of Python: First Programs
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.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Flow of Control Part 1: Selection
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Chapter 5 Repetition and Loop Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville,
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
JavaScript, Fourth Edition
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Repetition and Loop Statements By: Suraya Alias.
Control statements Mostafa Abdallah
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
CISC105 – General Computer Science Class 4 – 06/14/2006.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
1 ICS103 Programming in C Lecture 7: Repetition Structures.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
CHAPTER 4 REPETITION STRUCTURES 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 A.AlOsaimi.
CprE 185: Intro to Problem Solving (using C)
Loop Structures.
JavaScript: Control Statements.
3 Control Statements:.
Chapter 6: Repetition Statements
The System.exit() Method
Control Structure Chapter 3.
Boolean Expressions to Make Comparisons
Control Structure.
ICS103: Programming in C 5: Repetition and Loop Statements
Chapter 13 Control Structures
Presentation transcript:

Chapter 4 Control Structures –Decisions –Loops

Chapter 4 selection structures This chapter begins a new path in our programming ability Basically we can cause our programs to follow different paths, react differently to different situations. It’s an exciting time to be learning Java programming

Chapter Overview Control structures Boolean expressions If statements Nested if Switch Looping

Section 4.1 Control structures Sequence Selection –Alter normally sequential flow of a program Repetition –Alter normally sequential flow of a program

Boolean Expressions Boolean has two possible values –True –False Simplest Boolean expression is variable –boolean leapYear = true; –Can only be assigned true or false

Relational operators < less than <= less than or equal == equal > greater than >= greater than or equal != not equal

Reading Boolean data Use JOptionPane.showConfirmDialog(null, “Is this fun?”); This is the result of the statement Returns 0 for yes, 1 for no, 2 for cancel

Using the result To convert this value to boolean simply use the result like this: boolean myBool = (returnNum == 0) See methods top of page 186 for method to handle this

Operands Operands can be: –Literals –Variables

Boolean Operators && and || or ! not

And True False 0

Or True 0 False

not Result 1 False 0 True

Boolean Operators (salary 5) (temperature > 90.0) && (humidity > 0.90)

Boolean variables in expressions winningRecord && (!onProbation)

Boolean Assignment variable = expression same = true; same = (x == y);

Short-circuit Short circuit evaluation –Stops evaluating as soon as knows the outcome. –Can cause problems depending on what is in statement

Writing Conditions (min <= x) && (x <= max) x min max

Comparing Characters ‘c’ < ‘d’ true ‘a’ > ‘A’ true ‘3’ > ‘4’ false

Comparing Strings Must use String methods string1.equals(string2)

Lexicographic Comparison string1.compareTo(string2) –Negative value if string 1 < string 2 –Value 0 if string 1 = string 2 –Positive value if string 1 > string 2 See table pg 195

Section 4.3 if statement if (gross > ) net = gross – tax; //if expression is true else net = gross; //if expression is false gross > net = gross - tax net = gross true false

One selection if (x != 0.0) product = product * x;

Syntax single selection if (condition) statement;

Syntax 2 alternatives if (condition) statement; else statement;

Look at web example else/Page1.htm else/Page1.htm

If and compound statements Use the braces to create a block of code in the if statement. if (x > y) { temp = x; x = y; y = temp; } //end if

If else and compound See example top page 200

Returning booleans from methods Look at example 4.8 page 201 –good way –need not do as shown on the bottom of the page

5.5 Decision steps in Algorithms Decision step: selects one of several actions. Review example 4.13 Pages

Case Study page 205 Payroll problem –Analysis –Design –Implementation Page 213 variable scope –Local –Data fields

4.5 nested ifs Besides using the Boolean operators && || and ! We can also create nested if statements. Nested if statements are often more efficient than a sequence of if statements

Sequence versus Nested if (x > 0) y = y + 1; if (x < 0) y = y – 1; if (x ==0) y = y + 2; if (x> 0) y = y + 1; else if (x < 0) y = y – 1; else //btw x is 0 y = y + 2;

Matching else with If You must use indentiation to make it clear how your if/else match. BUT!! The compiler ignores the white space Java matches each else with it’s closest preceding if that is not already matched with an else

Good or Bad if (x > 0) y = y * 4; if (x < 0) y = y * - 4; else y = y + 4;

Multiple alternative format if (score >= 90) displayResult(“A”); else if (score >= 80) displayResult(“B”); else if (score >= 70) displayResult(“C”);.

Example Order matters big time see page 220 Review tax example page 221

Tips Code nested ifs one statement at a time. Code outer if then the internal ifs TEST TEST TEST

Switch statement Switch allows you to select from several alternatives. Works especially well when based on the value of one variable

This is what it looks like switch (editOp) { case 0: search(); break; case 1: insert(); break; case 2: delete(); break; case 3: replace(); break; case 4: displayResult("All done"); break; default: displayResult("Invalid operation."); }

Rules The switch selector must be an ordinal data type. –Primitive –All values maybe listed –int, boolean, char –Not double Break causes control to pass to statement after the switch. Break statements are not always necessary

Another example switch (month) { case 12 : julian = julian + day; case 11 : if (month == 11) julian = julian + day; else julian = julian + 30; case 10 : if (month == 10) julian = julian + day; else julian = julian + 31; case 9 : if (month == 9) julian = julian + day; else julian = julian + 30; case 1 : if (month == 1) julian = julian + day; else julian = julian + 31; }//end switch Case 8 – 2 go in here, slides just aren’t big enough

Returning a value Use of a return in a switch case statement also stops execution of the statement. I am a little fussy with entry level programmers having multiple exit points in a method, although will allow it in a switch statement.

Repetition Structures In the programs we have written each line only executes at most 1 time. There are times that we want statements to execute multiple times. –When would you want this? Repetition is 3 rd type of control structure –Sequence, selection, repetition

Overview Loops –Counting loops –Sentinel controlled loops –Flag controlled loops –Menu driven loops Loop types –while –for –do-while

Counting loops Loop, repetition of steps in a program. Counting loop repeats a predetermined number of times. Name some real life examples of count controlled loops Counter-controlled loops are controlled by a variable that keeps track of the number of repetitions performed.

While statement Syntax: while (condition) statement; Statement is the body of the loop –Can be compound { } Condition, continues looping while condition remains true

Example int countTenSum = 1; int tenSum = 0 while (countTenSum < 11) { tenSum = tenSum + countTenSum; countTenSum = countTenSum + 1; }

Example int numberEmp = readInt(“number of employees”); int countEmp = 0; while (countEmp < numberEmp) { //read pay data computer gross and net //add one to counter countEmp = countEmp + 1; }

Syntax and formatting while (repetitionCondition) loopBody Must use indentation for clarity –As in other cases white space is totally ignored by compiler

Flow chart countEmp < numberEmp false Get Data Perform Calculations Increment counter true

Loop-control variable You must perform the following steps to your loop-control variable –Initialize –Test –Update What is a loop that never ends called? Can you sing the song that never ends?

For statement This is used just for count controlled loops. It is a special loop format that compresses count controlled into a special format. Count control loops are used quite often.

While versus for counter = initial; While (counter <= final) { //loop processing counter++; } for (counter = initial; counter <=final; counter++){ //loop processing }

Syntax for statement For (initialization statement; repetition condition; update statement) {loop body} Initialization statement occurs when for loop begins execution Prior to each loop repetition (include 1 st ) condition tested Update statement executes after each repetition

For examples See code page 230 Example 4.18 (int i = 10; i >= 0; i--) System.out.println(i); OK to create variable local in the loop

Accumulating a Sum Loops can be used to accumulate a sum Must have an accumulator –Loop causes accumulator to increase with each time loop is processed This is a common use of a loop. See page 231

New operators!!! count = count + 1; –count++; accum = accum + count; –accum += count; countDown = countDown – 1; –countDown--;

Code Review code on pages

State-controlled loops Rather than loop for a specific number of repetitions (count control) We can loop while a condition is true –Repetition stops when a particular state is reached. This state causes the loop- repetition condition to become false. Can we always be sure these will end??

Code See exams pages

4.8 Case Study Problem –Write program to generate and solve arithmetic problems. –Has feature of varying difficulty –Checks answers and corrects when wrong

Analysis Need class that generates math problems. Problem represented by an operator and it’s left and right operands. Operands generated randomly Gets larger as difficulty increases Called MathProblem

Analysis Another class will use MathProblem to generate individual problems Will also allow for looping and user interaction Will additionally store statistics Called MathDrill

Design Table page 244 Table page 245

Implementation See code pages

Section 4.9 Debugging and testing Jbuilder includes a Debugger that allows user to –single-step through program –trace –set breakpoints –watch variables

Without debugger Use diagnostic output statements Put in println and showMessageDialog in appropriate places in program to monitor code and variables

4.10 Common Programming Errors Fully parenthesis your boolean expressions also boolean flag; flag && x == y; //works but should be flag && (x == y);

Other common errors Watch use of == versus = Watch use of {} and indentation if (x==y) x = 2; else y = 3; x = 1; //continue code here

Other loop errors Off by one –One to few –One to many Check you loop boundaries –initial and final values of loop control variables are they right?