Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CSCE 1030 Computer Science 1 Control Statements in Java.

Similar presentations


Presentation on theme: "1 CSCE 1030 Computer Science 1 Control Statements in Java."— Presentation transcript:

1 1 CSCE 1030 Computer Science 1 Control Statements in Java

2 2 Control Structures Sequential execution Statements are normally executed one after the other in the order in which they are written Transfer of control Branch to another statement out normal flow We not always need to execute the next statement in sequence Use goto statement Not a structured programming element

3 3 Control Structures – cont’d Selection Statements if statement Allows single-selection per if statement if…else statement Allows double-selection statement switch statement Allows multiple-selection

4 4 Control Structures – cont’d Repetition (Looping) statements Repeatedly executes action(s) while loop- continuation condition remains true while statement Loop body is executed zero or more times do…while statement Loop body is executed one or more times for statement Loop body is executed zero or more times

5 5 Top-Down, Stepwise Refinement Top step: Start with less detailed algorithmic solution usually one statement First refinement: Detail the solution into multiple statements which uses only the sequence structure yet more detailed Second refinement: Involve variables, and variety of control structures where necessary most detailed

6 6 if statement if (condition) { statement(s) if condition is true } if (StudentGrade < 60) { letterGrade=‘F’; System.out.println(“Student has failed”); } Prototype

7 7 if... else statement if (condition) { statement(s) if condition is true } else { statement(s) if condition is false } if (sex = ‘F’) { var1=“Madam”; System.out.println(“Good morning ” + var1); } else { var1=“Sir”; System.out.println(“Good morning ” + var1); }

8 8 if... else statement – cont’d Ternary operator ( ? : ) (takes 3 operands) Statement condition ? value if true : value if false; int a=10; int b=20; String result=a>b ? “a greater than b”:“a is less than b”; System.out.println(“The conclusion is: ” + result);

9 9 if... else statement – cont’d Nested if…else statements if…else block contains several if…else statements in if, in else or in both Blocks Braces { } associate statements into blocks Blocks can replace individual statements as an if body

10 10 if... else statement – cont’d Empty statements Put a semicolon ( ; ) in place of a statement Can replace an if body

11 11 Problems with if... else statement Dangling- else problem Each else should be preceded by an if Logic errors – not necessarily with if.. else only Fatal logic errors Program terminates before normal end Nonfatal logic errors Program yields incorrect results

12 12 switch Multiple-Selection Statement Allows multiple selections for cases where if.. else remains insufficient Provide a default case in switch statements. Also called a fall-through Don’t forget the break!

13 13 switch Multiple-Selection Statement – cont’d Expression in each case Integers Character constant E.g., ‘F’, ‘16’ or ‘#’ Constant variable Declared with keyword final

14 14  2005 Pearson Education, Inc. All rights reserved.

15 15  2005 Pearson Education, Inc. All rights reserved.

16 16 Loop condition uses method hasNext to determine whether there is more data to input switch statement determines which case label to execute, depending on controlling expression ( grade / 10 ) is controlling expression  2005 Pearson Education, Inc. All rights reserved.

17 17 default case for grade less than 60  2005 Pearson Education, Inc. All rights reserved.

18 18  2005 Pearson Education, Inc. All rights reserved.

19 19 Call GradeBook public methods to count grades  2005 Pearson Education, Inc. All rights reserved.

20 20  2005 Pearson Education, Inc. All rights reserved.

21 21 switch Multiple-Selection Statement – break and continue Statements break/continue Alter flow of control break statement Causes immediate exit from control structure Used in while, for, do…while or switch statements continue statement Skips remaining statements in loop body Proceeds to next iteration Used in while, for or do…while statements

22 22 Loop 10 times Exit for statement ( break ) when count equals 5  2005 Pearson Education, Inc. All rights reserved.

23 23 Loop 10 times Skip line 12 and proceed to line 7 when count equals 5  2005 Pearson Education, Inc. All rights reserved.

