ECE 103 Engineering Programming Chapter 22 Selection

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 4 Making Decisions.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Conditional Statement Chapter 8. Conditional Statements Are statements that check an expression then may or may not execute a statement or group of statement.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Copyright 2003 Scott/Jones Publishing Making Decisions.
ECE 103 Engineering Programming Chapter 18 Iteration Herbert G. Mayer, PSU CS Status 7/19/2015 Initial content copied verbatim from ECE 103 material developed.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Selection-making Decisions Selection allows you to choose between two or more possible program flow --- it lets you make decisions in your program. Examples.
Chapter Making Decisions 4. Relational Operators 4.1.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Dr. Sajib Datta Jan 23,  A precedence for each operator ◦ Multiplication and division have a higher precedence than addition and subtraction.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Dr. Sajib Datta Sep 3,  A new operator used in C is modulus operator: %  % only used for integers, not floating-point  Gives the integer.
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
CSE1301 Sem Selection Lecture 25 Lecture 9: Selection.
‘C’ Programming Khalid Jamal.
REPETITION CONTROL STRUCTURE
Selection (also known as Branching) Jumail Bin Taliba by
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Decisions Chapter 4.
Chapter 4: Making Decisions.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Chapter 4 (Conditional Statements)
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Condition Statements.
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Making Decisions.
Introduction to Programming
Chapter 7 Conditional Statements
Topics 4.1 Relational Operators 4.2 The if Statement
The Java switch Statement
ECE 103 Engineering Programming Chapter 19 Nested Loops
ECE 103 Engineering Programming Chapter 12 More C Statements
Week 3 – Program Control Structure
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
Control Structures Lecture 6.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
ECE 103 Engineering Programming Chapter 20 Change in Flow of Control
Herbert G. Mayer, PSU CS Status 7/19/2015
ECE 103 Engineering Programming Chapter 18 Iteration
Selection Control Structure
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

ECE 103 Engineering Programming Chapter 22 Selection Herbert G. Mayer, PSU CS Status 6/2 6/19/2015 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE

Syllabus If if-else if-else if Switch Triadic Conditional Expression Nested Selection Statements

Making Decisions in Programs A selection statement uses a conditional test to control the flow of execution in a program “conditional test” is AKA “conditional expression” or “boolean expression” A conditional test contains relational and/or logical expressions Conditional test evaluates to “true” or “false”: If test is “true” (non-zero), one group of statements is executed, known as the “Then Clause” If test is “false” (zero), a different group of statements is executed

Example of 2-way true or false decision Decisions can be documented by a flowchart or by pseudocode: IF expression is true THEN Execute branch A ELSE Execute branch B END IF expression branch A branch B true false Example of 2-way true or false decision

Selection Statements in C In C, logic states have these definitions: “false” is the zero value (e.g., 0, 0.0, '\0') “true” is any non-zero value (e.g., -1, 5, 12.4, 'A’) C has three types of selection statements based on the if keyword: if if–else if–else if any number of times C has an additional selection called switch

if pre-code; if (expression) Statement; post-code; if expression is Execution Sequence true ( != 0 ) Statement is executed Execution then continues at post-code false ( == 0 ) Statement is skipped Execution continues at post-code

expression must be inside parentheses ( ). Statement can be a single statement or a block: if (expression) Statement; /* Single statement */ if (expression) { Statement_1; /* Statement block */  Statement_k; } All statements in the block are executed if the expression is true.

Example: Note: Indentation improves clarity. #include <stdio.h> #define TRUE 1 #define FALSE 0 #define LO_LIMIT 20 #define HI_LIMIT 100 int main( void ) { // main int N; /* Input value */ int low = FALSE, high = FALSE; printf( "Enter N: ” ); scanf( "%d", &N ); /* Check input range */ if( N < LO_LIMIT ) low = TRUE; if( N > HI_LIMIT ) high = TRUE; if( low || high ) printf("Out of range.\n"); if( !low && !high ) printf("Within range.\n"); return 0; } if( temperature <= 65 ) turn_heat_on = 1; if( temperature > 65 ) turn_heat_on = 0; if( x < 0 ) { printf("x is negative.\n” ); } //end if y = abs(x); Note: Indentation improves clarity. 7

if–else pre-code; if (expression) Statement_T; else Statement_F; post-code; pre-code expression post-code Statement_T T F Statement_F if expression is Execution Sequence true ( != 0 ) Statement_T is executed Execution continues at post-code false ( == 0 ) Statement_F is executed

Example: if( temperature <= 65 ) turn_heat_on = 1; else #include <stdio.h> #define TRUE 1 #define FALSE 0 #define LO_LIMIT 20 #define HI_LIMIT 100 int main( void ) { // main int N; /* Input value */ printf("Enter N: "); scanf("%d", &N); /* Check input range */ if( N < LO_LIMIT || N > HI_LIMIT ) printf("Out of range.\n"); else printf("Within range.\n"); // end if return 0; } if( temperature <= 65 ) turn_heat_on = 1; else turn_heat_on = 0; if( age >= 18 ) { printf( "Adult\n” ); allow_vote = 1; }else{ printf( "Pre-Adult\n” ); allow_vote = 0; } //end if 9

Example: /* This is wrong! */ Write code that does this: if( y ) printf( "Yes!” ); else m = -1; is actually seen by the compiler as Write code that does this: if y is true, then set m to 1 and display "Yes!". Otherwise, set m to -1 and display nothing. /* This is correct */ if( y ) { m = 1; printf( "Yes!” ); }else{ m = -1; } //end if 10

