1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Advertisements

Control Structures Corresponds with Chapters 3 and 4.
8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter4: Control Statements Part I.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Introduction to Computers and Programming Lecture 7:
Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
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.
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops –For For Reading for this Lecture, L&L, Part of 5.8.
CS1061: C Programming Lecture 8: Repetition A. O’Riordan, 2004.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
 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.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Java Programming: From the Ground Up
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 5 Loops.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Chapter 4: Control Structures II
 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.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
The for loop.
Introduction to Computers and Programming Lecture 7:
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
COMP Loop Statements Yi Hong May 21, 2015.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Chapter 4: Control Structures I
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Topics The if Statement The if-else Statement Comparing Strings
SELECTION STATEMENTS (1)
Chapter 4: Control Structures I
3 Control Statements:.
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Additional control structures
Selection Statements August 22, 2019 ICS102: The course.
Control Statements:.
Presentation transcript:

1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional operator Loops  while, do while, for, enhanced for Loops often use a programming idiom called autoincrement and autodecrement.

2 Control Structures Order of topics: compound while autoincrement and autodecrement if for do-while

3 Compound statement A compound statement is a group of statements that are executed sequentially, one following the other, from beginning to end { temp = x; x = y; y = temp; } Opening brace Closing brace A compound statement is often used with if’s, while’s etc. … to provide a group of statements to be executed repeatedly or conditionally.

4 Loops: while While statement executes a statement as long as some expression is true while ( logical expression ) statement

5 Loops: while How a while executes

6 Loops: while A logical expression is an expression that evaluates true or false. Suppose a, b, q, i, j are integers and found is boolean. Examples of logical expressions: while ( logical expression ) statement a < b a+5 >= q*3 a == b a != b found a < b || b < c found && i<100 i < 100 && j < 100 !found && i < 100 ! found

7 Loops: while Example 1 Page 70. Numbers0to9 displays the digits from 0 to 9 A code snippet: int count = 0; System.out.println("Numbers"); while ( count < 10 ){ System.out.println(count); count = count + 1; } Indented code Executed repeatedly until count is 10 Start of compound statement How can you modify this code to display numbers from 9 down to 0?

8 Loops: while Example 2 Page 72. DisplayDigits displays the digits of a positive number. A code snippet: while (number > 0){ int digit = number % 10; System.out.print("\t"+digit); number = number / 10; System.out.println("\t"+number); } Indented code Executed repeatedly as long as number > 0 Start of compound statement How can you modify this code to calculate the sum of an integer’s digits?

9 Loops: Nesting whiles A while can contain another while Example. Suppose we need to display a times table (See example 3 page 72)

10 Loops: Nesting whiles To produce a times table its best to use one loop inside another. We say one loop is nested inside the other loop. To begin with we will just produce a simple vertical listing of i, j, i*j where i varies from 1 to 4 and j varies from 1 to 4. Ultimately one wants a listing like that shown on previous slide. see Example 3 on page 74 … shown on next slide see Exercise 14 on page 77

