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

Size: px
Start display at page:

Download "Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal"

Transcription

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

2 Lesson Goals Understand Control Structures Understand how to control the flow of a program via selection mechanisms Understand if, if-else and switch statements Build programs with nested layers of decision making Building blocks of execution code Understand how to deal with the dangling else Understand else-if and how it is different from switch Understand the conditional operator 2

3 Control Structures in Java There are three control structures in Java Sequence Structure Built into Java Ensures that statements execute one after the other in the order they are written, unless directed otherwise Selection Structure (Chapter 4) Based on truth or falsity In Java includes the if, if else, if... else if, and switch statements Repetition Structure (Chapter 5) Allows for repetition of the same group of statements multiple times, as long as a condition is met In Java includes the do, do while, for, and enhanced for statements Also known as iteration statements or looping statements 3

4 Two Way Decisions Windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made. Start at the top of the chart then follow the line to the question: is it raining? The answer is either true or false. If the answer is true, follow the line labeled True, perform the instructions in the box "wipers on", follow the line to "continue". If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off", follow the line to "continue". The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made by executing many small decisions. 4

5 The Basic Syntax of the if Statement if (boolean expression) statement 1; statement 2; o 0 o statement n; The statements inside the block (delineated by a pair of braces) are executed only if the boolean statement is true You should use the braces even if there is only a single statement inside the block even though this isn t required No semicolon on the if statement An if with a single statement following it does not require curly braces, however, it us best to use them all the time at first if (boolean expression) statement 1; 5

6 Basic Terminology An if statement is also called a conditional or selection statement The phrase if (boolean expression) is called the if clause The boolean expression itself is called the condition The statements inside the curly braces comprise a block You can nest if statements inside each other 6

7 A Very Simple Example public class SimpleIfStatementDemo1 public static void main(string args[]) //Declaring a variable "test" and initializing it with a value 10 int test = 10; //Checking if "test" is greater than 5 if (test > 5) //This block will be executed only if "test" is greater than 5 System.out.println("Success"); //The if block ends. System.out.println("Executed successfully"); 7

8 The Basic Syntax of the if-else Statement Similar to the if statement, but exclusively executes an alternative set of statement(s) if the conditional is false if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 o statement n; else statement a; statement b; o 0 o statement x; Note: Once again if there is only a single statement then braces are not required if (boolean expression) // always evaluates to either true or false statement 1; else statement a; 8

9 A Simple Example of if-else import java.util.scanner; class NumberTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); int num; System.out.println("Enter an integer:"); num = keyboard.nextint(); if ( num < 0 ) System.out.println("The number " + num + " is negative"); num = num +5; else System.out.println("The number " + num + " is zero or positive"); num = num -4; System.out.println("The number is now " + num ); System.out.println("Good-bye for now"); 9

10 if else if Syntax Allows for testing for multiple different conditions Only the first case that tests as true will be executed If there is no else statement at the end there may not be execution of any of the blocks if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 statement n; else if(boolean expression) // always evaluates to true or false statement a; statement b; o 0 statement x; else //optional statement a; statement b; o 0 statement x; 10

11 An else if Example //This program assigns a letter grade based on a character grade import java.util.scanner; class IfElseDemo public static void main(string[] args) Scanner keyboard = new Scanner(System.in); System.out.println("Enter the grade"); int testscore = keyboard.nextint(); char grade; if (testscore >= 90) grade = 'A'; else if (testscore >= 80) grade = 'B'; else if (testscore >= 70) grade = 'C'; else if (testscore >= 60) grade = 'D'; else grade = 'F'; System.out.println("Grade = " + grade); Note: If you reverse the order then you would need to compare from bottom to top using <= Be careful in use of > vs. >=, etc. 11

12 A Note On boolean Expressions Be careful when using float or double type variables in boolean expressions Since there is always limited precision the possibility of an execution error exists, especially after more complex mathematical operations Example: (7.13*2.9)/(3.6*2.95) may be different than (7.13/(3.6*2.95))*2.9 See DecimalCompare.java 12

13 The Dangling if (1) Rule - An else matches with the nearest, previous, unmatched if that's not in a block. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.println( "aaa" ) ; else // Matches with previous unmatched if System.out.println( "bbb" ) ; In the example above, the else is indented with the inner if statement. It prints "bbb" only if num > 0 and num >= 10, which means it prints only if num is 10 or greater. In the example below, the else is indented with the outer if statement. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.println( "aaa" ) ; else // Matches with previous unmatched if System.out.println( "bbb" ) ; Which one does else match with? It picks the closest if unless there is a further clarification with the use of braces. This phenomenon of having to pick between one of two possible if statements is called the dangling else. Depending on which if the else is paired with, you can get different results. By now, you should know that Java doesn't pay attention to indentation. So both examples above are the same to Java, which means that it makes its determination based strictly on the syntax. To the Java Compiler there is no ambiguity (You can t say That s not what I really meant ) The compiler doesn t care about indenting. But you should for clarity 13