if–else if pre-code; if (expression_1) Statement_1; else if (expression_2) Statement_2; else Statement_3; post-code; pre-code expression_1 post-code Statement_1 T F expression_2 Statement_2 Statement_3 Note: It is else if, not elseif.

Example: if( x > 0 ) { printf("Positive\n"); p_count++; #include <stdio.h> int main( void ) { // main int score; /* Numeric grade */ char grade; /* Letter grade */ printf("Enter score: "); scanf("%d", &score); /* Check grade brackets */ if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; printf("Grade = %c\n", grade); return 0; } //end main if( x > 0 ) { printf("Positive\n"); p_count++; }else if( x < 0 ) { printf( "Negative\n” ); n_count++; }else{ printf( "Zero\n” ); z_count++; } //end ifs 12

switch switch (expression) if (expression==const_1) { { { { case const_1: Statements_1; Statements_1; } break; else if (expression==const_2) case const_2: { Statements_2; Statements_2; break; } … … default: else Statements_d; { break; Statements_d; } //end switch } //end if

A case value cannot be a string or floating-point number expression must be inside parentheses and evaluate to a single char or integer value A case value must evaluate to a single char or integer constant that is known at compile-time A case value cannot be a string or floating-point number If expression matches a case value, then its associated statements are executed until a break is encountered 14

When break is encountered, the switch exits and execution continues at post-code If no break exists in a case block, execution “falls through” to the following case default handles the “none of the above” case. It can be omitted if not needed 15

Example: switch(experience) { case 'n': printf("Newbie\n"); N++; #include <stdio.h> #include "myfunctions.h" #define WARNING 1 #define DANGER 2 #define PANIC 3 int main (void) { int status, num_warnings = 0; scanf("%d", &status); switch (status) case WARNING: printf("What?\n"); num_warnings++; break; case DANGER: printf("Leave now!\n"); notify_friends(); case PANIC: printf("HELP ME!!!!!\n"); freak_out(10); default: printf("All is fine.\n"); } return 0; switch(experience) { case 'n': printf("Newbie\n"); N++; break; case 'a': disp('Amateur'); A++; case 'p': case 'P': printf("Professional\n"); P++; } 16

Tip: Selection Ordering To improve the performance of a multi-conditional selection, arrange it in order of most likely occurrence. Example: Use an if-else if selection to test a character variable. The character value can be 'a', 'b', 'c', 'd', or 'e'. They are not all equally likely. Sorted from most likely to occur to least likely to occur: 'c', 'd' 'b' 'a' Assume c and d are equally likely. Inefficient ordering: if (ch == 'a') {…} else if (ch == 'b') else if (ch == 'c') else if (ch == 'd‘) Better arrangement: if (ch=='c' || ch=='d') {…} else if (ch == 'b') else if (ch == 'a') MOST LEAST 17

Triadic Conditional Expression var = (condition) ? expr1 : expr2; is equivalent to if (condition) var = expr1; else var = expr2; Both expressions should evaluate to the same data type as var. 18

Example: /* If voltage > 2, then set state to high (1) else set state to low (0) */ state = (voltage > 2.0) ? 1 : 0; /* Sinc calculation handles x == 0 case */ y = (fabs(x) < 1e-8) ? 1.0 : sin(x)/x; 19

Nested Selection Statements The body of a selection statement can contain another selection statement within it. Each else is matched to the nearest if or else if. 20

Example: Convert the if-else if to a nested if. /* if-else if version */ if (x == 0) t++; else if (x==1 || x==2) printf("zen state\n"); else if (x < 0) { m = sin(Q); f = 3 * m * sqrt(m); } else printf("Moo\n"); /* Nested if version */ if (x == 0) t++; else { if (x==1 || x==2) printf("zen state\n"); if (x < 0) m = sin(Q); f = 3 * m * sqrt(m); } printf("Moo\n"); 21

Example: Use indenting to make it clear what you really mean! if (t >= 0 && t < 100) if (F < 1500e3) flim = 143.5; else { flim = 500.0; overload = 1; if (cps == 'x') cnt++; } else if (t2 > 750) printf("D22 max\n"); if (!mox) mox = 1; pc += 10; done = 1; if (t >= 0 && t < 100) if (F < 1500e3) flim = 143.5; else { flim = 500.0; overload = 1; if (cps == 'x') cnt++; } else if (t2 > 750) printf("D22 max\n"); if (!mox) mox = 1; pc += 10; done = 1; Use indenting to make it clear what you really mean! 22

Nesting can lead to ambiguous situations Nesting can lead to ambiguous situations. If necessary, use braces to clarify your intentions. Example: if (x >= 0) if (y > 5) printf("Hi!\n"); else printf("Goodbye!\n"); Is the "else" associated with the first or second "if"? if (x >= 0) if (y > 5) printf("Hi!\n"); else printf("Goodbye!\n"); if (x >= 0) { /* Braces clarify */ if (y > 5) printf("Hi!\n"); else printf("Goodbye!\n"); } 23