11 Loops: Nesting whiles public class NestedWhiles { public static void main(String[] args) { int i, j; System.out.println("\ti\tj\ti*j"); // i takes on values 1,2,3,4 i = 1; while (i < 5){ j = 1; // j takes on values 1,2,3,4 while (j < 5){ System.out.println("\t"+i+"\t"+j+"\t"+(i*j)); j = j + 1; } i = i + 1; } System.out.println("program ended"); } a while nested inside another while For each value of i, j takes on values 1, 2, 3, 4

12 Loops: Nesting whiles Output from NestedWhiles Heading Note when i is 1 j takes on 1, 2, 3, 4 when i is 2 j takes on 1, 2, 3, 4 when i is 3 j takes on 1, 2, 3, 4 when i is 4 j takes on 1, 2, 3, 4

13 Loops and Autoincrement, Autodecrement statements such as n = n + 1; m = m - 1; are so common in programming that languages such as Java include special operators for this purpose called autoincrement and autodecrement

14 Autoincrement and Autodecrement n++; m--; and ++ n; --m; post-increment post-decrement pre-increment pre-decrement

15 Autoincrement and Autodecrement n++; ++ n; m--; --m; When autoincrement is used alone and not as part of a larger expression pre- and post- increment have the same effect … to increment the operand by 1. Similarily …. When autodecrement is used alone and not as part of a larger expression pre- and post- decrement have the same effect … to decrement the operand by 1.

16 ASIDE: for Autoincrement and Autodecrement ASIDE: autoincrement, autodecrement within an expression… post-increment and post-decrement: the operand’s value is used and then the operand’s value is incremented/ decremented pre-increment and pre-decrement: the operand’s value is incremented/ decremented and then the operand’s value is used // try this out // what is printed? int m = 1; int n = m++ + m++; System.out.println("m="+m); System.out.println("n="+n); // try this out // what is printed? int m = 1; int n = ++m + ++m; System.out.println("m="+m); System.out.println("n="+n);

17 Decision structures : the if statement An if statement is coded with a logical expression and either one statement (statement 1 ) or two statements (statement 1, statement 2 ) written according to syntax as: if ( logical expression) statement 1 else statement 2 We say the if is a decision structure … based on the outcome of evaluating the logical expression one of possibly two statements is executed. The else clause is optional

18 Decision structures : the if statement if ( logical expression) statement 1 else statement 2 When an if executes the logical expression is evaluated and : when the expression evaluates to true statement 1 executes, and then execution of program statements continue at the statement following the if ; when the logical expression evaluates to false statement 2 executes, and then execution of program statements continue at the statement following the if. The else clause is optional

19 Decision structures : the if statement Example. PositiveOrNot page 79 Gets a number from the user and displays positive or not positive accordingly int number = keyboard.nextInt(); System.out.print("the number "+number+" is "); // Display a message if number is positive or not if (number > 0) { System.out.println("positive"); } else { System.out.println("not positive"); } Only one of these can execute Strictly speaking, the { } are not required when there is just a single statement … but it is a common practice to always use compound statements in control structures.

20 Decision structures : the if statement Another example: Background: The Canadian SIN can be tested for a proper check digit. Part of the process involves multiplying individual digits by either 1 or 2. When a digit is multiplied by 2 and the result is > 9 then the two digits of this product must be added. For example, if the digit is 8 then the product 2*8 is 16 … the sum of its digits is  1+6 is 7 Along these lines consider a simpler program that: 1.gets a digit from the user 2.multiplies that digit by 2 3.if the product is <= 9 then displays the digit otherwise displays the sum of the digits of the product

21 Decision structures : the if statement import java.util.Scanner; /** * Get a digit from the user and multiply by 2 * If the result is larger than 9 add its two digits */ public class TestGreaterThanNine { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("Please enter a single digit:"); int digit = kb.nextInt(); int result = digit*2; if (result > 9) { result = result/10 + result%10; } System.out.println(" result is "+result); } else clause is not necessary… and so omitted

22 Decision structures : nested ifs statement 1 or statement 2 can be any Java statement statement 1, statement 2 can be ifs, whiles, etc. We can nest one control structure inside another control structure

23 Decision structures : nested ifs Example. Round Cost Up Down pages Suppose we must handle a purchase transaction in one of two ways: If the customer pays cash we must round up/down as there are no pennies. If the customers pays by electronic means there is a surcharge of 25 cents.

24 Decision structures : nested ifs In pseudocode: 1.obtain the type and amount of the purchase 2.if the purchase is cash then round the cost up/down 3.otherwise add on the surcharge 4.display the total cost for the customer Code for this is shown on next slide  This can be handled with a nested if-else

25 Decision structures : the if statement if (typePayment.equals("cash")) { if (originalCost % 5 < 3) actualCost = originalCost - originalCost%5; else actualCost = originalCost + (5 - originalCost%5); } else actualCost = originalCost + 25; Nested if to handle the details of the cash payment

26 Decision structures : nested ifs Example. Consider the example beginning on page 84 A table for converting alphabetic grades to a numeric value: When you need to convert some letter grade to its equivalent numeric value you would look for which row the letter appears in and read off the numeric value in that same row. E.g. the numeric value corresponding to B is 3 Letter gradeNumeric grade A4 B3 C2 D1 F0

27 Decision structures : nested ifs To program this conversion nested ifs are useful We can structure this code in many ways We will consider three ways to write the required logic  Letter gradeNumeric grade A4 B3 C2 D1 F0

28 Decision structures : nested ifs Option 1: if (letterGrade.equals("A")) numericGrade = 4.0; if (letterGrade.equals("B")) numericGrade = 3.0; if (letterGrade.equals("C")) numericGrade = 2.0; if (letterGrade.equals("D")) numericGrade = 1.0; This style requires the evaluation of expressions that would not be necessary (for example, when the grade is A the other if s do not need to execute, but they do)

29 Decision structures : nested ifs Option 2: if (letterGrade.equals("A")) numericGrade = 4.0; else if (letterGrade.equals("B")) numericGrade = 3.0; else if (letterGrade.equals("C")) numericGrade = 2.0; else if (letterGrade.equals("D")) numericGrade = 1.0; else numericGrade = 0.0; This style uses indentation properly … each if is indented within the outer if … but the code easily goes off the page/screen and gets hard to read

30 Decision structures : nested ifs Option 3: if (letterGrade.equals("A")) numericGrade = 4.0; else if (letterGrade.equals("B")) numericGrade = 3.0; else if (letterGrade.equals("C")) numericGrade = 2.0; else if (letterGrade.equals("D")) numericGrade = 1.0; else numericGrade = 0.0; Due to the similarity of the logical conditions, this style would be favoured by many … it shows the choices at the same level of indentation

31 Loops: for The for statement is commonly used where there is a need for a statement to be executed a specific number of times The syntax of the for statement we consider here is for ( initialization; logical expression; increment ) statement

32 Loops: for

33 Loops: for Example 1, Numbers0To9WithFor, uses a for to display integers 0 through 9 A code snippet: for (int count=0; count < 10; count++ ) System.out.println(count); Increment Count is increased by 1 each time through the loop Loop continues as long as count < 10 count starts at 0 The statement that is executed repeatedly This statement is indented for clarity and readability

34 Loops: for Example 2, GetIndividualCharacters, uses charAt and a for. Displays characters one-by-one. A code snippet: String text = "abc123"; int textLength = text.length(); System.out.println("text string is: "+text); System.out.println("now, each character one-by-one"); for (int i=0; i<textLength; i++){ char c = text.charAt(i); System.out.println(c); } Length of the string length used to control number of times loop executes Get the i th character Indented code

35 Loops: nesting control structures Example 3, CountLetters, uses an if and a for. Counts the number of times the letter ‘a’ appears. A code snippet: text = kb.nextLine(); int count = 0; for (int i=0; i<text.length(); i++){ if (text.charAt(i) == 'a') count++; } System.out.println("The line contains "+count +" a\'s"); A line of text length used to control number of times loop executes Use an if to test the i th character

36 Loops: nesting control structures Example 4, NestedFor, uses two for s, one nested inside the other Lines 10 to 13 …. the outer for Lines 11 and 12 … the inner for 10 for (int i =1; i <=4; i ++) { 11 for (int j =1; j <=4; j ++) 12 System.out.println "\t"+i+"\t"+j+"\t"+(i*j)); 13 } How many times does this execute? The outer for contains a compound statement

37 Loops: do-while The do-while statement is useful when it is known the loop body must execute at least once. syntax : do statement while ( logical expression ) ;

38 Loops: do-while

39 Loops: do-while The do-while statement is useful when it is known the loop body must execute at least once. syntax : do statement while ( logical expression ) ;

40 Loops: do-while Example. Suppose we are adding the digits of a positive integer There must be at least one digit to add to a total  can use do-while System.out.println("Enter a number"); int n = kb.nextInt(); int sum = 0; do { sum += n % 10; n /= 10; } while (n>0); System.out.println("sum is "+sum); Executed at least once How many times does the loop execute if n is 5? 25? 0?