# Chapter 3. Selections

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Chapter 3 Selections 1

2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2

3 1. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement execution through a method is linear (sequential): one statement after another in sequence Some programming statements allow us to: decide whether or not to execute a particular statement execute a statement over and over, repetitively These selection (decision) statements are based on boolean expressions (or conditions) that evaluate to true or false 3

4 2. Selection Statements A Selection (conditional) statement allows us to choose which statement (or block of statements) will be executed next. Java selection statements are: if statement - allows one option if-else statement - allows two options switch statement - allows multiple options 4

5 3. The if Statement The if statement has the following syntax: if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if (condition) { statementblock; ; If the condition is true, the statementblock is executed. If it is false, the statementblock is skipped. 5

6 Logic of if statement Statement condition evaluated 1 int grade = 70; 2 if (grade>= 90) 3 System.out.println("You got an "A"); 4 System.out.println("This is line 4"); true false Statement Block Statement 1 int grade = 95; 2 if (grade>= 90) 3 System.out.println("You got an "A"); 4 System.out.println("This is line 4"); 6

7 Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) 7

8 Example - if Statement An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); First, the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not If the condition is true, the assignment statement is executed -- if it isn t (i.e., false), the assignment statement is skipped. Either way, the call to println is executed next See Age.java next slide 8

9 Example - if Statement // Age.java import java.util.scanner; public class Age { public static void main (String[] args) { final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextint(); System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy!"); System.out.println ("Age is a state of mind."); 9

10 Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand Although it makes no difference to the compiler, proper indentation is crucial for code readability and debugging 10

11 Expressions What do the following statements do? if (top >= MAXIMUM) top = 0; //next statement starts here Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total!= stock + warehouse) inventoryerror = true; // next statement starts here Sets a flag to true if the value of total is not equal to the sum of stock and warehouse Note: the precedence of arithmetic operators is higher than the precedence of equality and relational operators. 11

12 Logical Operators Boolean expressions can also use the following logical operators:! Logical NOT && Logical AND Logical OR ^ Logical XOR (exclusive OR) They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND, OR, and XOR are binary operators (each operates on two operands) 12

13 Logical Operators The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then!a is false; if a is false, then!a is true Logical expressions can be shown using a truth table boolean a!a true false false true 13

14 Logical Operators The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b is true if a or b or both are true, and false otherwise The logical XOR expression a ^ b is true if and only if a and b are different. 14

15 Logical Operators A truth table shows all possible true-false combinations of the terms Since &&,, and ^ each have two operands, there are four possible combinations of a and b (boolean expressions) a b a && b a b a ^ b true true true true false true false false true true false true false true true false false false false false 15

16 Boolean Expressions Expressions that use logical operators can form complex conditions if (total < MAX + 5 &&!found) System.out.println ("Processing "); Mathematical operators have higher precedence than the Relational and Logical operators Relational operators have higher precedence than Logical operators 16

17 Boolean Expressions Specific expressions can be evaluated using truth tables Given X = total < MAX &&!found What is the values of X? total < MAX!found X = total < MAX &&!found true true true true false false false true false false false false 17

18 Operator Precedence var++, var-- ++var, --var Postfix increment Prefix increment +, - unary operators (type) Casting and parenthesis! Not *, /, % Math operators +, - Math operators <, <=, >, >= Relational operators ==,!= Relational equality ^ Exclusive OR && Logical AND Logical OR =, +=, -=, *=, /=, %= Assignment operators 18

19 Operator Precedence Applying operator precedence and associativity rule to the expression: * 4 > 5 * (4 + 3) * 4 > 5 * (4 + 3) * 4 > 5 * > 5 * > > > 34 false (1) inside parentheses first (2) multiplication (3) multiplication (4) addition (5) subtraction (6) greater than 19

20 4. The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statementblock1; else statementblock2; If the condition is true, statementblock1 is executed; if the condition is false, statementblock2 is executed One or the other will be executed, but not both 20

21 Logic of an if-else statement Statement condition evaluated true false StatementBlock1 StatementBlock2 Statement 21

22 Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); 22

23 Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); 23

24 Trace if-else statement Suppose score is 70.0 The condition is true if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); 24

25 Trace if-else statement Suppose score is 70.0 grade is C if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); 25

26 Trace if-else statement Suppose score is 70.0 Exit the if statement if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); See Wages.java example next slide. 26

