5. Selection: If and Switch Controls

Similar documents
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Chapter One Introduction to Programming

Introduction to Python

Chapter 5. Selection 5-1

Informatica e Sistemi in Tempo Reale

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Moving from CS 61A Scheme to CS 61B Java

6. Control Structures

Lecture 2 Notes: Flow of Control

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

JavaScript: Control Statements I

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Writing Control Structures

Sources: On the Web: Slides will be available on:

Object Oriented Software Design

Chapter 8 Selection 8-1

Object Oriented Software Design

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Selection Statements

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Conditions & Boolean Expressions

Two-way selection. Branching and Looping

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Introduction to Java

The C Programming Language course syllabus associate level

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

Logic in Computer Science: Logic Gates

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Chapter 2: Elements of Java

Statements and Control Flow

ALGORITHMS AND FLOWCHARTS

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Notes on Algorithms, Pseudocode, and Flowcharts

I PUC - Computer Science. Practical s Syllabus. Contents

Java Basics: Data Types, Variables, and Loops

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Decision Logic: if, if else, switch, Boolean conditions and variables

C++ Language Tutorial

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Python Programming: An Introduction To Computer Science

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

COMPUTER SCIENCE (5651) Test at a Glance

Pseudo code Tutorial and Exercises Teacher s Version

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Flowcharting, pseudocoding, and process design

1 Description of The Simpletron

The design recipe. Programs as communication. Some goals for software design. Readings: HtDP, sections 1-5

Computer Programming I

VB.NET Programming Fundamentals

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

C A R I B B E A N E X A M I N A T I O N S REPORT ON CANDIDATES S WORK IN THE CARIBBEAN SECONDARY EDUCATION CERTIFICATE EXAMINATION MAY/JUNE 2012

Fundamentals of Programming

Exercise 4 Learning Python language fundamentals

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Chapter 3 Operators and Control Flow

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

The previous chapter provided a definition of the semantics of a programming

Basics of I/O Streams and File I/O

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Pemrograman Dasar. Basic Elements Of Java

C++ INTERVIEW QUESTIONS

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Example of a Java program

13 Classes & Objects with Constructors/Destructors

Problem Solving Basics and Computer Programming

The While Loop. Objectives. Textbook. WHILE Loops

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

TIP: To access the WinRunner help system at any time, press the F1 key.

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Microsoft Excel Tips & Tricks

USC Marshall School of Business Academic Information Services. Excel 2007 Qualtrics Survey Analysis

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

While Loop. 6. Iteration

1.3 Conditionals and Loops

Number Representation

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

6.087 Lecture 2 January 12, 2010

ARIZONA CTE CAREER PREPARATION STANDARDS & MEASUREMENT CRITERIA SOFTWARE DEVELOPMENT,

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Introduction to Java. CS 3: Computer Programming in Java

Python Evaluation Rules

arrays C Programming Language - Arrays

El Dorado Union High School District Educational Services

Tutorial on C Language Programming

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Topic 11 Scanner object, conditional execution

Transcription:

Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Spring 2006

Computer Science I CS 135 0. Course Presentation 1. Introduction to Programming 2. Functions I: Passing by Value 3. File Input/Output 4. Predefined Functions 5. If and Switch Controls 6. While and For Loops 7. Functions II: Passing by Reference 8. 1-D and 2-D Arrays 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 2

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures c. Logical Expressions d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 3

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures What are control structures? Selection structures Repetition structures (next week) b. If / Else Selection Structures c. Logical Expressions d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 4

5.a Control Structures What are control structures? Reminder: there are six basic computer operations 1. a computer can receive information (Get, Read, etc.) 2. a computer can put out information (Display, etc.) 3. a computer can perform arithmetic (Add, Divide, etc.) 4. a computer can assign a value to a variable or memory location (Set, Initialize, etc.) 5. a computer can compare variables and select one of two alternate actions selection structures 6. a computer can repeat a group of actions repetition structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 5

