Control Structures in Java if-else and switch

Similar documents
Control Structures in Java if-else and switch

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

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

BRANCHING if-else statements

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

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

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

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

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

COMP 202 Java in one week

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

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

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

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Topics. Chapter 5. Equality Operators

Chapter 3. Selections

Lecture 5 Tao Wang 1

Introduction. C provides two styles of flow control:

Conditionals and Loops

Object-Oriented Programming

Building Java Programs

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

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

CS111: PROGRAMMING LANGUAGE II

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Building Java Programs

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Building Java Programs

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

1007 Imperative Programming Part II

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

CompSci 125 Lecture 11

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

Chapter 4: Making Decisions

Decision Making -Branching. Class Incharge: S. Sasirekha

Chapter 4: Making Decisions

LECTURE 04 MAKING DECISIONS

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Building Java Programs

The Java language has a wide variety of modifiers, including the following:

Quiz 1: Functions and Procedures

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Flow Control. CSC215 Lecture

Lecture 3 (02/06, 02/08): Condition Statements Decision, Operations & Information Technologies Robert H. Smith School of Business Spring, 2017

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

5. Selection: If and Switch Controls

Flow Control. Key Notion. Statement Categories. 28-Oct-10

CS 115 Lecture 8. Selection: the if statement. Neil Moore

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

Java Bytecode (binary file)

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

Midterm Review Session

Topic 4 Expressions and variables

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Introduction to Object-Oriented Programming

BM214E Object Oriented Programming Lecture 4

SELECTION. (Chapter 2)

Flow of Control. Chapter 3

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

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

Conditional Programming

PROGRAMMING FUNDAMENTALS

The Basic Parts of Java

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.

Flow of Control. Chapter 3

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Decision Making in C

CT 229 Java Syntax Continued

CONDITIONAL EXECUTION: PART 2

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Computational Expression

Lecture 4. CS118 Term planner. The simple if statement. Control flow: selection. The if... else statement cont... The if... else statement.

CS1004: Intro to CS in Java, Spring 2005

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

Java is an objet-oriented programming language providing features that support

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

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

Program Elements -- Introduction

Principles of Computer Science

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Building Java Programs Chapter 2

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Computer Programming I - Unit 5 Lecture page 1 of 14

Selections. CSE 114, Computer Science 1 Stony Brook University

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

Programming with Java

Chapter 4 - Notes Control Structures I (Selection)

Flow of Control Branching 2. Cheng, Wei COMP May 19, Title

Java I/O and Control Structures

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

LESSON 3 CONTROL STRUCTURES

Transcription:

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 of the order in which the individual statements, instructions or function calls of an imperative program are executed or evaluated Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 2 / 26

Types of Control Flow Flow of control through any given function is implemented with three basic types of control structures: Sequential: Default mode. Statements are executed line by line. Selection: Used for decisions, branching choosing between 2 or more alternative paths. if if - else switch conditional statements Repetition: Used for looping repeating a piece of code multiple times in a row. while do - while for The function construct, itself, forms another way to affect flow of control through a whole program. This will be discussed later in the course. Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 3 / 26

Logical Operators Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 4 / 26

Logical Operators Java has Boolean operators for combining expressions. Each of these operators returns a Boolean value: a true or a false.!x // the NOT operator (negation) true if x is false x && y x y // the AND operator true if both x and y are true // the OR operator true if either x or y (or both) are true x y // the EXCLUSIVE OR operator true if exactly one operand is true and one is false These operators will be commonly used as test expressions in selection statements or repetition statements (loops). Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 5 / 26

Relational Operators The comparison operators in Java work much like the symbols we use in mathematics. Each of these operators returns a Boolean value: a true or a false. x == y x!= y x <y x <= y x >y x >= y // x is equal to y // x is not equal to y // x is less than y // x is less than or equal to y // x is greater than y // x is greater than or equal to y Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 6 / 26

Examples of Expressions (x >0 && y >0 && z >0) // all three of (x, y, z) are positive (x <0 y <0 z <0) // at least one of the three variables is negative ( numstudents >= 20 &&!(classavg <70)) // there are at least 20 students and the class average is at least 70 ( numstudents >= 20 && classavg >= 70) // means the same thing as the previous expression Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 7 / 26

Short Circuit Evaluation The && and operators also have a feature known as short-circuit evaluation. In the Boolean AND expression (X && Y), if X is false, there is no need to evaluate Y (so the evaluation stops). Example: (d!= 0 && n / d >0) Notice that the short circuit is crucial in this one. If d is 0, then evaluating (n / d) would result in division by 0 (illegal). But the short-circuit prevents it in this case. If d is 0, the first operand (d!= 0) is false. So the whole && is false. Similarly, for the Boolean OR operation (X Y), if the first part is true, the whole thing is true, so there is no need to continue the evaluation. The computer only evaluates as much of the expression as it needs. This can allow the programmer to write faster executing code. Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 8 / 26