24 24 Repetition (Looping) statements - While while condition { statement 1; statement 2; } a=10, b=20; while (a < b) { System.out.println(“a=” + a + “ b=” + b; a=a*10; } This part is called the loop body

25 25 Counter Controlled Repetition Counter-controlled repetition requires: Control variable (loop counter): The variable which keeps track of the number of times a loop is iterated Initial value of the control variable Increment/decrement of control variable through each loop to make sure that loop eventually ends No indefinite loop Loop-continuation condition that tests for the final value of the control variable

26 26 Control-variable name is counter Control-variable initial value is 1 Condition tests for counter ’s final value Increment for counter A simple example with while loop  2005 Pearson Education, Inc. All rights reserved.

27 27 Fig. 4.5 | Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem. 1Set total to zero 2Set grade counter to one 3 4While grade counter is less than or equal to ten 5Prompt the user to enter the next grade 6Input the next grade 7Add the grade into the total 8Add one to the grade counter 9 10Set the class average to the total divided by ten 11Print the class average

28 28 Outline Assign a value to instance variable courseName Declare method setCourseName Declare method getCourseName  2005 Pearson Education, Inc. All rights reserved.

29 29 Outline Declare method displayMessage Declare method determineClassAverage Declare and initialize Scanner variable input Declare local int variables total, gradeCounter, grade and average  2005 Pearson Education, Inc. All rights reserved.

30 30 Outline while loop iterates as long as gradeCounter <= 10 Increment the counter variable gradeCounter Calculate average grade Display results  2005 Pearson Education, Inc. All rights reserved.

31 31 Outline Create a new GradeBook object Pass the course’s name to the GradeBook constructor as a string Call GradeBook ’s determineClassAverage method  2005 Pearson Education, Inc. All rights reserved.

32 32 Integer division Division of two integer operands yield a truncated integer result 12 / 5 = 2 63 / 6 = 10 17 / 2 = 8

33 33 Sentinel Controlled Repetition Also called indefinite repetition A sentinel value (aka signal, dummy or flag value) is used to indicate loop end This value is some value that is for sure will not occur as input value for the problem It is a good idea to let user know about the sentinel value when you get input to the program

34 34 Fig. 4.8 | Class-average problem pseudocode algorithm with sentinel-controlled repetition. 1Initialize total to zero 2Initialize counter to zero 3 4Prompt the user to enter the first grade 5Input the first grade (possibly the sentinel) 6 7While the user has not yet entered the sentinel 8Add this grade into the running total 9Add one to the grade counter 10Prompt the user to enter the next grade 11Input the next grade (possibly the sentinel) 12 13If the counter is not equal to zero 14Set the average to the total divided by the counter 15Print the average 16else 17Print “No grades were entered”  2005 Pearson Education, Inc. All rights reserved.

35 35 Outline Assign a value to instance variable courseName Declare method setCourseName Declare method getCourseName  2005 Pearson Education, Inc. All rights reserved.

36 36 Outline Declare method displayMessage Declare method determineClassAverage Declare and initialize Scanner variable input Declare local int variables total, gradeCounter and grade and double variable average  2005 Pearson Education, Inc. All rights reserved.

37 37 Outline while loop iterates as long as grade != the sentinel value, -1 Calculate average grade using (double) to perform explicit conversion Display average grade Display “No grades were entered” message  2005 Pearson Education, Inc. All rights reserved.

38 38 Outline Create a new GradeBook object Pass the course’s name to the GradeBook constructor as a string Call GradeBook ’s determineClassAverage method  2005 Pearson Education, Inc. All rights reserved.

39 39 Type Casting Explicit conversion Performed by user with unary cast operator Implicit conversion (promotion) Done by Java

40 40 Type Casting – cont’d In Fig. 4.9 line 72 average = total / gradeCounter; Although average was declared as double (line 45), the integer division above yields an integer value b/c both total and gradeCounter are integer variables To preserve the fraction in result, use unary cast operator via explicit conversion average = (double) total / gradeCounter; This converts the type of variable total to double temporarily Then, Java applies promotion (implicit conversion) to convert type of variable gradeCounter to double temporarily

41 41 do…while Repetition Statement First executes the body loop, then tests the loop condition

42 42 Variable counter ’s value is displayed before testing counter ’s final value  2005 Pearson Education, Inc. All rights reserved.

43 43 The for loop Fig. 5.3 | for statement header components. Not a comma! No semi-colon  2005 Pearson Education, Inc. All rights reserved.

44 44 The for loop as a while loop for (initialization; loopContinuationCondition; increment ) statement; is the same as initialization; while ( loopContinuationCondition ) { statement; increment; }

45 45 Examples Using the for Statement Varying control variable in for statement Vary control variable from 1 to 100 in increments of 1 for ( int i = 1; i <= 100; i++ ) Vary control variable from 100 to 1 in increments of –1 for ( int i = 100; i >= 1; i-- ) Vary control variable from 7 to 77 in increments of 7 for ( int i = 7; i <= 77; i += 7 ) Vary control variable from 20 to 2 in decrements of 2 for ( int i = 20; i >= 2; i -= 2 ) Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20 for ( int i = 2; i <= 20; i += 3 ) Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for ( int i = 99; i >= 0; i -= 11 )  2005 Pearson Education, Inc. All rights reserved.

46 46 increment number by 2 each iteration  2005 Pearson Education, Inc. All rights reserved.

47 47 Java treats floating-points as type double Second string is right justified and displayed with a field width of 20  2005 Pearson Education, Inc. All rights reserved.

48 48 Calculate amount with for statement  2005 Pearson Education, Inc. All rights reserved.

49 49 Control-variable name is counter Control-variable initial value is 1 Condition tests for counter ’s final value Increment for counter  2005 Pearson Education, Inc. All rights reserved.

50 50 Nested Control Statements Control statements Conditional operations ( if, if.. else, switch ) Iterative operations ( while, do..while, for ) may occur inside the body of other control statements

51 51 Fig. 4.11 | Pseudocode for examination-results problem.  2005 Pearson Education, Inc. All rights reserved.

52 52 Outline Declare processExamResults ’ local variables while loop iterates as long as studentCounter <= 10  2005 Pearson Education, Inc. All rights reserved.

53 53 Outline Determine whether this student passed or failed and increment the appropriate variable Determine whether more than eight students passed the exam  2005 Pearson Education, Inc. All rights reserved.

54 54 Outline Create an Analysis object More than 8 students passed the exam  2005 Pearson Education, Inc. All rights reserved.

55 55 Compound Assignment Operators variable = variable operator expression ; where operator is +, -, *, / or % is rewritten as: variable operator = expression ; myVar = myVar+ 7; can be written as myVar+= 7; Add 7 to the value in variable myVar and stores the result in variable myVar  2005 Pearson Education, Inc. All rights reserved.

56 56 Fig. 4.14 | Arithmetic compound assignment operators.  2005 Pearson Education, Inc. All rights reserved.

57 57 Increment and Decrement Operators Unary increment and decrement operators Unary increment operator ( ++ ) adds 1 to its operand Unary decrement operator ( -- ) subtracts 1 from its operand Prefix increment (and decrement) operator Change the value of the operand first Then execute the operation in which with the new value of the operand Postfix increment (and decrement) operator First use the current value of the operand in the expression in which the operation appears Then, change the value of the operand  2005 Pearson Education, Inc. All rights reserved.

58 58 Fig. 4.17 | Precedence and associativity of the operators discussed so far.  2005 Pearson Education, Inc. All rights reserved.

59 59 Logical Operators Logical operators Allows for forming more complex conditions Combines simple conditions Java logical operators && (conditional AND) || (conditional OR) & (boolean logical AND) | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT)  2005 Pearson Education, Inc. All rights reserved.

