Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction To Scientific Programming Chapter 3.

Similar presentations


Presentation on theme: "Introduction To Scientific Programming Chapter 3."— Presentation transcript:

1 Introduction To Scientific Programming Chapter 3

2 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

3 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

4 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

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

6 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).

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

8 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).

9 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.”);

10 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

11 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; }

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

13 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;

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

15 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; }

16 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

17 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

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

19 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

20 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 }

21 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(); }

22 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

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

24 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

25 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: 1 2 3 4 5

26 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;

27 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

28 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!

29 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: *****

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

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

32 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!

33 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

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

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

36 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

37 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 }

38 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

39 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

40 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");

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


Download ppt "Introduction To Scientific Programming Chapter 3."

Similar presentations


Ads by Google