Selection Statements. Pseudocode

Similar documents
Chapter 3 Selection Statements

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Selections. CSE 114, Computer Science 1 Stony Brook University

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

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

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Lecture 1 Java SE Programming

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

BRANCHING if-else statements

CS1150 Principles of Computer Science Boolean, Selection Statements

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

Lecture 3 Tao Wang 1

Eng. Mohammed S. Abdualal

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

In this lab, you will learn more about selection statements. You will get familiar to

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

3chapter C ONTROL S TATEMENTS. Objectives

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

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

Chapter 2, Part III Arithmetic Operators and Decision Making

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

Chapter 3: Decision Structures

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 3: Decision Structures

COMP Primitive and Class Types. Yi Hong May 14, 2015

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

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

BASIC ELEMENTS OF A COMPUTER PROGRAM

Arithmetic Expressions in C

LECTURE 04 MAKING DECISIONS

Python - Week 3. Mohammad Shokoohi-Yekta

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

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

Topics. Chapter 5. Equality Operators

Chapter 3: Decision Structures

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

Computer System and programming in C

LECTURE 3 C++ Basics Part 2

Fundamentals of Programming

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

Information Science 1

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Chapter 3. Selections

FRAC: Language Reference Manual

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

Fundamental of Programming (C)

Information Science 1

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

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

UNIT- 3 Introduction to C++

Relational Operators and if. Class 10

1.3b Type Conversion

Basics of Java Programming

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

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

Chapter 4: Making Decisions

egrapher Language Reference Manual

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

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

Chapter 4: Making Decisions

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Chapter 4: Basic C Operators

CS102: Variables and Expressions

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Outline. Data and Operations. Data Types. Integral Types

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Chapter 2: Using Data

(2-1) Numeric Expressions in C H&K Chapter 2. Instructor - Andrew S. O Fallon CptS 121 (August 27, 2018) Washington State University

Reserved Words and Identifiers

Chapter 3 Structure of a C Program

Lecture 2 Tao Wang 1

Computer Programming CS F111

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Chapter 6 Primitive types

CIS 110: Introduction to Computer Programming

Operators & Expressions

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

DEPARTMENT OF MATHS, MJ COLLEGE

Chapter 2 Primitive Data Types and Operations. Objectives

Lecture 5: Making Decisions

Chapter 2: Using Data

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

CONDITIONAL EXECUTION

Chapter 2: Basic Elements of C++

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

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.

UEE1302(1102) F10: Introduction to Computers and Programming

MODULE 02: BASIC COMPUTATION IN JAVA

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Operators and Expressions:

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Transcription:

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 the result; 1

Use conditions Selection Statement Conditions are in Boolean expression The bool Type and Operators Compare two values, such as whether i is greater than j C++ provides six relational operators (also known as comparison operators) Can also compare character Operator Name Example Result < less than 1 < 2 true <= less than or equal to 1 <= 2 true > greater than 1 > 2 false >= greater than or equal to 1 >= 2 false == equal to 1 == 2 false!= not equal to 1!= 2 true == is equal to operator = is assignment operator 2

One-way if Statements if (booleanexpression) statement(s); if (radius >= 0) area = radius * radius * PI; printf("the area for the circle of %f radius is %f, radius, area); Boolean Expression false (radius >= 0) false true true Statement(s) area = radius * radius * PI; printf("the area for the circle of %f radius is %f, radius, area); (a) (b) Boolean Expression Enclosed in parentheses Outer parentheses required if ((i > 0) && (i < 10)) pritnf( i is an integer between 0 and 10 ); (a) Equivalent Braces can be omitted if the block contains a single statement if ((i > 0) && (i < 10)) printf( i is an integer between 0 and 10 ); (b) 3

Boolean Expression Adding a semicolon at the end of an if clause is a common mistake This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error This error often occurs when you use the next-line block style if (radius >= 0); area = radius * radius * PI; printf("the area is %f", area); (a) Logic Error Equivalent if (radius >= 0) ; area = radius * radius * PI; printf("the area is %f", area); (b) Empty Body Logical Operators (Boolean Operators) Combination of several conditions Name Operator Description Not! Logical negation And && Logical conjunction Or Logical disjunction 4