Structure theorem 5.a Control Structures What are control structures? it is possible to write any computer program by using only three basic control structures that are easily represented in pseudocode: sequence structures selection structures repetition structures Sequence structures introduce branching ( jumps ) in the sequential logic straightforward execution of one processing step after another sequence of pseudocode statements: do this, do that, then this, then that, etc. 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 6

Selection structures 5.a Control Structures What are control structures? condition and choice between two actions, depending on whether the condition is true or false represented by the pseudocode keywords IF, THEN, ELSE, and ENDIF Repetition structures block of statements to be executed repeatedly, as long as a condition is true represented by the pseudocode keywords WHILE and ENDWHILE 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 7

5.a Control Structures What are control structures? Sequence, selection and repetition structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 8

5.a Control Structures Selection structures A computer can compare variables and select one of two alternate actions selection structures examples: one-way if it starts to rain, go inside the building two-way if the car starts, drive; otherwise, take the bus pseudocode examples: IF age >= 12 THEN ENDIF Prompt for entrance fee One-way selection IF student is female THEN ELSE ENDIF Add 1 to female count Add 1 to male count Two-way selection 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 9

5.a Control Structures Selection structures Anatomy of an if /else selection structure (pseudocode) the header is a logical expression the body contains actions that are performed (or not) depending on the header header body IF (true or false logical expression) [THEN] actions that are performed if true ELSE alternative body other actions that are performed if false Anatomy of an if / else selection structure 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 10

5.a Control Structures Repetition structures (next week) A computer can repeat a group of actions repetition structures examples: calculate 100 student grades pour water in the saucepan until it is full cook the pasta until it is al dente pseudocode example: WHILE water_level < pan_height Add 1 tablespoon to water_volume water_level = water_volume / pan_surface ENDWHILE 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 11

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures What are control structures? Selection structures Repetition structures (next week) b. If / Else Selection Structures c. Logical Expressions d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 12

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures One-way selection structure: if Two-way selection structure: if else Compound statement selection structures Nested selection structures Conditional operator c. Logical Expressions d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 13

5.b If / Else Selection Structures One-way selection structure: if A one-way selection decides whether to execute a statement or not 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 14

5.b If / Else Selection Structures One-way selection structure: if Syntax of a one-way selection if (expression) if (age >= 12) statement pay_entrance(); if is a reserved keyword expression is a logical expression sometimes called a decision maker because it decides whether to execute the statement that follows it or not statement follows expression and can be any C++ statement sometimes called the action statement statement is executed if the value of expression is true statement is bypassed if the value is false: the program goes to the next statement directly 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 15

5.b If / Else Selection Structures Two-way selection structure: if else A two-way selection decides whether to execute one statement or another 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 16

5.b If / Else Selection Structures Two-way selection structure: if else Syntax of a two-way selection if (expression) if (age >= 12) statement1 pay(8.00); else else statement2 pay(3.50); else is also a reserved keyword expression is a logical expression statement1 and statement2 can be any C++ statements statement1 is executed if the value of expression is true statement2 is executed if the value is false after that, if there was not failure or early exit, the program goes to the next statement after the if / else structure 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 17

5.b If / Else Selection Structures Compound statement selection structures Compound statement the body of an if/else structure can contain multiple C statements a block of statements is called a compound statement and must be surrounded with curly braces { } if (expression) { if (age >= 12) { statement1 cout << "adult"; statement2 pay(8.00); statement3... } } else { else { statement4 cout << "child"; statement5 pay(3.50); } } 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 18

5.b If / Else Selection Structures Nested selection structures If/else structures can be inserted inside other if/else structures some statements inside the body of a selection structure can themselves be if/else selection structures if (expression1) { statement1 } else { if (expression2) { statement2 } else { statement3 } } same code if (expression1) { statement1 } else if (expression2) { statement2 } else { statement3 } 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 19

5.b If / Else Selection Structures Nested selection structures Programming is like a construction game control structures can be nested in other control structures if ( ) { } else { } if ( ) { } else { } however, too much nesting inside the same area of code is not good programming practice 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 20