60 60 Logical Operators – cont’d Conditional AND ( && ) Operator Consider the following if statement if ( gender == FEMALE && age >= 65 ) ++seniorFemales; Combined condition is true if and only if both simple conditions are true Combined condition is false if either or both of the simple conditions are false  2005 Pearson Education, Inc. All rights reserved.

61 61 Fig. 5.14 | && (conditional AND) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

62 62 Logical Operators (Cont.) Conditional OR ( || ) Operator Consider the following if statement if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) System.out.println( “Student grade is A” ); Combined condition is true if either or both of the simple condition are true Combined condition is false if both of the simple conditions are false  2005 Pearson Education, Inc. All rights reserved.

63 63 Fig. 5.15 | || (conditional OR) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

64 64 Logical Operators (Cont.) Short-Circuit Evaluation of Complex Conditions Parts of an expression containing && or || operators are evaluated only until it is known whether the condition is true or false E.g., ( gender == FEMALE ) && ( age >= 65 ) Stops immediately if gender is not equal to FEMALE  2005 Pearson Education, Inc. All rights reserved.

65 65 Logical Operators (Cont.) Boolean Logical Exclusive OR ( ^ ) One of its operands is true and the other is false Evaluates to true Both operands are true or both are false Evaluates to false Logical Negation ( ! ) Operator Unary operator  2005 Pearson Education, Inc. All rights reserved.

66 66 Fig. 5.16 | ^ (boolean logical exclusive OR) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

67 67 Fig. 5.17 |! (logical negation, or logical NOT) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

68 68 Conditional AND truth tableConditional OR truth tableBoolean logical AND truth table  2005 Pearson Education, Inc. All rights reserved.

69 69 Boolean logical inclusive OR truth table Boolean logical exclusive OR truth table Logical negation truth table  2005 Pearson Education, Inc. All rights reserved.

70 70  2005 Pearson Education, Inc. All rights reserved.

71 71 Fig. 5.19 | Precedence/associativity of the operators discussed so far.  2005 Pearson Education, Inc. All rights reserved.

72 72 References H. M. Deitel, P. J. Deitel, ”Small JAVA How to Program 6th edition”, Pearson/Prentice Hall, 2005.”Small JAVA How to Program 6th edition”


Download ppt "1 CSCE 1030 Computer Science 1 Control Statements in Java."

Similar presentations


Ads by Google