Introduction To Scientific Programming Chapter 3.

Slides:



Advertisements
Similar presentations
Branching Loops exit(n) method Boolean data type and expressions
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
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.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
ITM352 Loops Lecture #6. 1/28/03ITM352 Fall 2003 Class 5 – Control Flow 2 Announcements r Lab class dates have changed!!! m Check the “Weekly Schedule”
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Chapter 31 Flow of Control Chapter 3. 2 Reminders Project 1 was due last night Project 2 released: due Sept 10:30 pm - No Late Submissions Follow.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 200 Lecture 4 Matt Kayala 1/30/06. Learning Objectives Boolean Expressions –Building, Evaluating & Precedence Rules Branching Mechanisms –if-else.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Logical Operators and Conditional statements
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
© 2004 Pearson Addison-Wesley. All rights reserved February 17, 2006 The ‘while’ Statement ComS 207: Programming I (in Java) Iowa State University, SPRING.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control.
Flow of Control Module 3. Objectives Use Java branching statements Compare values of primitive types Compare objects such as strings Use the primitive.
Flow of Control Part 1: Selection
ITM 352 Flow-Control: if and switch. ITM © Port, KazmanFlow-Control - 2 What is "Flow of Control"? Flow of Control is the execution order of instructions.
Lecture 4 – PHP Flow Control SFDV3011 – Advanced Web Development 1.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
Flow of Control Chapter 3 Flow of control Branching Loops
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Chapter 3 1 l Branching l Loops l exit(n) method l Boolean data type and logic expressions Flow of Control – Part 1.
Control Flow Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Control statements Mostafa Abdallah
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Lecturer: Dr. AJ Bieszczad Chapter 3 COMP 150: Introduction to Object-Oriented Programming 3-1 l Branching l Loops l exit(n) method l Boolean data type.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Chapter 3Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 3 l Branching l Loops l exit(n) method l Boolean data type.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Chapter 3 Branching Statements
ITM 352 Flow-Control: if and switch
Branching Loops exit(n) method Boolean data type and expressions
Control Structures – Selection
3 Control Statements:.
Web Programming– UFCFB Lecture 20
Chapter 4 - Program Control
Announcements/Reminders
Presentation transcript:

Introduction To Scientific Programming Chapter 3

S.Horton/107/Ch. 3Slide 2 Overview I.Program Control or “Flow” Tests A.Introduction to Boolean Variables and Expressions II.Program Control Structures A.Branches B.Loops III.Boolean Expressions Revisited IV.Programming with Control Strucutres A.Debugging program control & breaking out of loops B.Java Packages

S.Horton/107/Ch. 3Slide 3 What is Program Control or “Flow”? Program control is how the execution of a program’s instructions are handled. Programs can be written with three main control flow elements: 1. Sequence - just go to the next instruction 2. Branching or Selection – make a choice from two or more blocks to: either go to the next instruction or jump to some other instruction 3. Loop or Repetition - loop or repeat a block of code and then at the end of the loop: either go back and repeat the block of code or continue with the next instruction after the block

S.Horton/107/Ch. 3Slide 4 Introduction - Java Control Statements By default, Java automatically executes the next instruction unless you use a control (branching or looping) statement. Basic control statements are: Branching if if-else if-else if-else if- … - else switch Loop while do-while for

S.Horton/107/Ch. 3Slide 5 I. Boolean Variables and Expressions Branching allows for more than one choice when executing the next instruction or block of code. Which branch is taken depends on a test condition which evaluates to either true or false. In general, if the test is true then one block is executed, otherwise if it is false, another code block is executed. Variables or expressions that are either true or false are called boolean variables (or expressions). So, the value of a boolean variable (or expression) is always either true or false.

S.Horton/107/Ch. 3Slide 6 More On Boolean Expressions Often, boolean expressions are simply the comparison of two values. Example: Is A greater than B? Is A equal to B? Is A less than or equal to B? … A and B can be any data type (or class), but they should be the same data type (or class).

S.Horton/107/Ch. 3Slide 7 Java Comparison Operators