5.b If / Else Selection Structures Nested selection structures Programming is like a construction game breaking up into FUNCTIONS is better practice if ( ) { } else { myfunction( ); myfunction( ) { if ( ) { } else { } it will generally depend on the size of a compound statement: if it gets too big, cut it out and put it in a function 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 21 } }

5.b If / Else Selection Structures Conditional operator The conditional operator is a one-line shortcut for if the conditional operator is used exclusively for conditional assignment statements involving the same variable instead of if (expression) { x = value1; } else { x = value2; } you can write x = (expression)? value1 : value2; using the question mark? and colon : symbols 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 22

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures One-way selection structure: if Two-way selection structure: if / else Compound statement selection structures Nested selection structures Conditional operator c. Logical Expressions d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 23

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures c. Logical Expressions Relational operators Logical (Boolean) operators Order of precedence d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 24

5.c Logical Expressions In this section, we look at the header of if / else selection structures IF (true or false logical expression) ELSE actions performed if true actions performed if false 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 25

5.c Logical Expressions Relational operators Relational operators allow to make comparisons a relational operator is a binary operator: it takes two numeric operands yields a boolean result, true or false false also evaluates as 0 and true evaluates as nonzero 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 26

5.c Logical Expressions Relational operators Relational operators allow to make comparisons examples: 8 < 8.01 8 less than 8.01 6!= 6.0 6 not equal to 6.0 7 >= 7 7 greater than or equal to 7 'a' == 'b' char a equal to b true false true false unlike the assignment operator = it is ok to have expressions on both sides of a relational operator, for example if x is 6: (7 + x/5.0) > (x + 2.1) is true because of precision problems, use caution when equating floating-point expressions (using ==) 2.0/7 + 5.0/7 == 1.0 is likely to be false 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 27

5.c Logical Expressions Relational operators Relational operators allow to make comparisons relational operators are strictly binary 0 <= x < 10 is illegal syntax it must be written: (0 <= x) && (x < 10) the operator && ( and ) is a logical operator; we will look at logical operators in the next slides caution when comparing different data types, such as numbers and characters: 8 < '5' is true! alphabetically comparing strings using rel. ops is ok in C++ "apple" <= "orange" (but is not ok in C or Java!) 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 28

5.c Logical Expressions Relational operators Comparing characters and strings relational operators compare the characters ASCII codes 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 29

5.c Logical Expressions Logical (Boolean) operators Logical operators allow to combine logical expressions there are 3 main logical operators in C++ && the binary and operator the binary or operator! the unary not operator each logical operator takes only logical values, true and false, as operands yields only a logical value, true and false, as a result 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 30

The! ( not ) operator 5.c Logical Expressions Logical (Boolean) operators reverses the value of its logical operand examples:!(8 > 15) not (8 is greater than 15)!(6 == 6) not (6 is equal to 6)!('a'>'b') not ( a is greater than b ) true false true 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 31

5.c Logical Expressions Logical (Boolean) operators The && ( and ) operator is true if and only if both of its logical operands are true examples: one false operand is enough to yield false (14 >= 5) && ('A' == 'B') (14!= 5) && ('A' < 'B') false true (14 < 5) &&!('$' >= '*')!(14 < 5) && 3?? never mind false true 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 32

5.c Logical Expressions Logical (Boolean) operators Boolean algebra with && ( and ) important equivalences among expressions containing && Logical expression x && true x && false x && x x &&!x x && y x && (y && z) Equivalent expression x false x false y && x (x && y) && z 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 33

The ( or ) operator 5.c Logical Expressions Logical (Boolean) operators is true if at least one of its logical operand is true examples: (14 == 5) ('A' <= 'B')!(14!= 5) ('A' == 'B') (14 > 5)!('$' >= '*')!(14 > 5) 0 one true operand is enough to yield true?? never mind true false true false 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 34

5.c Logical Expressions Logical (Boolean) operators Boolean algebra with ( or ) important equivalences among expressions containing Logical expression x true x false x x x!x x y x (y z) Equivalent expression true x x true y x (x y) z 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 35

