Topic 2: Making Decisions

Similar documents
Topic 2: Making Decisions

Topic 8: Lazy Evaluation

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions

Key Differences Between Python and Java

Topic 7: Algebraic Data Types

Topic 9: Type Checking

Topic 9: Type Checking

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

ENGR 101 Engineering Design Workshop

Datatypes, Variables, and Operations

Control Structures in Java if-else and switch

Variable and Data Type I

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Topic 4: Tuples and Lists

If Control Construct

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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

Topic 1: Introduction

VARIABLES & ASSIGNMENTS

Variable and Data Type I

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

Introduction to Python

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Text Input and Conditionals

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

Chapter 4: Making Decisions

ENJOY! Problem 2 What does the following code do, in a brief English sentence? int mystery(int k) { int i = 0; if (k < 0) return -1;

Chapter 4: Making Decisions

Introduction Course Information Object Oriented Concepts Operators & Control Statements Assignment 3. CS Java. Introduction to Java

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

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

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

Chapter 7. Expressions and Assignment Statements (updated edition 11) ISBN

Boolean Algebra Boolean Algebra

2015 Academic Challenge

Program Planning, Data Comparisons, Strings

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

Chapter 7. Expressions and Assignment Statements ISBN

SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques

Other Loop Options EXAMPLE

CSI33 Data Structures

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

cs1114 REVIEW of details test closed laptop period

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

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

LECTURE 04 MAKING DECISIONS

Hints: I used a left fold and wrote a named helper function when I created my solution.

Chapter 7. Expressions and Assignment Statements

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Expressions & Assignment Statements

PROGRAMMING FUNDAMENTALS

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Conditional Expressions and Decision Statements

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

REVIEW. The C++ Programming Language. CS 151 Review #2

Do not turn to the next page until the start of the exam.

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

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

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Variables, expressions and statements

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

LECTURE 02 INTRODUCTION TO C++

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Conditionals and Loops

Decisions. Arizona State University 1

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Tokens, Expressions and Control Structures

Perfect square. #include<iostream> using namespace std; int main(){ int a=1; int square; while(true){ } cout<<square<<endl; }

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

G Programming Languages - Fall 2012

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Conditionals !

CHAPTER 3 BASIC INSTRUCTION OF C++

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

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

Computer Science II Lecture 1 Introduction and Background

LAB 4.1 Relational Operators and the if Statement

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

CS150 Intro to CS I. Fall Fall 2017 CS150 - Intro to CS I 1

Control Structures 1 / 17

Spoke. Language Reference Manual* CS4118 PROGRAMMING LANGUAGES AND TRANSLATORS. William Yang Wang, Chia-che Tsai, Zhou Yu, Xin Chen 2010/11/03

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

BRANCHING if-else statements

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

Real Python: Python 3 Cheat Sheet

Computational Expression

Principles of Computer Science

C++ for Python Programmers

Chapter 4: Control Structures I (Selection)

CS1500 Algorithms and Data Structures for Engineering, FALL Virgil Pavlu, Jose Annunziato,

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

Transcription:

Topic 2: Making Decisions 1

Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 3.1, 3.5, 3.8, 3.9, 3.10, 3.11, 3.13, 3.14, 3.16, 3.17, 3.18, 3.19, 3.20, 3.22, 3.23 and 3.24 Readings: Chapter 3 2

Making Decisions Most Interesting functions perform different tasks for different parameter values What mechanisms exist to make decisions? 3

Making Decisions A quick look at if and if else if (i < 0) if (i < 5) cout << "A" << endl; else cout << "B" << endl; What does this code display for i == 0 i == 3 i == 6? 4

Making Decisions A closer look at switch case case somechar of 'a', 'e', 'i', 'o', 'u': writeln('vowel'); 'y': writeln( Vowel or consonant'); else writeln('consonant'); end; switch (somechar) { case 'a': case 'e': case 'i': case 'o': case 'u': cout << "Vowel" << endl; case 'y': cout << "Vowel or consonant" << endl; default: cout << "Consonant" << endl; } given ($somechar) { when (['a', 'e', 'i', 'o', 'u']) { say 'Vowel'; } when ('y') { say 'Vowel or consonant'; } default { say 'Consonant'; } } switch (somechar) { case 'a': case 'e': case 'i': case 'o': case 'u': Console.WriteLine("Vowel"); case 'y': Console.WriteLine("Vowel or consonant"); default: Console.WriteLine("Consonant"); } 5

Making Decisions A closer look at switch case Provided by many languages But details vary Default is to fall through: C, C++, Java break prevents fall through Cannot fall through: Pascal, C# Default is not to fall through: Perl continue permits it Not included: Python Can fake it with a dictionary Advantages of switch case compared to if elif else? Disadvantages? 6

An Elegant Use of Fall Through // // Determine the day within the year // (New Year's Day is day 1) // int get_day_of_year(int day, int month, int year) { int day_of_year = day; switch (month) { case 12: day_of_year += 30; case 11: day_of_year += 31; case 10: day_of_year += 30; case 9: day_of_year += 31; case 8: day_of_year += 31; case 7: day_of_year += 30; case 6: day_of_year += 31; case 5: day_of_year += 30; case 4: day_of_year += 31; case 3: if (is_leap_year(year)) day_of_year += 29; else day_of_year += 28; case 2: day_of_year += 31; } return day_of_year; } 7

Making Decisions A closer look at inline if / conditional expressions Called by many different names Ternary if, ternary conditional, ternary operator, conditional operator, inline if, conditional expression, Allows a program to make a decision inside an expression System.out.println(x + " is an " + (x % 2 == 0? "even" : "odd") + " integer"); print("the value" + ("s are" if len(data) > 1 else " is"), data) Can be used as an lvalue in C++ x = 0; y = 0; cout << "Before: x is " << x << ", y is " << y << endl; (change_x == true? x : y) = 1; cout << "After: x is " << x << ", y is " << y << endl; 8

Making Decisions Decision Making Structures in Haskell Pattern matching Guards if then else case 9

Pattern Matching Pattern matching permits multiple definitions for the same function Patterns describe combinations of values that can be passed to the function Each pattern is checked in sequence The first matching pattern executes 10

Pattern Matching Convert the following truth table into a Haskell Function: a b result False False True False True True True False False True True True 11

Pattern Matching Patterns can include a mixture of formal parameter variables and values Example: Construct a function, named mydiv, which divides a floating point numerator by a floating point denominator. The function should report an error if the denominator is 0. 12

Pattern Matching Works well for a small number of special cases Unable to handle two large collections of values like all positive integers and all negative integers Pattern order matters More specific patterns must be listed first Patterns can be applied to any data type By convention, _ is used for formal parameter variables that are not used in the function body 13

Guards Guards Permit a function s behavior to vary based on arbitrary expressions Often contain relational operators Less than Less than or equal Greater than Greater than or equal Equal Not equal 14

Guards Example: Construct a comparison function that takes one integer parameter, x. It will return 1 when x is less than 0 0 when x is equal to 0 1 when x is greater than 0 15

Combining Pattern Matching and Guards Pattern matching and guards can be combined Guards apply to the pattern that immediately precede them If none of the guards for a pattern evaluate to true, Haskell will move on to the next pattern Example: An alternative implementation of the comparison function 16

Guards Guards are evaluated in order Only the statement associated with the first guard that evaluates to true is executed Example: Convert a character from lowercase to uppercase Other characters should be returned unchanged 17

if then else Can be used within another expression Analogous to Java and C++ ternary conditional, or Python s conditional expression Example: Write a function that takes a character as its only parameter. The function will return a string containing a message that indicates whether or not the character is uppercase. For example A is an uppercase letter or b is not an uppercase letter. 18

case Pattern matching on an arbitrary expression Example: Write a function that reports whether or not a character is a vowel Should work for both upper and lowercase letters Don t want to list both the uppercase and lowercase vowels Y is sometimes a vowel 19

Summary Most languages provide multiple decision making constructs Imperative and object oriented languages if, if else, if elif else Switch / case Conditional operator / conditional expressions Haskell Pattern matching Guards if then else case 20