Truth Table p!p true false false True Logical negation p1 p2 p1 p2 false false false false true true true false true true true true Logical disjunction p1 p2 p1 && p2 false false false false true false true false False true true true Logical conjunction Conditional Short-circuit AND operator p1 && p2 If p1 is false, p2 is not evaluated Short-circuit OR operator p1 p2 If p1 is true, p2 is not evaluated 5

Leap Year Write a program that lets the user enter a year and checks whether it is a leap year. A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400. So you can use the following Boolean expression to check whether a year is a leap year: (year % 4 == 0 && year % 100!= 0) (year % 400 == 0) Mathematics: x < y < z (x < y) &&(y < z) Conversion 6

The if... Statement if (booleanexpression) statement(s)-for-the-true-case; statement(s)-for-the-false-case; true Statement(s) for the true case Boolean Expression false Statement(s) for the false case Nested if Statements if (i > k) if (j > k) printf("i and j are greater than k ); printf("i is less than or equal to k ); 7

Multiple Alternative if Statements if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F'; Equivalent if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F'; Multiple if Statements The 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) printf("a"); printf("b"); (a) Equivalent This is better with correct indentation int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) printf("a"); printf("b") (b) 8

Multiple if Statements Nothing is printed from the preceding statement. To force the clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) printf ("A ); printf( "B ); This statement prints B. Expression Statement if (number % 2 == 0) even = true; even = false; (a) Equivalent This is better bool even = number % 2 == 0; (b) if (even == true) printf("it is even."); (a) Equivalent This is better if (even) printf("it is even."); (b) 9

Common Errors in Selection Statements Forgetting Necessary Braces if (radius >= 0) area = radius * radius * PI; printf("the area is %f,area); if (radius >= 0) area = radius * radius * PI; printf("the area is %f,area); (a) Wrong (b) Correct Common Errors in Selection Statements Wrong Semicolon at the if Line Logic Error if (radius >= 0); area = radius * radius * PI; printf("the area is %f,area); Equivalent Empty Body if (radius >= 0) ; area = radius * radius * PI; printf("the area is %f,area); (a) (b) 10

Common Errors in Selection Statements Mistakenly Using = for == if (count = 1) printf( count is zero\n ); printf( count is not zero\n ); Common Errors in Selection Statements Redundant Testing of Boolean Values if (even == true) printf("it is even."); (a) Equivalent This is better if (even) printf("it is even."); (b) 11

Compute BMI BMI Interpretation below 16 serious underweight 16-18 underweight 18-24 normal weight 24-29 overweight 29-35 seriously overweight above 35 gravely overweight Compute Taxes 12

switch Statements Handle multiple conditions switch (status) case 0: compute taxes for single filers; case 1: compute taxes for married file jointly; case 2: compute taxes for married file separately; case 3: compute taxes for head of household; default: printf("errors: invalid status"); switch Statement Flow Chart status is 0 Compute tax for single filers break status is 1 Compute tax for married file jointly break status is 2 Compute tax for married file separatly break status is 3 Compute tax for head of household break default Default actions Next Statement 13

switch Statement Rules The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value1,..., and valuen must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1,..., and valuen are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x. switch (switch-expression) case value1: statement(s)1; case value2: statement(s)2; case valuen: statement(s)n; default: statement(s)-for-default; switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. switch (switch-expression) case value1: statement(s)1; case value2: statement(s)2; case valuen: statement(s)n; default: statement(s)-for-default; The casestatements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end. 14

Fall-Through Behavior Multiple cases matched in switch statement that will be executed until a break or end of the switch is reached switch(ch) case a : printf(ch) case b : printf(ch); case c : printf(ch); Formatting Output Operator setprecision(n) fixed showpoint setw(width) left right Description sets the precision of a floating-point number displays floating-point numbers in fixed point notation causes a floating-point number to be displayed with a decimal point with trailing zeros even if it has no fractional part specifies the width of a print field justifies the output to the left justifies the output to the right 15

Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) 1? Operator Precedence Evaluation an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule Precedence rule: var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==,!=; (Equality) && (Conditional AND) Short-circuit AND (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator) 16

Associativity a b + c d is equivalent to ((a-b)+c)-d A=b+=c = 5 is equivalent to a =(b+=(c=5)) Reference Hanly, J (2010), Problem Solving and Program Design in C, Addison Wesley, 6 th Ed, Chapter 4 Deitel, P. 2012. C: How to Program. Pearson Education, Inc Liang, Y. D. 2007. Introduction to Programming with C++. Pearson Education, Inc. Chapter 3 17