Control Structures Corresponds with Chapters 3 and 4.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
Advertisements

Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 5 Control Statements.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 4 Program Control Statements
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Chapter 05 (Part III) Control Statements: Part II.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 3 Control Statements F Selection Statements –Using if and if...else –Nested if Statements –Using switch Statements –Conditional Operator F Repetition.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
COMP Loop Statements Yi Hong May 21, 2015.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.1 Chapter 3 Selections.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Control Structures Lecture 3 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Introduction to Control Statements IT108 George Mason University.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Chapter 3 Control Statements
Selections Java.
The switch Statement, and Introduction to Looping
Chapter 4: Making Decisions.
Control Structures.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Making Decisions.
Chapter 5 Control Statements
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Outline Altering flow of control Boolean expressions
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 3 Control Statements
Presentation transcript:

Control Structures Corresponds with Chapters 3 and 4

Control Statements Decisions (selections) Decisions (selections) if statements if statements switch statements switch statements Iterations (repetitions) Iterations (repetitions) for loops (enumerated) for loops (enumerated) while loops (top-tested) while loops (top-tested) do while loops (bottom-tested) do while loops (bottom-tested)

if Statement if (booleanExpression) single statement; single statement; Evaluates to true or false Must be enclosed in parentheses. Remember to indent the subordinate statement

if Statement if (booleanExpression) { statement1; statement2; … statementn; } If you have multiple subordinate statements, these must be a block enclosed in braces.

if flowchart Boolean test Subordinate statement(s) Independent statement(s) true false

Example: if (i >= 0 && i = 0 && i <= 10) System.out.println("i is an System.out.println("i is an integer between 0 and 10"); integer between 0 and 10"); boolean value Statement executes only if both conditions are true

The if...else Statement if (booleanExpression) { statement(s)-for-the-true-case; statement(s)-for-the-true-case;}else{ statement(s)-for-the-false-case; statement(s)-for-the-false-case;} Note: blocks with braces are necessary when there are multiple subordinate statements. They are optional when there is a single subordinate statement.

if-- else flowchart Boolean test statement(s) subordinate to if Independent statement(s) true false statement(s) subordinate to else

if...else Example if (radius >= 0) { area = radius*radius*PI; area = radius*radius*PI; System.out.println("The area for the " System.out.println("The area for the " + "circle of radius " + radius + " is" + "circle of radius " + radius + " is" + area); + area);}else System.out.println("Negative input"); System.out.println("Negative input"); The if branch statement must be in a block because there are two of them. There is only one else-branch statement. It does not need to be in a block, but you can if you want.

Nested if Statements This is true indentation for the nesting… inner ifs are nested within else of previous if statement. This has the same effect, but is more readable. Unlike VB, there is no ElseIf clause in Java, but the else if lines make it look like a VB ElseIf. Similar idea to figure 3.3 p76

FlowChart for if – else if -- else Boolean test statement(s) subordinate to if Independent statement(s) true false statement(s) subordinate to elseif Boolean test false statement(s) subordinate to else true

Nesting an if - else inside the if portion if (boolean expression1) if (boolean expression2) statement1;elsestatement2; The nested if-else. NOTE: an else is always associated with the most recent if. This else is the result of boolean expression2, not boolean expression1.

FlowChart for if with nested if -- else Boolean test1 Independent statement(s) false true statement1 subordinate to success on boolean test2. Therefore both tests succeeded. Boolean test2 false true statement2 subordinate to success on boolean test2. Therefore test1 succeeded and test2 failed.

Outer if-else with a nested if (no inner else) if (boolean expression1){ if (boolean expression2) statement1;}elsestatement2; The nested if. NOTE: here, because of the braces, the else is associated with the if for boolean expression #1.

FlowChart for if -else with nested if Boolean test1 Independent statement(s) false statement1 subordinate to success on boolean test2. Therefore both tests succeeded. Boolean test2 false true statement2 subordinate to failure of boolean test1 (the outer else). true

Shortcut if Statements if (x > 0) y = 1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1; test if Returned if true else Returned if false

switch Statements switch (switch-expression) { case value1: case value1: statement(s) 1; break; case value2: case value2: statement(s) 2; break; … case valueN: interestRate = 9.0; case valueN: interestRate = 9.0; statement(s) N; break; default: default: statement(s) for default; } switch-expression can evaluate to char, byte, short, or int. break causes control to skip past the end of the switch block. Without break, control would fall through to the next case. No break needed for last condition

switch Statements switch (status) { case 0: compute taxes for single filers; case 0: compute taxes for single filers; break; break; case 1: compute taxes for married file jointly; case 1: compute taxes for married file jointly; break; break; case 2: compute taxes for married file separately; case 2: compute taxes for married file separately; break; break; case 3: compute taxes for head of household; case 3: compute taxes for head of household; break; break; default: System.out.println("Errors: invalid status"); default: System.out.println("Errors: invalid status"); System.exit(0); System.exit(0);}

switch Statement Flow Chart