if Statement The most common selection statement is the if statement. Basic syntax: if (boolean expression) { statement(s) } The condition is always a boolean expression. This means that it must be an expression that evaluates to a true or a false. Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 9 / 26

if - else Statements The if statement can also have an else clause. This is sometimes known as an if/else statement. Basic syntax: if (boolean expression) { statement(s) } else { statement(s) } In both of these formats, the set braces can be left out if the body of the if or the else is a single statement. Otherwise, the block is needed. Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 10 / 26

Examples if (grade >= 68) System.out.print("Passing"); if (x == 0) System.out.println("Nothing here"); else System.out.println("There is a value"); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 11 / 26

Examples if (y!= 4) { System.out.println("Wrong number"); y = y * 2; counter++; } else { System.out.println("That s it!"); success = true; } Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 12 / 26

Examples Be careful with ifs and elses. If you don t use { }, you may think that you ve included more under an if condition than you really have. if (val <5) System.out.println("True"); else System.out.println("False"); System.out.println("Too bad!"); Indentation is only for people! It improves readability, but means nothing to the compiler. Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 13 / 26

Some Common Errors What s wrong with these if-statements? Which ones are syntax errors and which ones are logic errors? if (x == 1 2 3) System.out.print("x is a number in the range 1-3"); if (x >5) && (y <10) System.out.print( Yahoo! ); if (response!= Y response!= N ) System.out.print("You must type Y or N (for yes or no)"); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 14 / 26

Nested if-statement We could add more valid statements between the set braces, including valid if statements: if ( x >10) { x /= 10; System.out.println(x); if ( x >10) { x /= 10; System.out.println(x); } } else System.out.println("x is less than 10"); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 15 / 26

Multi-way If-Else Statements find the first valid conditional expression in the series that evaluates to true, execute the java statement immediately under it, and then to skip the remainder of the series. if (temperature <= 95) // low body temperature System.out.println("low body temperature"); else if (temperature > 101) // fever System.out.println("fever!"); else // normal temperature System.out.println("normal"); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 16 / 26

Order Matters the example to print out big if a number is bigger than 100, medium if a number is between 20 and 100, and small otherwise. if (num > 100) System.out.println( Big ); else if (num > 20) System.out.println( Medium ); else System.out.println( Small ); if (num > 20) System.out.println( Big ); else if (num >100) System.out.println( Medium ); else System.out.println( Small ); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 17 / 26

Exercise Figuring a letter grade Have the user enter a number from 1 to 12 corresponding to the index of the month. The program then prints out the name of the month Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 18 / 26

The switch Statement A switch statement is often convenient for occasions in which there are multiple cases to choose from. The syntax format is: switch (expression) { case constant: statements case constant: statements...(as many case labels as needed) } default: statements // optional label Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 19 / 26

The switch Statement The switch statement evaluates the expression, and then compares it to the values in the case labels. If it finds a match, execution of code jumps to that case label. The values in case labels must be constants, and may only be types char, byte, short, or int. From Java 7 onwards, Strings and Enum types are also allowed. It must be of the same type with the expression This also means the case label must be a literal or a variable declared to be constant (with final). You may not have case labels with regular variables, floating point literals, operations, or function calls If you want to execute code only in the case that you jump to, end the case with a break statement, otherwise execution of code will fall through to the next case. The all statements after the match are executed including those in the subsequent cases. Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 20 / 26

The switch Statement switch (expression) { case constant: statements break; case constant: statements break;...(as many case labels as needed) } default: statements // optional label Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 21 / 26

example The day is Weekday or Weekend? switch (day) { case 2: case 3: case 4: case 5: case 6: name = "Weekday"; case 1: case 7: name = "Weekend"; } System.out.println( It is a + name); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 22 / 26

Exercise Figuring a letter grade with Switch(Grades2-2.java) Have the user enter a number from 1 to 12 corresponding to the index of the month. The program then prints out the name of the month Converts the day of the in numeric form (1, 2,... 7) to the name of the day (Monday,...,Sunday)(DayName.java) Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 23 / 26

The Conditional Operator There is a special operator known as the conditional operator that can be used to create short expressions that work like if/else statements. Format: boolean expr? true expr : false expr How it works: The boolean expression is evaluated for true/false value. This is like the test expression of an if-statement. If the expression is true, the operator returns the true expression value. If the test expression is false, the operator returns the false expression value. Note that this operator takes three operands. It is the one ternary operator in the Java language Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 24 / 26

Some Examples System.out.print( (x >y)? "x is greater than y" : "x is less than or equal to y"); // Note that this expression gives the same result as the following if (x >y) System.out.print("x is greater than y"); else System.out.print("x is less than or equal to y"); Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 25 / 26

Some Examples (x <0? value = 10 : value = 20); // this gives the same result as: value = (x <0? 10 : 20); // and also gives the same result as: if (x <0) value = 10; else value = 20; Lecture 4CGS 3416 Spring 2017 Selection January 23, 2017 26 / 26