Introduction To Scientific Programming Chapter 3 Overview I

  • Slides: 41
Download presentation
Introduction To Scientific Programming Chapter 3

Introduction To Scientific Programming Chapter 3

Overview I. Program Control or “Flow” Tests A. II. Introduction to Boolean Variables and

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

What is Program Control or “Flow”? l Program control is how the execution of

What is Program Control or “Flow”? l Program control is how the execution of a program’s instructions are handled. l 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: l l 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: l l S. Horton/107/Ch. 3 either go back and repeat the block of code or continue with the next instruction after the block 3

Introduction - Java Control Statements l By default, Java automatically executes the next instruction

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

I. Boolean Variables and Expressions l Branching allows for more than one choice when

I. Boolean Variables and Expressions l Branching allows for more than one choice when executing the next instruction or block of code. l 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. l Variables or expressions that are either true or false are called boolean variables (or expressions). l So, the value of a boolean variable (or expression) is always either true or false. S. Horton/107/Ch. 3 5

More On Boolean Expressions l Often, boolean expressions are simply the comparison of two

More On Boolean Expressions l Often, boolean expressions are simply the comparison of two values. l Example: l l l 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. 3 6

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

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

II-A. Branching – The Java if Statement l Simplest version is selection l Do

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

if Example l The body of the if statement is conditionally executed. l Statements

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

Two-way Selection: if-else l Select either one of two options l Either do Action

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