14 The Dangling if (2) What if we wanted the else to match with the first if? Then, we need braces. if ( num > 0 ) // Previous unmatched if if ( num < 10 ) // Unmatched, but in block System.out.println( "aaa" ) ; else // Matches with previous unmatched if not in block System.out.println( "bbb" ) ; //This prints if num <= 0. The else above matches with the previous, unmatched if not in a block. This happens to be the outer if. There is an unmatched if that's the inner if, but that's in a block, so you can't match to it. Notice the else sits outside of the block. An else can not match to a previous if if the else is outside the block, where the closest if is found. 14

15 The Dangling if The Rules Summarized Every else must match with a unique if. You can't have two or more else matching to the same if. If there is no matching if for an else, then your program won't compile. Each else must be preceded by a valid if Fortunately, your program fails to compile if you don't do this. Use Braces If you always use a block for if body and else body, then you can avoid confusion. However, it's useful to know the correct rules. 15

16 The switch Statement The syntax of a switch statement looks like: switch ( expr ) case literal1: case literal1 body case literal2: case literal2 body case literal3: case literal3 body default: default body Unlike if statements which contain a condition in the parentheses, switch contains an expression. This expression must be type int, char or String. (Note: String is a newer feature, and the book says only int or char) The semantics of switch are: Evaluate the expression Begin looking at each case, starting top to bottom If the value of the expression matches the case, then run the body Note: The case keyword has to be followed by a literal or a constant expression. It can't be a range or something that tests If you run a break statement, you then exit the switch If you don't run a break statement, and you are at the end of a body, run the next body. Keep running bodies until you exit If no match is made to the cases, run the default, if it exists. The default case is always run last, no matter where it appears. (It should be placed last, though). It is not mandatory to have a default statement. 16

17 Examples of the Switch Statement int x = 4 ; switch ( x ) case 2: System.out.println( "TWO" ) ; break ; case 4: System.out.println( "FOUR" ) ; break ; case 6: System.out.println( "SIX" ) ; break ; default: System.out.println( "DEFAULT" ) ; This evaluates x to 4. It skips case 2 since the value 4 doesn't match 2. It does match case 4. It runs the body and prints FOUR". Then it runs break and exits the switch. 17

18 Examples of the Switch Statement (2) Most of the times, you will end each case with break. Both C and languages like Java force you to write a statement that should be there all the time. Let's see what happens when you leave it out. int x = 4 ; switch ( x ) case 2: System.out.println( "TWO" ) ; case 4: System.out.println( "FOUR" ) ; case 6: System.out.println( "SIX" ) ; default: System.out.println( "DEFAULT" ) ; This prints out: FOUR SIX DEFAULT That's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case. However, there are cases where you will want to execute multiple statements from multiple cases (see next example) 18

19 Examples of the Switch Statement (3) You can combine cases together. int x = 4 ; switch ( x ) case 1: case 3: case 5: System.out.println( "ODD" ) ; break ; case 2: case 4: case 6: System.out.println( "EVEN" ) ; break ; default: System.out.println( "DEFAULT" ) ; 19

20 A Few Addi%onal Notes On the switch Statement Every switch statement can be implemented as an if/if else type statement It doesn t always work the other way around Obviously if the if/else is doing more complex comparisons (i.e. >=) or using floating point numbers, then this can t be implemented in a switch statement 20

21 The Condi%onal Operator (1) The conditional operator is used like this: true-or-false-condition? value-if-true : value-if-false Here is how it works: The true-or-false-condition evaluates to true or false. That value selects one choice: If the true-or-false-condition is true, then evaluate the expression between? and : If the true-or-false-condition is false, then evaluate the expression between : and the end. The result of evaluation is the value of the entire conditional expression. This approach can be used in assignment statements 21

22 The Condi%onal Operator (2) int a = 7, b = 21; System.out.println( "The min is: " + (a < b? a : b ) ); The output would be: The min is 7 22

23 The Condi%onal Operator (3) double value = ; double absvalue; absvalue = (value < 0 )? -value : value ; The constant value is assigned to absvalue 23

24 An Example Using String Features That Will Be Taught Later import java.util.scanner; class RainTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); String answer; System.out.print("Is it raining? (Y or N): "); answer = keyboard.nextline(); if ( answer.equals("y") ) // is answer exactly "Y"? System.out.println("Wipers On"); // true branch else System.out.println("Wipers Off"); // false branch 24