Equivalent if statement if (status == 0) compute tax for single filers; else if (status == 1) compute tax for married filing jointly; compute tax for married filing jointly; else if (status == 2) compute tax for married filing separately; compute tax for married filing separately; else if (status == 3) compute tax for head of household; compute tax for head of household;else{System.out.println( ("Errors: invalid status"); ("Errors: invalid status");System.exit(0);}

Exercise if (a==1) x += 6; else if (a == 2) x += 10; else if (a == 3) x += 16; else if (a == 4) x += 34; Convert this if statement into a switch statement

while Loops while (continue-condition) { // loop-body; // loop-body;} Top-tested loop Test before performing statements of loop Loop body may never execute

Listing 4.4 p109 – User Decides when to quit Initial data input – before the loop Subsequent data inputs – toward the end of the loop body

Do-while Loops do{ //loop body; //loop body; } while (continue-condition) Bottom-tested loop Perform statements of loop before testing Always enter the loop body at least once

Listing 4.5 – a Do-While Loop Test is at the bottom

for Loops for (control variable initialization; continue-test; adjustment-statement) continue-test; adjustment-statement){ //loop body; //loop body;} 1) assignment statement 2) boolean expression 3) assignment statement 1)Set initial value for loop counter (only once, before looping starts) 2)Test loop counter (also called control variable) to see if it is less than the max loop allowed (before executing loop body) 3)Increment loop counter (after executing loop body) (usually an increment operator).

for Loop Flow Chart

for Loop Example: int i; for (i = 0; i<100; i++) { System.out.println(“Hi. i is:” + i); System.out.println(“Hi. i is:” + i);} Here, the loop counter variable (called i ) is available for use outside the loop.

Alternative Syntax: Declare Loop Counter in Initialization for (int i = 0; i<100; i++) { System.out.println(“Hi. i is:” + i); System.out.println(“Hi. i is:” + i);} Here, the loop counter variable (called i ) is available for use only within the loop.

The Nested for Loop for (int i=0; i<outerLoopLimit;i++){ outer loop statement(s); for (int j=0;j<innerLoopLimit;j++){ inner loop statement(s); } outer loop statement(s); } Body of outer loop Body of inner loop Body of outer loop will execute outerLoopLimit times Body of inner loop will execute innerLoopLimit times for each time the outer loop body executes.  Total innerLoopLimit * outerLoopLimit times!

Initialize outer loop counter Initialize inner loop counter Test to continue outer loop Test to continue inner loop Outer loop statement(s) Inner loop statement(s) Increment outer loop counter Increment inner loop counter Statements preceding loop Statements following loop No Yes The Nested for Loop -- Flowchart

Nested Loop Example (my example) Outer loop Inner loop

Example Program Run

A couple points about the example Max loop count value can be any numeric expression. Here it’s a variable Special escape character \t for tab.

Reminders about packages from the example The class NestedForLoop is in the package called controlStructurePackage. Therefore, there is a file called NestedForLoop.class in a folder called controlStructurePackage.

Reminders about packages from the example In order to use a class from outside your own package, you must import the package that the class is contained in. Here, we import the JOptionPane class from the javax.swing package.

Another Example -- listing 4.6 p115

Listing 4.6 Loop with single statement in body

Listing 4.6 An if statement nested inside a for loop, which is itself nested in another for loop.

Listing 4.6 At the end, the string is displayed in the output screen Note: actions in the loops are concatenating values into the string output.

Listing 4.6 program analysis Question 1: how many times will outer loop body execute? Question 2: how many times will inner loop body execute? Question 3: how many times will IF branch execute?

The break Keyword break can be used to terminate the loop based on decisions inside the loop body.

Listing 4.11 Using the break keyword Question: how many times will this loop body execute? What will be the value in sum?

The continue Keyword continue can be used to branch to the top of the loop (skipping statements in loop body) based on decisions inside the loop body.

Listing 4.12 Using the continue keyword Question 1: how many times will this loop body execute? Question 2: how many times sum += number; execute?

Typical Nested Structure: Decision within a Loop (menu-driven as first statement in loop) User wants to quit? User choice 1? Present menu options to user Input User Choice Choice 1 statement(s) Statements following loop No Yes User choice n? Choice n statement(s) Yes No

A Java Implementation This implementation nests a switch inside a while loop. Exercise: Do the same thing by nesting an if statement inside a do- while loop.

Other Useful Examples Listing 4.8: finding the greatest common divisor (while loop with nested if statement) Listing 4.8: finding the greatest common divisor (while loop with nested if statement) Listing 4.9: finding a sales amount (do-while loop with nested if - else if - else statement) Listing 4.9: finding a sales amount (do-while loop with nested if - else if - else statement) Listing 4.10: printing a pyramid (outer for loop with three nested for loops inside it) Listing 4.10: printing a pyramid (outer for loop with three nested for loops inside it) Listing 4.14: finding prime numbers (outer while loop with nested for loop with nested if statement) Listing 4.14: finding prime numbers (outer while loop with nested for loop with nested if statement)