27 Example // Wages.java import java.text.numberformat; import java.util.scanner; public class Wages { public static void main (String[] args) { final double RATE = 8.25; //regular pay rate final int STANDARD = 40; //weekly hours Scanner scan = new Scanner (System.in); //scanner object double pay = 0.0; // initialization System.out.print ("Enter the number of hours worked: "); //prompt int hours = scan.nextint(); //read input value System.out.println (); //print blank line // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-standard) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance();//format System.out.println ("Gross earnings: " + fmt.format(pay));//output 27

28 Indentation - Revisited Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System.out.println ("Error!!"); errorcount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not 28

29 Block Statements Several statements can be grouped together into a block statement delimited by braces if (total > MAX) { System.out.println ("Error!!"); errorcount++; // more statements 29

30 Block Statements In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System.out.println ("Error!!"); errorcount++; else { System.out.println ("Total: " + total); current = total * 2; See Guessing.java next slide. 30

31 Example // Guessing.java import java.util.*; public class Guessing { public static void main (String[] args) { final int MAX = 10; int answer, guess; Scanner scan = new Scanner (System.in); //scanner object Random generator = new Random(); //number generator object answer = generator.nextint(max) + 1; //generate a number System.out.print ("I'm thinking of a number between 1" + "and " + MAX + ". Guess what it is: "); guess = scan.nextint(); //read user input if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct!"); System.out.println ("The number was " + answer); 31

32 5. The Conditional Operator Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated Its syntax is: condition? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The conditional operator is ternary because it requires three operands 32

33 The Conditional Operator The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2)? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger Same as if (num1 > num2) larger = num1; else larger = num2; 33

34 The Conditional Operator Another example: System.out.println ("Your change is " + count + ((count == 1)? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed 34

35 Nested if Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements Java Rule: An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs See MinOfThree.java next slide 35

36 Example // MinOfThree.java import java.util.scanner; public class MinOfThree { public static void main (String[] args) { int num1, num2, num3, min = 0; Scanner scan = new Scanner (System.in); System.out.println ("Enter three integers: "); num1 = scan.nextint(); num2 = scan.nextint(); num3 = scan.nextint(); if (num1 < num2) if (num1 < num3) min = num1; else min = num3; if (num1 < num2) min = num1; else min = num2; else if (num2 < num3) min = num2; if (num3 < min) else min = num3; min = num3; System.out.println ("Minimum value: " + min); 36

37 6. Switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases (options) Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches 37

38 Syntax The general syntax of a switch statement is: switch and case are reserved words switch (expression) { case value1: statement_list1 break; case value2: statement_list2 break; case value3: statement_list3 break; case... If expression matches value2, control jumps to here default: statement_list 38

39 break Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case 39

40 Trace switch statement Suppose day is 2: switch (day) { //day is of type int case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 40

41 Trace switch statement Match case 2 switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 41

42 Trace switch statement Match case 2 switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 42

43 Trace switch statement Fall through case 3 switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 43

44 Trace switch statement Fall through case 4 switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 44

45 Trace switch statement Fall through case 5 switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 45

46 Trace switch statement Printout Weekday switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 46

47 Trace switch statement Encounter break switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 47

48 Trace switch statement Exit the statement switch (day) { case 1: case 2: case 3: case 4: case 5: System.out.println("Weekday"); break; case 6: case 7: System.out.println("Weekend"); 48

49 Default Case A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to the default case if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch statement 49

50 Example switch (option) //option is of type char { case 'A': acount = acount + 1; break; case 'B': bcount = bcount + 1; break; case 'C': ccount = ccount + 1; break; default: System.out.println ("Invalid Option ") 50

51 Switch Statement Expression The expression of a switch statement must result in an integer type (byte, short, int, long) or a char type. It cannot be a boolean value or a floating point value (float or double) You cannot perform relational checks with a switch statement See GradeReport.java next slide 51

52 Example import java.util.scanner; public class GradeReport { public static void main (String[] args) {... Some other code here grade = scan.nextint(); category = grade / 10; System.out.print ("That grade is "); switch (category) { case 10: System.out.println ("a perfect score, well done."); break; case 9: System.out.println ("well above average. Excellent."); break; case 8: System.out.println ("above average. Nice job."); break; case 7: System.out.println ("average."); break; case 6: System.out.println ("below average. Do better!"); break; default: System.out.println ("not passing."); 52

53 7. Useful Hints if i > 0 { System.out.println("i is positive"); //wrong if (i > 0) { System.out.println("i is positive"); //correct =================================================== if (i > 0) { System.out.println("i is positive"); Same as if (i > 0) System.out.println("i is positive"); 53

54 Useful Hints Nested if statements and style issue. if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Equivalen t if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 54

55 Useful Hints The else clause matches the most recent if clause in the same block. int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); Equivalent int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); if (even == true) System.out.println( "It is even."); Equivalent if (even) System.out.println( "It is even."); 55

56 Useful Hints Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); <=== Wrong { area = radius*radius*pi; System.out.println( "The area for the circle of radius " + radius + " is " + area); This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logical error. 56

57 8. Using Assertions Assertion is a way to validate assumptions and detect errors to make code more secure and robust. Java supports assertions using assert statement. assert statement can be used to test your assumptions about the program. While executing asset statement, if the assumption believed to be false, Java throws an error named AssertionError and terminates the program. That is, the program execution stops at that point. It is mainly used for testing purpose. 57

58 assert Statement Syntax Statement syntax: assert expression1; assert expression1 : expression2; Example: validate if salary is positive value. //read and validate salary value int salary = scanner.nextint(); assert salary > 0; OR //read and validate salary value int salary = scanner.nextint(); assert salary > 0 : "Invalid input. Salary must be positive value" 58

59 Logic of assert Statement Statement Logic: Evaluate exporession1 false Execute expression 2 and stop the program Next Statement true If expression 1 is false (invalid), execute expression 2 and stop program execution. Otherwise continue program execution. Expression 2 can be empty. 59

60 if Statement vs. assert Statement Statement Statement Evaluate exporession1 Evaluate condition false Execute expression 2 and stop the program true true StatementBlock1 false StatementBlock2 Next Statement Statement assert Statement if statement 60

61 Assertions - Example 1 import java.util.scanner; //To enable Assertions in JGRASP, //click menu "Build" and check box "Enable Assertions" class AssertionExample{ public static void main( String args[]){ Scanner scanner = new Scanner( System.in); System.out.print("Enter your age (>= 18): "); int age = scanner.nextint(); //check my assumption, quit if value < 18 assert age>=18 : age + " is invalid input for age."; System.out.println("Entered age value is " + age); // other code 61

62 Assertions - Example 1 Outputs ----jgrasp exec: java -ea AssertionExample Enter your age (>= 18): 20 Entered age value is jgrasp: operation complete. ----jgrasp exec: java -ea AssertionExample Enter your age (>= 18): 15 Exception in thread "main" java.lang.assertionerror: 15 is invalid input for age. at AssertionExample.main(AssertionExample.java:15) ----jgrasp wedge2: exit code for process is jgrasp: operation complete. 62

63 Assertions - Example 2 //To enable Assertions in JGRASP, //click menu "Build" and check box "Enable Assertions" import java.util.*; import java.util.scanner; public class AssertionExample2 { public static void main(string args[]) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number between 0 and 100: "); int value = scanner.nextint(); // validate number value, quit if invalid input assert (value >= 0 && value <= 100) : "Invalid number: " + value; System.out.println("You have entered " + value); // other code 63

64 Assertions - Example 2 Outputs ----jgrasp exec: java -ea AssertionExample2 Enter a number between 0 and 100: 89 You have entered jgrasp: operation complete. ----jgrasp exec: java -ea AssertionExample2 Enter a number between 0 and 100: 125 Exception in thread "main" java.lang.assertionerror: Invalid number: 125 at AssertionExample2.main(AssertionExample2.java:16) ----jgrasp wedge2: exit code for process is jgrasp: operation complete. 64

66 End of Chapter 3 Slides 66

### Java I/O and Control Structures

Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying

### Java I/O and Control Structures Algorithms in everyday life

Introduction Java I/O and Control Structures Algorithms in everyday life CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Source: http://xkcd.com/627/

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

3.1 Introduction Chapter 3 Selections Java provides selections that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are Boolean expressions.

### Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition Program Development The creation of software involves four basic activities: establishing

### Selection Statements and operators

Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Chapter 3: Program Statements

Chapter 3: Program Statements Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by

### Chapter 4: Control Structures I

Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

### Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

### Topics. Chapter 5. Equality Operators

Topics Chapter 5 Flow of Control Part 1: Selection Forming Conditions if/ Statements Comparing Floating-Point Numbers Comparing Objects The equals Method String Comparison Methods The Conditional Operator

### Chapter 3 Selection Statements

Chapter 3 Selection Statements 3.1 Introduction Java provides selection statements that let you choose actions with two or more alternative courses. Selection statements use conditions. Conditions are

### Selection and Repetition Revisited

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Program Control Flow

Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

### Program Control Flow

Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

### Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 03: Control Flow Statements: Selection Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad Noor

### Java Coding 3. Over & over again!

Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

### More Programming Constructs -- Introduction

More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

### CMPT 125: Lecture 4 Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 17, 2009 1 Flow of Control The order in which statements are executed

### Introduction to Computer Science Unit 2. Exercises

Introduction to Computer Science Unit 2. Exercises Note: Curly brackets { are optional if there is only one statement associated with the if (or ) statement. 1. If the user enters 82, what is 2. If the

### Lesson 7 Part 2 Flags

Lesson 7 Part 2 Flags A Flag is a boolean variable that signals when some condition exists in a program. When a flag is set to true, it means some condition exists When a flag is set to false, it means

### Selection and Repetition

Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

### Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Motivating Examples (1.1) Selections EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG 1 import java.util.scanner; 2 public class ComputeArea { 3 public static void main(string[] args)

### Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Basic Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

### Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

### Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal

Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal

Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

### CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

LIANMC03v3_0132221586.QXD 5/15/06 7:41 PM Page 67 CCHAPTER HAPTER 3 1 SELECTION STATEMENTS Objectives To declare boolean type and write Boolean expressions ( 3.2). To distinguish between conditional and

### School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

### Java Programming Language. 0 A history

Java Programming Language 0 A history How java works What you ll do in Java JVM API Java Features 0Platform Independence. 0Object Oriented. 0Compiler/Interpreter 0 Good Performance 0Robust. 0Security 0

### Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

### Pace University. Fundamental Concepts of CS121 1

Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

### 3chapter C ONTROL S TATEMENTS. Objectives

3chapter C ONTROL S TATEMENTS Objectives To understand the flow of control in selection and loop statements ( 3.2 3.7). To use Boolean expressions to control selection statements and loop statements (

### JAVA Ch. 4. Variables and Constants Lawrenceville Press

JAVA Ch. 4 Variables and Constants Slide 1 Slide 2 Warm up/introduction int A = 13; int B = 23; int C; C = A+B; System.out.print( The answer is +C); Slide 3 Declaring and using variables Slide 4 Declaring

### Chapter 2. Elementary Programming

Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

### Selection Statements. Pseudocode

Selection Statements Pseudocode Natural language mixed with programming code Ex: if the radius is negative the program display a message indicating wrong input; the program compute the area and display

### Elementary Programming

Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

### CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSC 1051 Algorithms and Data Structures I Midterm Examination February 25, 2016 Name: KEY A Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in

### CT 229 Java Syntax Continued

CT 229 Java Syntax Continued 29/09/2006 CT229 Lab Assignments One Week Extension for Lab Assignment 1. Due Date: Oct 8 th Before submission make sure that the name of each.java file matches the name given

### Condensed Java. 12-Oct-15

Condensed Java 12-Oct-15 Python and Java Python and Java are both object-oriented languages Conceptually, the languages are very similar The syntax, however, is quite different, and Java syntax is much

### Section 2.2 Your First Program in Java: Printing a Line of Text

Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

### Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2016 February 2, 2016 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions

### THE JAVA FOR STATEMENT

THE JAVA FOR STATEMENT The for statement behaves as a while statement. Its syntax visually emphasizes the code that initializes and updates the loop variables. for ( init; truth value; update ) statement

### Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

### Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

### Data Conversion & Scanner Class

Data Conversion & Scanner Class Quick review of last lecture August 29, 2007 ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Numeric Primitive Data Storing

### Chapter 2: Data and Expressions

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types

### Java Bytecode (binary file)

Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

### H212 Introduction to Software Systems Honors

Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

### Chapter. Solving Problems that Require Decisions. Objectives: At the end of the chapter students should be able to:

Chapter 13 Solving Problems that Require Decisions Objectives: At the end of the chapter students should be able to: Design programs that correctly use decision logic Correctly write and evaluate simple

### Chapter 2: Data and Expressions

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

### Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Flow of Control of Program Statements CS 112 Introduction to Programming (Spring 2012) q Java provides two types of program flow of control statements: decision statements, or conditional statements: decide

### McGill University School of Computer Science COMP-202A Introduction to Computing 1

McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

### Building Java Programs

Building Java Programs Chapter 4: Conditional Execution 1 loop techniques cumulative sum fencepost loops conditional execution Chapter outline the if statement and the if/else statement relational expressions

### Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

CS 201 Selection Structures (2) and Repetition Debzani Deb Multiple-Alternative Decision Form of Nested if Nested if statements can become quite complex. If there are more than three alternatives and indentation

### Control Statements: Part 1

4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

### AP COMPUTER SCIENCE A

AP COMPUTER SCIENCE A CONTROL FLOW Aug 28 2017 Week 2 http://apcs.cold.rocks 1 More operators! not!= not equals to % remainder! Goes ahead of boolean!= is used just like == % is used just like / http://apcs.cold.rocks

### Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

### CS 112 Introduction to Programming

CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

### Repetition Structures

Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

### Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

### COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015 Announcements Midterm Exams on 4 th of June (12:35 14:35) Room allocation will be announced soon

### Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

### Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

### CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

CSC 1051 Algorithms and Data Structures I Midterm Examination October 9, 2014 Name: KEY Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the

### Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program

### BLOCK STRUCTURE. class block main method block do-while statement block if statement block. if statement block. Block Structure Page 1

BLOCK STRUCTURE A block is a bundle of statements in a computer program that can include declarations and executable statements. A programming language is block structured if it (1) allows blocks to be

### Decisions (If Statements) And Boolean Expressions

Decisions (If Statements) And Boolean Expressions CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Last updated: 2/15/16 1 Syntax if (boolean_expr)

### CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]

### Programming Language Basics

Programming Language Basics Lecture Outline & Notes Overview 1. History & Background 2. Basic Program structure a. How an operating system runs a program i. Machine code ii. OS- specific commands to setup

### Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Data and Algorithms Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs Algorithms in everyday life CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari

### COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity Java Decisions and Loops Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) A decision is made by evaluating a condition in an if/else

### CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

### Repetition. Chapter 6

Chapter 6 Repetition Goals This chapter introduces the third major control structure repetition (sequential and selection being the first two). Repetition is discussed within the context of two general

### CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I 06 / 02 / 2015 Instructor: Michael Eckmann Today s Topics Operators continue if/else statements User input Operators + when used with numeric types (e.g. int,

### Question: Total Points: Score:

CS 170 Exam 1 Section 000 Fall 2014 Name (print): Instructions: Keep your eyes on your own paper and do your best to prevent anyone else from seeing your work. Do NOT communicate with anyone other than

### ++x vs. x++ We will use these notations very often.

++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3

### Chapter 4: Control structures. Repetition

Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

### Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

### Lecture Set 2: Starting Java

Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

### COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

### Information Science 1

Information Science 1 Fundamental Programming Constructs (1) Week 11 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 10 l Flow of control

Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static

### Lecture Set 2: Starting Java

Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

### 2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

### STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

### New York University Intro to Computer Science (CSCI-UA.101) Fall 2014 Midterm #1 Test G. Instructions:

NAME: New York University Intro to Computer Science (CSCI-UA.101) Fall 2014 Midterm #1 Test G Instructions: KEEP TEST BOOKLET CLOSED UNTIL YOU ARE INSTRUCTED TO BEGIN. Omit one page from this exam. To

### CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

CSC 1051 Algorithms and Data Structures I Midterm Examination October 6, 2016 Name: Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make a

CIS 3022 Prog for CIS Majors I February 10, 2009 Exam I Print Your Name Your Section # Total Score Your work is to be done individually. The exam is worth 105 points (five points of extra credit are available

### Operators & Expressions

Operators & Expressions Operator An operator is a symbol used to indicate a specific operation on variables in a program. Example : symbol + is an add operator that adds two data items called operands.

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Loops and Expression Types

Software and Programming I Loops and Expression Types Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline The while, for and do Loops Sections 4.1, 4.3 and 4.4 Variable Scope Section

### Conditional Execution

Unit 3, Part 3 Conditional Execution Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Simple Conditional Execution in Java if () { else {

### Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,

### Chapter 4: Control structures

Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

### What did we talk about last time? Examples switch statements

Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static