25 Now That Your Programs Are GeWng More Complex Always check your programs through each of the else cases, switch gates etc. To do this you need to develop a set of test cases A test case has components that describe an input, action or event and an expected response, to determine if a feature of an application is working correctly Your test cases must be expansive enough to cover the full range of possibilities For instance if there is a statement if (x>4) you don t need to test for every possibility greater than 4, but you need to test for at least one. Typically we build a software test verification matrix 25

26 Sample Test Matrix Y X 1 R1 R2 R3 2 R4 R5 R6 5 R7 R8 R9 7 R10 R11 R12 Test for all possible combinations When there are multiple variables break the testing into smaller pieces Always test for different and outlying conditions Positive, zero and negative numbers First and last number and some element in the middle when processing a list 26

27 Special Topic - Rounding Java includes different methods and techniques for rounding, some of which we will learn later this year However, if you are interested in rounding do the following: 1. Take the floating point number and multiply by 1000; Cast the number multiplied by 1000 as an int (if it is not too large for an int, otherwise use long 2. Take the original floating point number and multiply by 100; Cast the number multiplied by 100 as an int (if it is not too large for an int, otherwise use long 3. Determine if the last digit of the int value multiplied by 1000 is greater than or equal to 5 4. If the last digit is greater than or equal to 5 divide by and add 1, otherwise divide by 100 Example: double x = , xround; int xintthous = (int)(x*1000);// this is int xinthund = (int)(x*100);// this is if (xintthous%10 >=5) xround = (xinthund+1)/100.; else xround = (xinthund/100.); See full program in RoundingExample.java 27

28 Programming Exercises Class (1) Exercise 1. Sort Three Write a program that accepts three integers and displays the number in order from lowest to highest. 28

29 Programming Exercises Class (2) Exercise 8. Toll Free Numbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not. 29

30 Programming Exercises Lab (1) Exercise 3. Positive Sum Write a program that prompts for five integers and calculates the sum of those that are positive. 30

31 Programming Exercises Lab (2) Exercise11. Grade Conversion A certain school assigns number grades ranging from Write a program that queries the user for a numerical score and converts the score to a letter grade according to thee following criteria: 0-59:F; D: 70-72, C-: 73-76, C: C+; 80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A; A+ 31

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 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

More information

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal Control Statements Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review some of Java s control structures Review how to control the flow of a program via selection mechanisms Understand if, if-else,

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

More information

Topics. Chapter 5. Equality Operators

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

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control 1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false. CS101, Mock Boolean Conditions, If-Then Boolean Expressions and Conditions The physical order of a program is the order in which the statements are listed. The logical order of a program is the order in

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

Chapter 4: Making Decisions

Chapter 4: Making Decisions Chapter 4: Making Decisions CSE 142 - Computer Programming I 1 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >=

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 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 1. Flow of

More information

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14 Chapter 4: Making Decisions 4.1 Relational Operators Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than or equal to

More information

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch Control Structures in Java if-else and switch Lecture 4 CGS 3416 Spring 2017 January 23, 2017 Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 1 / 26 Control Flow Control flow refers to the specification

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

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

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)

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Chapter 4: Control Structures I

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

More information

LECTURE 04 MAKING DECISIONS

LECTURE 04 MAKING DECISIONS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 04 MAKING DECISIONS

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Selections EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes The Boolean Data Type if Statement Compound vs. Primitive Statement Common Errors

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

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

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

More information

Conditional Programming

Conditional Programming COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,

More information

Decision Making in C

Decision Making in C Decision Making in C Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Algorithms and Conditionals

Algorithms and Conditionals Algorithms and Conditionals 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/

More information

CMPT 125: Lecture 4 Conditionals and Loops

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

More information

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL 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

More information

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

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

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1 Motivation In the programs we have written thus far, statements are executed one after the other, in the order in which they appear. Programs often

More information

Methods CSC 121 Fall 2016 Howard Rosenthal

Methods CSC 121 Fall 2016 Howard Rosenthal Methods CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme Chapter 4: 4.1 Making Decisions Relational Operators Simple Program Scheme Simple Program Scheme So far our programs follow a simple scheme Gather input from the user Perform one or more calculations Display

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Lesson 7 Part 2 Flags

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

More information

Flow of Control. Chapter 3

Flow of Control. Chapter 3 Walter Savitch Frank M. Carrano Flow of Control Chapter 3 Outline The if-else statement The Type boolean The switch statement Flow of Control Flow of control is the order in which a program performs actions.

More information

Repetition Structures

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

More information

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you

More information

Methods CSC 121 Spring 2017 Howard Rosenthal

Methods CSC 121 Spring 2017 Howard Rosenthal Methods CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand what a method is in Java Understand Java s Math Class and how to use it Learn the syntax of method construction Learn both void methods

More information

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Flow of Control: Loops. Chapter 4

Flow of Control: Loops. Chapter 4 Flow of Control: Loops Chapter 4 Java Loop Statements: Outline The while statement The do-while statement The for Statement Java Loop Statements A portion of a program that repeats a statement or a group

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

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

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

More information

Logical Operators and if/else statement. If Statement. If/Else (4.3)

Logical Operators and if/else statement. If Statement. If/Else (4.3) Logical Operators and if/ statement 1 If Statement We may want to execute some code if an expression is true, and execute some other code when the expression is false. This can be done with two if statements

More information

5. Selection: If and Switch Controls

5. Selection: If and Switch Controls Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Fall 2005 Computer Science I CS 135 0. Course Presentation

More information

Chapter 3 Selection Statements

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

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

Selections. CSE 114, Computer Science 1 Stony Brook University

Selections. CSE 114, Computer Science 1 Stony Brook University Selections CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation If you assigned a negative value for radius in ComputeArea.java, then you don't want the

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

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

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

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

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

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?

More information

Control Structures in Java if-else and switch

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

More information

Flow of Control. Chapter 3

Flow of Control. Chapter 3 Flow of Control Chapter 3 Outline The if-else Stetement The Type boolean The switch statement Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order

More information

Problem Solving With Loops

Problem Solving With Loops To appreciate the value of loops, take a look at the following example. This program will calculate the average of 10 numbers input by the user. Without a loop, the three lines of code that prompt the

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Darrell Bethea May 25, 2011

Darrell Bethea May 25, 2011 Darrell Bethea May 25, 2011 Yesterdays slides updated Midterm on tomorrow in SN014 Closed books, no notes, no computer Program 3 due Tuesday 2 3 A whirlwind tour of almost everything we have covered so

More information

CS1150 Principles of Computer Science Loops (Part II)

CS1150 Principles of Computer Science Loops (Part II) CS1150 Principles of Computer Science Loops (Part II) Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Review Is this an infinite loop? Why (not)?

More information

Oct Decision Structures cont d

Oct Decision Structures cont d Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

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

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

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

Logic & program control part 2: Simple selection structures

Logic & program control part 2: Simple selection structures Logic & program control part 2: Simple selection structures Summary of logical expressions in Java boolean expression means an expression whose value is true or false An expression is any valid combination

More information

Conditional Statement

Conditional Statement Conditional Statement 1 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition Also called Branching How do we specify conditions?

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

More information

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use: CSE 20 SAMPLE FINAL Version A Time: 180 minutes Name The following precedence table is provided for your use: Precedence of Operators ( ) - (unary),!, ++, -- *, /, % +, - (binary) = = =,!= &&

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

Pace University. Fundamental Concepts of CS121 1

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

More information

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

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

More information

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer Programming, I. Laboratory Manual. Experiment #3. Selections Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3

More information

Building Java Programs

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

More information

Variables and data types

Variables and data types Survivor: CSCI 135 Variables Variables and data types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations String

More information

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

STUDENT LESSON A7 Simple I/O

STUDENT LESSON A7 Simple I/O STUDENT LESSON A7 Simple I/O Java Curriculum for AP Computer Science, Student Lesson A7 1 STUDENT LESSON A7 Simple I/O INTRODUCTION: The input and output of a program s data is usually referred to as I/O.

More information

Some Sample AP Computer Science A Questions - Solutions

Some Sample AP Computer Science A Questions - Solutions Some Sample AP Computer Science A Questions - s Note: These aren't from actual AP tests. I've created these questions based on looking at actual AP tests. Also, in cases where it's not necessary to have

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

More information

CSEN 202 Introduction to Computer Programming

CSEN 202 Introduction to Computer Programming CSEN 202 Introduction to Computer Programming Lecture 3: Decisions Prof. Dr. Slim Abdennadher and Dr Mohammed Abdel Megeed Salem, slim.abdennadher@guc.edu.eg German University Cairo, Department of Media

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 2- Arithmetic and Decision Making: Equality and Relational Operators Objectives: To use arithmetic operators. The precedence of arithmetic

More information

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

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

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[]

More information

Lecture 5 Tao Wang 1

Lecture 5 Tao Wang 1 Lecture 5 Tao Wang 1 Objectives In this chapter, you will learn about: Selection criteria Relational operators Logical operators The if-else statement Nested if statements C++ for Engineers and Scientists,

More information

Chapter 4: Conditionals and Recursion

Chapter 4: Conditionals and Recursion Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information