5.c Logical Expressions Logical (Boolean) operators Boolean algebra with && and important equivalences among expressions with && and Logical expression x (y && z) x (x && z) x && (y z) x && (x z)!(x y)!(x && y) Equivalent expression (x y) && (x z) x (x && y) (x && z) x!x &&!y!x!y De Morgan s laws 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 36

5.c Logical Expressions Order of precedence How to evaluate complex logical expressions expressions can mix arithmetic, relational and logical operators:!(5 + 3 <= 9) 6 < 15 && 7!= 8 evaluation follows a priority scheme 1. arithmetic operators 2. relational operators 3. logical operators 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 37

5.c Logical Expressions Order of precedence Example of precedence in logical expressions bool found = true; double x = 5.2, y = 3.4; int a = 5, b = 8, n = 0; char ch = '$'; Logical expression!found && x >= 0!(found x < 0) x + y <= 20.5 n < 1 n > 100 'A' <= ch && ch <= 'Z' 'a' <= ch && ch <= 'z' a + 2 <= b && found Value false false true true false true 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 38

x 5.c Logical Expressions Order of precedence Building expressions is like a construction game + 39 y!= > &&! if ( ) 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 39

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures c. Logical Expressions Relational operators Logical (Boolean) operators Order of precedence d. Switch Selection Structures 2/27/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 40

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures c. Logical Expressions d. Switch Selection Structures Switch syntax and rules Typical switch examples 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 41

5.d Switch Selection Structures Switch syntax and rules 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 42

5.d Switch Selection Structures Switch syntax and rules A switch structure can replace multiple nested if/else it is used exclusively in the case where the same integral expression or variable can evaluate to multiple constant values if (expr == val1) statement1 else if (expr == val2) statement2 else if (expr == val3) statement3 else statement0 same code switch (expr) { case val1: statement 1 break; case val2: statement 2 break; case val3: statement 3 break; default: statement0 break; } 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 43

5.d Switch Selection Structures Switch syntax and rules (Fun?) facts about switch selection structures a switch selection structure uses four special keywords: switch, case, default, break the expression in the header is evaluated first and can only yield an integer value the value of the expression determines which corresponding statement is selected for execution each constant case value must appear only once each case label may be followed by one statement or a compound statement (here, curly braces are not necessary) the break statement should appear after each statement; if it doesn t, then the next statement will also be executed 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 44

5.d Switch Selection Structures Switch syntax and rules Rules of switch selection structures when value of the expression is matched against a case value: statements execute at that point until a break statement is found or the end of switch structure is reached if value of the expression does not match any of the case values: statements following the default label execute if there is neither a matching value, nor a default label: the entire switch statement is skipped in any case, wherever it is found, a break statement causes an immediate exit from the switch structure 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 45

5.d Switch Selection Structures Typical switch examples Switch example 1: conditional conversion scheme a switch can convert when there is no simple one-line formula switch (score/10) { case 0: case 1: case 2: case 3: case 4: case 5: grade = 'F'; break; case 6: grade = 'D'; break; case 7: grade = 'C'; break; case 8: grade = 'B'; break; case 9: case 10: grade = 'A'; break; default: cout << "Invalid score: " << score; } 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 46

5.d Switch Selection Structures Typical switch examples Switch example 2: branching upon user input a switch can perform different actions depending on user input char answer; cout << "Please select one option from..."; cin >> answer; switch (answer) { case 'p': play_game(); break; case 'h': display_help(); break; case 'q': quit(); break; default: cout << "Invalid selection: " << answer; } 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 47

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures c. Logical Expressions d. Switch Selection Structures Switch syntax and rules Typical switch examples 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 48

Computer Science I CS 135 5. Selection: If and Switch Controls a. Control Structures b. If / Else Selection Structures c. Logical Expressions d. Switch Selection Structures 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 49

Computer Science I CS 135 0. Course Presentation 1. Introduction to Programming 2. Functions I: Passing by Value 3. File Input/Output 4. Predefined Functions 5. If and Switch Controls 6. While and For Loops 7. Functions II: Passing by Reference 8. 1-D and 2-D Arrays 3/1/2006 CS 135 - Computer Science I - 5. Selection: If and Switch Controls 50