if-else Examples l Example with single-statement blocks: if (time < limit) System. out. println(“You

if-else Examples l Example with single-statement blocks: if (time < limit) System. out. println(“You made it. ”); else System. out. println(“You missed the deadline. ”); l 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. 3 11

Nested if Statements l One if statement can have another if statement inside it.

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

Multibranch Selection: if-else if-…-else l One way to handle situations with more than two

Multibranch Selection: if-else if-…-else l One way to handle situations with more than two possibilities l 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. 3 13

if-else if-…else Example if (score >= 90) grade = 'A'; else if (score >=

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'; S. Horton/107/Ch. 3 Note the code indentation. Even though these are nested if statements, they are all indented the same amount to indicate a multibranch selection. 14

More Multibranch Selection: The Java switch Statement switch(Control_Expression) { case Case_Label 1: statements …

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

switch Example switch(seat. Location. Code) { case 1: System. out. println(“Orchestra”); price = 40.

switch Example switch(seat. Location. Code) { 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 seat. Location. Code is 2: Mezzanine S. Horton/107/Ch. 3 16

II-B. Looping l Structure: l l Usually some initialization code body of loop Sometimes

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

while Loop l Syntax: while(Boolean_Expression) { First_Statement; . . . Last_Statement; } Something in

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

Structure of the while Statement while (Boolean_Expression) Body Start Evaluate Boolean_Expression true Execute Body

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

while: A Counting Loop Example l A loop to sum 10 numbers entered by

while: A Counting Loop Example l 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 = Savitch. In. read. Line. Int(); total = total + next; count++; //Loop termination counter } S. Horton/107/Ch. 3 20

while: A “Sentinel-Controlled” Loop Example l A loop to sum positive integers entered by

while: A “Sentinel-Controlled” Loop Example l A loop to sum positive integers entered by the user l next is the sentinel l 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 = Savitch. In. read. Line. Int(); } S. Horton/107/Ch. 3 21

Note: while Loops Can Have Zero Iterations l Because the first input value read

Note: while Loops Can Have Zero Iterations l 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 = Savitch. In. read. Line. Int(); while (next >= 0) //Termination condition { total = total + next; next = Savitch. In. read. Line. Int(); } l If the first number the user enters is negative the loop body never executes S. Horton/107/Ch. 3 22

do-while Loop l Syntax do { First_Statement; . . . Last_Statement; } while(Boolean_Expression); Something

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

Structure of the do-while Statement do Body while(Boolean_Expression); Start Execute Body Evaluate Boolean_Expression true

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

do-while Example //Initialization int count = 1; int number = 5; //Display integers 1

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

for Loop l Best choice for a counting loop and very flexible l Initialization,

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

Structure of the for Statement for (Initialization; Boolean_Expression; Update_Action) loop body; Start Execute Initialization

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

for Example l Count down from 3 to 1 for (int count = 3;

for Example l 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: S. Horton/107/Ch. 3 T = 2 T = 1 Blast and counting off! 28

More Nested Loops l The body of a loop can have any kind of

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

III. Boolean Revisited - Compound Boolean Expressions l Many times, one needs to evaluate

III. Boolean Revisited - Compound Boolean Expressions l Many times, one needs to evaluate multiple (compound) boolean expressions to make a decision l Use && to AND two or more conditions (i. e. A && B) l l Use || to OR two or more conditions (i. e. A || B) l l Expression will be true if both parts are true. 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. 3 30

Truth Tables for boolean Operators && (and) Value of A Value of B ||

Truth Tables for boolean Operators && (and) Value of A Value of B || (or) A && B Value of A Value of B A || B true true false true false true false false ! (not) S. Horton/107/Ch. 3 Value of A !A true false true 31

Precedence Rules – Updated! Highest Precedence l First: the unary operators: +, -, ++,

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

Short-Circuit Evaluation l Short-circuit evaluation evaluates only as much of a boolean expression as

Short-Circuit Evaluation l Short-circuit evaluation evaluates only as much of a boolean expression as necessary. l Example: if ((assign > 0) && ((total/assign) > 60)) System. out. println(“Good work”); else System. out. println(“Work harder. ”); l 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. l Short-circuit evaluation prevents a divide-by-zero exception when assign is 0. l Use a single & or | to force full evaluation. S. Horton/107/Ch. 3 33

IV. Programming With Control Structures l The most common loop errors are unintended infinite

IV. Programming With Control Structures l The most common loop errors are unintended infinite loops and off-by-one errors in counting loops. l Sooner or later everyone writes an infinite loop l l 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. 3 34

Tracing a Variable in a Loop l Tracing a variable: print out the variable

Tracing a Variable in a Loop l Tracing a variable: print out the variable each time through the loop l A common technique is to test loop counters and troubleshoot off-by-one and other loop errors. l 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). l If no built-in utility is available, insert temporary output statements to print values. S. Horton/107/Ch. 3 35

Control Interruption - The exit Method l If you have a program situation where

Control Interruption - The exit Method l If you have a program situation where it is pointless to continue execution you can terminate the program with the exit(n) method. l 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. l In some circumstances, you will need to stop a loop but want to continue on with program - use break S. Horton/107/Ch. 3 36

exit Method Example System. out. println("Enter e to exit or c to continue"); char

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

Boolean Comparison Methods for String Class (Or Any Object) l “==“ does not do

Boolean Comparison Methods for String Class (Or Any Object) l “==“ does not do what you may think for String objects l 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 l l More on this later Use “. equals” method to test if the strings are equal String s 1 = “Yes”, s 2; boolean go. Ahead; s 2 = Savitch. In. read. Line(); go. Ahead = s 1. equals(s 2); l returns true if the user enters Yes, false otherwise l . equals()is case sensitive! l Use. equals. Ignore. Case()to ignore case S. Horton/107/Ch. 3 38

One More Note On String Comparisons - Alphabetical Ordering l Use compare. To method

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

boolean Variables in Assignments l A boolean expression evaluates to one of the two

boolean Variables in Assignments l A boolean expression evaluates to one of the two values true or false. l The value of a boolean expression can be assigned to a boolean variable: int fuel = -5; boolean systems. Are. OK; systems. Are. OK = (fuel > 0); if (systems. Are. OK) System. out. println("Initiate launch sequence. "); else System. out. println("Abort launching sequence"); l 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. S. Horton/107/Ch. 3 40

IV-B. Java Packages l Java contains many Classes and Methods to help you get

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