S.Horton/107/Ch. 3Slide 8 II-A. Branching – The Java if Statement Simplest version is selection Do the next statement if test is true or skip if false Syntax: if (Boolean_Expression) Action; //execute only if true next action; //always executed Note the indentation for readability (not needed to compile or execute).

S.Horton/107/Ch. 3Slide 9 if Example The body of the if statement is conditionally executed. Statements after the body of the if statement always execute. if (eggsPerBasket < 12) { System.out.println(“Less than a dozen eggs per basket”); } totalEggs = numberOfEggs * eggsPerBasket; System.out.println(“You have a total of” + totalEggs + “eggs.”);

S.Horton/107/Ch. 3Slide 10 Two-way Selection: if-else Select either one of two options Either do Action1 or Action2, depending on the test value Syntax: if (Boolean_Expression) { Action1; //execute only if true } else { Action2;//execute only if false } Action3;//always executed

S.Horton/107/Ch. 3Slide 11 if-else Examples Example with single-statement blocks: if (time < limit) System.out.println(“You made it.”); else System.out.println(“You missed the deadline.”); Example with compound statements: if (time < limit) { System.out.println(“You made it.”); bonus = 100; } else { System.out.println(“You missed the deadline.”); bonus = 0; }

S.Horton/107/Ch. 3Slide 12 Nested if Statements One if statement can have another if statement inside it. These are called nested if statements. Inner statements are indented more than outer statements. if (balance >= 0) if (RATE >= 0) balance = balance + (RATE * balance)/12; else System.out.println("Cannot have negative rate"); else balance = balance – OVERDRAWN_PENALTY; inner statement outer statement The inner if statement will be skipped entirely if balance >= 0 is false.

S.Horton/107/Ch. 3Slide 13 Multibranch Selection: if-else if-else if-…-else One way to handle situations with more than two possibilities Syntax: if (Boolean_Expression_1) Action_1; else if (Boolean_Expression_2) Action_2;. else if (Boolean_Expression_n) Action_n; else Default_Action;

S.Horton/107/Ch. 3Slide 14 if-else if-else if-…- else Example if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = ‘F'; Note the code indentation. Even though these are nested if statements, they are all indented the same amount to indicate a multibranch selection.

S.Horton/107/Ch. 3Slide 15 More Multibranch Selection: The Java switch Statement Another multibranch technique Uses Control_Expression to decide which way to branch Control_Expression must be char, ant, short or byte. Control_Expression and Case_Label must be same type. When a break statement is encountered, control goes to the first statement after the switch. The break may be omitted. switch can have any number of cases and the default case is optional. switch(Control_Expression) { case Case_Label1: statements … break; case Case_Label2: statements … break; default: statements … break; }

S.Horton/107/Ch. 3Slide 16 switch Example switch(seatLocationCode) { case 1: System.out.println(“Orchestra”); price = 40.00; break; case 2: System.out.println(“Mezzanine”); price = 30.00; break; case 3: System.out.println(“Balcony”); price = 15.00; break; default: System.out.println(“Unknown seat code”); break; } Output if seatLocationCode is 2: Mezzanine

S.Horton/107/Ch. 3Slide 17 II-B. Looping Structure: Usually some initialization code body of loop Sometimes loop termination check Several logical control possibilities! counting loops “sentinel-controlled” loops infinite loops minimum of zero or minimum of one iteration

S.Horton/107/Ch. 3Slide 18 while Loop Syntax: while(Boolean_Expression) { First_Statement;... Last_Statement; } Initialization statements usually precede the loop. Boolean_Expression is the loop termination condition. The loop will continue executing as long as Boolean_Expression is true. May be either counting or sentinel loop. Something in body of loop needs to cause Boolean_Expression to eventually be false.

S.Horton/107/Ch. 3Slide 19 Structure of the while Statement while (Boolean_Expression) Body Start Evaluate Boolean_Expression End loop false Execute Body true

S.Horton/107/Ch. 3Slide 20 while : A Counting Loop Example A loop to sum 10 numbers entered by user int next; //Loop initialization int count = 1; int total = 0; while (count <= 10)//Loop termination condition { next = SavitchIn.readLineInt(); total = total + next; count++; //Loop termination counter }

S.Horton/107/Ch. 3Slide 21 while : A “Sentinel-Controlled” Loop Example A loop to sum positive integers entered by the user next is the sentinel The loop terminates when the user enters a negative number. This allows for a variable amount of input! //Initialization int next = 0; int total = 0; while (next >= 0) //Termination condition { total = total + next; next = SavitchIn.readLineInt(); }

S.Horton/107/Ch. 3Slide 22 Note: while Loops Can Have Zero Iterations Because the first input value read and the test precedes the loop, the body of the while loop may not execute at all //Initialization int next; int total = 0; next = SavitchIn.readLineInt(); while (next >= 0) //Termination condition { total = total + next; next = SavitchIn.readLineInt(); } If the first number the user enters is negative the loop body never executes

S.Horton/107/Ch. 3Slide 23 do-while Loop Syntax do { First_Statement;... Last_Statement; } while(Boolean_Expression); Initialization code may precede loop body Loop test is after loop body so the body must execute at least once (minimum of at least one iteration) May be either counting or sentinel loop Something in body of loop should eventually cause Boolean_Expression to be false.

S.Horton/107/Ch. 3Slide 24 Structure of the do-while Statement do Body while(Boolean_Expression); Start Evaluate Boolean_Expression End loop false Execute Body true Execute Body

S.Horton/107/Ch. 3Slide 25 do-while Example //Initialization int count = 1; int number = 5; //Display integers 1 to 5 on one line do { System.out.print(count + " "); count++; } while (count <= number); Output:

S.Horton/107/Ch. 3Slide 26 for Loop Best choice for a counting loop and very flexible Initialization, loop test, and loop counter change are part of the syntax Syntax: for (Initialization; Boolean_Expression; Update_Action) loop body;

S.Horton/107/Ch. 3Slide 27 Structure of the for Statement for (Initialization; Boolean_Expression; Update_Action) loop body; Start Evaluate Boolean_Expression End loop false Execute Body true Execute Initialization Execute Update_Action //Display integers 1 to 5 on one line

S.Horton/107/Ch. 3Slide 28 for Example Count down from 3 to 1 for (int count = 3; count >= 1; count--) { System.out.print("T = " + count); System.out.println(" and counting"); } System.out.println("Blast off!"); Output: T = 3 and counting T = 2 and counting T = 1 and counting Blast off!

S.Horton/107/Ch. 3Slide 29 More Nested Loops The body of a loop can have any kind of statements, including another loop. Each time the outer loop body is executed, the inner loop body will execute 5 times, making a total of 20 times! for (line = 0; line < 4; line++) for (star = 0; star < 5; star++) System.out.print('*'); System.out.println(); body of inner loop body of outer loop Output: *****

S.Horton/107/Ch. 3Slide 30 III. Boolean Revisited - Compound Boolean Expressions Many times, one needs to evaluate multiple (compound) boolean expressions to make a decision Use && to AND two or more conditions (i.e. A && B) Expression will be true if both parts are true. Use || to OR two or more conditions (i.e. A || B) Expression will be true if either part is true, or if both parts are true. Example: write a test to see if B is either 0 or between (exclusive) the values of A and C (B == 0) || ((B > A) && (B < C))

S.Horton/107/Ch. 3Slide 31 Truth Tables for boolean Operators Value of AValue of BA && B truetruetrue truefalsefalse falsetruefalse falsefalsefalse Value of AValue of BA || B truetruetrue truefalsetrue falsetruetrue falsefalsefalse Value of A!A truefalse falsetrue && (and)|| (or) ! (not)

S.Horton/107/Ch. 3Slide 32 Highest Precedence First: the unary operators: +, -, ++, --, and ! Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, - Fourth: the boolean operators:, = = Fifth: the boolean operators: ==, != Sixth: the boolean operator & Seventh: the boolean operator | Eighth: the boolean operator && Ninth: the boolean operator || Lowest Precedence  Hint: Always Use Parenthesis To Force Explicit Evaluation! Precedence Rules – Updated!

S.Horton/107/Ch. 3Slide 33 Short-circuit evaluation evaluates only as much of a boolean expression as necessary. Example: If assign > 0 is false, then the complete expression cannot be true because AND is only true if both operands are true. Java will not evaluate the second part of the expression. Short-circuit evaluation prevents a divide-by-zero exception when assign is 0. Use a single & or | to force full evaluation. if ((assign > 0) && ((total/assign) > 60)) System.out.println(“Good work”); else System.out.println(“Work harder.”); Short-Circuit Evaluation

S.Horton/107/Ch. 3Slide 34 IV. Programming With Control Structures The most common loop errors are unintended infinite loops and off-by-one errors in counting loops. Sooner or later everyone writes an infinite loop To get out of an infinite loop enter ^C (control-C) Loops should be tested thoroughly, especially at the boundaries of the loop test, to check for off-by-one or uninitialization errors.

S.Horton/107/Ch. 3Slide 35 Tracing a Variable in a Loop Tracing a variable: print out the variable each time through the loop A common technique is to test loop counters and troubleshoot off-by-one and other loop errors. Some systems provide a built-in “debugging” system that allows you to trace a variable without having to change your program (JCreator PRO: Build-Start Debugger). If no built-in utility is available, insert temporary output statements to print values.

S.Horton/107/Ch. 3Slide 36 Control Interruption - The exit Method If you have a program situation where it is pointless to continue execution you can terminate the program with the exit(n) method. n is often used to identify if the program ended normally or abnormally. n is conventionally 0 for normal termination and non-zero for abnormal termination. In some circumstances, you will need to stop a loop but want to continue on with program - use break

S.Horton/107/Ch. 3Slide 37 exit Method Example System.out.println("Enter e to exit or c to continue"); char userIn = SavitchInReadLineChar(); if(userIn == 'e') System.exit(0); else if(userIn == 'c') { //statements to do work } else { System.out.println("Invalid entry"); //statements to something appropriate }

S.Horton/107/Ch. 3Slide 38 Boolean Comparison Methods for String Class (Or Any Object) “==“ does not do what you may think for String objects When “==“ is used to test objects (such as String objects) it tests to see if the storage addresses of the two objects are the same – i.e. location More on this later Use “.equals” method to test if the strings are equal String s1 = “Yes”,s2; boolean goAhead; s2 = SavitchIn.readLine(); goAhead = s1.equals(s2); returns true if the user enters Yes, false otherwise.equals() is case sensitive! Use.equalsIgnoreCase() to ignore case

S.Horton/107/Ch. 3Slide 39 One More Note On String Comparisons - Alphabetical Ordering Use compareTo method of String class for ordering Uses ASCII lexicographic ordering where all uppercase letters come before all lowercase letters For example capital 'Z' comes before small 'a' Convert strings to all uppercase (or all lowercase) to avoid problems s1.compareTo(s2) returns a negative value if s1 comes before s2 returns zero if the two strings are equal returns a positive value if s2 comes before s1

S.Horton/107/Ch. 3Slide 40 boolean Variables in Assignments A boolean expression evaluates to one of the two values true or false. The value of a boolean expression can be assigned to a boolean variable: There are simpler ways to write this code segment, but in general boolean variables are very useful in keeping track of conditions that depend on a number of factors. int fuel = -5; boolean systemsAreOK; systemsAreOK = (fuel > 0); if (systemsAreOK) System.out.println("Initiate launch sequence."); else System.out.println("Abort launching sequence");

S.Horton/107/Ch. 3Slide 41 IV-B. Java Packages Java contains many Classes and Methods to help you get the job done. These are grouped into “Packages”. If not automatically loaded, you must use import at the beginning of your code. Example: import java.math.*; Warning – do not excessively add packages when you do not need them. They will increase program size.