1 CSCE 1030 Computer Science 1 Control Statements in Java.

Slides:



Advertisements
Similar presentations
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
Advertisements

 2002 Prentice Hall. All rights reserved Control Structures 3 control structures –Sequential structure Built into Python –Selection structure The.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part I.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Structured Program Development in C
 2002 Prentice Hall. All rights reserved. 1 Chapter 3 – Control Structures Outline 3.1 Introduction 3.2 Algorithms 3.3 Pseudocode 3.4Control Structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Chapter 4 Control Statements: Part I
The University of Texas – Pan American
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
1 Control Statements: Part I Chapter 4 Control Statements: Part I Chapter 4.
 2003 Prentice Hall, Inc. All rights reserved. 1 Control Structures Outline -Introduction -Algorithms -Pseudocode -Control Structures -if Selection Structure.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
C++ How to Program, Late Objects Version, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved. 1.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Control Statements: Part1  if, if…else, switch 1.
 2005 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter 7 JavaScript: Control Statements, Part 1
Introduction to Computer Programming
Control Statements: Part 1
Control Statements: Part 2
JavaScript: Control Statements I
Chapter 4 – Control Structures Part 1
JavaScript: Control Statements.
Chapter 5- part 2 Control Statements: Loops 2
MSIS 655 Advanced Business Applications Programming
Advanced Programming Chapters 5 & 6: Control Structures
3 Control Statements:.
Chapter 6 Control Statements: Part 2
Control Statements:.
Presentation transcript:

1 CSCE 1030 Computer Science 1 Control Statements in Java

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 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 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 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 if statement if (condition) { statement(s) if condition is true } if (StudentGrade < 60) { letterGrade=‘F’; System.out.println(“Student has failed”); } Prototype

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 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 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 if... else statement – cont’d Empty statements Put a semicolon ( ; ) in place of a statement Can replace an if body

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 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 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  2005 Pearson Education, Inc. All rights reserved.

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

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 default case for grade less than 60  2005 Pearson Education, Inc. All rights reserved.

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

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

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

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 Loop 10 times Exit for statement ( break ) when count equals 5  2005 Pearson Education, Inc. All rights reserved.

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

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 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 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 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 Outline Assign a value to instance variable courseName Declare method setCourseName Declare method getCourseName  2005 Pearson Education, Inc. All rights reserved.

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 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 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 Integer division Division of two integer operands yield a truncated integer result 12 / 5 = 2 63 / 6 = / 2 = 8

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 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 Outline Assign a value to instance variable courseName Declare method setCourseName Declare method getCourseName  2005 Pearson Education, Inc. All rights reserved.

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 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 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 Type Casting Explicit conversion Performed by user with unary cast operator Implicit conversion (promotion) Done by Java

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 do…while Repetition Statement First executes the body loop, then tests the loop condition

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

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 The for loop as a while loop for (initialization; loopContinuationCondition; increment ) statement; is the same as initialization; while ( loopContinuationCondition ) { statement; increment; }

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 increment number by 2 each iteration  2005 Pearson Education, Inc. All rights reserved.

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 Calculate amount with for statement  2005 Pearson Education, Inc. All rights reserved.

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 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 Fig | Pseudocode for examination-results problem.  2005 Pearson Education, Inc. All rights reserved.

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

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 Outline Create an Analysis object More than 8 students passed the exam  2005 Pearson Education, Inc. All rights reserved.

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 Fig | Arithmetic compound assignment operators.  2005 Pearson Education, Inc. All rights reserved.

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 Fig | Precedence and associativity of the operators discussed so far.  2005 Pearson Education, Inc. All rights reserved.

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 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 Fig | && (conditional AND) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

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 Fig | || (conditional OR) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

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 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 Fig | ^ (boolean logical exclusive OR) operator truth table.  2005 Pearson Education, Inc. All rights reserved.

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

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

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  2005 Pearson Education, Inc. All rights reserved.

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

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”