Computer Science & Engineering 150A Problem Solving Using Computers

Similar documents
Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

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

Introduction to C Programming

Introduction to Computing Lecture 05: Selection (continued)

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

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

Checking Multiple Conditions

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

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Object Oriented Programming with Java

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

Chapter 5: Control Structures

5. Selection: If and Switch Controls

Full file at C How to Program, 6/e Multiple Choice Test Bank

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Control Structures in Java if-else and switch

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

BRANCHING if-else statements

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

UEE1302(1102) F10: Introduction to Computers and Programming

Control Structures in Java if-else and switch

Flow Control. CSC215 Lecture

Lecture 3 Tao Wang 1

Control Structure: Selection

Lesson #4. Logical Operators and Selection Statements. 4. Logical Operators and Selection Statements - Copyright Denis Hamelin - Ryerson University

Operators. Java operators are classified into three categories:

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

APCS Semester #1 Final Exam Practice Problems

Lecture 5 Tao Wang 1

Chapter 4 - Notes Control Structures I (Selection)

printf( Please enter another number: ); scanf( %d, &num2);

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

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

DECISION MAKING STATEMENTS

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

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

Topics. Chapter 5. Equality Operators

Conditionals. CSE / ENGR 142 Programming I. Chapter 4. Conditional Execution. Conditional ("if ") Statement. Conditional Expressions

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

QUIZ: What value is stored in a after this

Fundamental of Programming (C)

Operators And Expressions

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

C: How to Program. Week /Mar/05

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

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Introduction to Java & Fundamental Data Types

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

Chapter 2 - Introduction to C Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

Programming for Engineers Introduction to C

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

(4-2) Selection Structures in C H&K Chapter 4. Instructor - Andrew S. O Fallon CptS 121 (September 12, 2018) Washington State University

Chapter 4: Control Structures I (Selection)

1007 Imperative Programming Part II

Mr. Monroe s Guide to Mastering Java Syntax

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

Programming Logic and Design Sixth Edition

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

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.

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

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Computational Expression

Chapter 2, Part III Arithmetic Operators and Decision Making

More Complex Versions of the if Statement. Class 13

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

Lecture 4 CSE July 1992

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

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

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Computer Components. Software{ User Programs. Operating System. Hardware

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Flow of Control. Chapter 3

Conditional Statement

Conditions, logical expressions, and selection. Introduction to control structures

Chapter 4. Flow of Control

5. Control Statements

Decision Making -Branching. Class Incharge: S. Sasirekha

CS102: Variables and Expressions

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

Computer Programming : C++

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

Add Subtract Multiply Divide

Fundamentals of Programming Session 4

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Transcription:

Computer Science & Engineering 150A Problem Solving Using Computers Lecture 04 - Conditionals Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Control Structure Conditions if statements 2 / 1 Control Structure Control structures: Control the flow of execution in a program or function. Enable you to combine individual instructions into a single logical unit with one entry point (i.e. int main(void) {) and one exit point (return 0; }). Three kinds of structures to control execution flow: Sequence Selection Repetition 3 / 1

Sequential Flow Compound statement: Written as a group of statements Bracketed by { and } Used to specify sequential flow All statements are unconditionally executed Order is important Statement01; Statement02; Statement03; 4 / 1. Selection Flow Selection control structure: Evaluates criteria to determine which alternative path to follow. A control structure determines which statement(s) to execute Statements are mutually exclusive Statement01; Selection Control Structure Statement02;. 5 / 1 Selection Flow Conditions Definition A condition is an expression that is either true or false. A program chooses alternative paths of computation by testing one or more conditions. (ConditionEval == 1) true, (ConditionEval == 0) false. The resting heart rate is a good indicator of health if (resting heart rate < 75) then you are in good health. if resting heart rate is 80, ConditionEval is false. if resting heart rate is 50, ConditionEval is true. if resting heart rate is 75, what is ConditionEval? 6 / 1

Relational and Equality Operators Operator Meaning Type < less than relational > greater than relational <= less than or equal to relational >= greater than or equal to relational == equal to equality!= not equal to equality Table: Relational and Equality Operators in C 7 / 1 Relational and Equality Operators Conditions come in four forms: variable relational-operator variable Example: if(numberofstudents > numberofseats) variable relational-operator CONSTANT Example: if(numberofstudents < 5) variable equality-operator variable Example: if(numberofstudents == numberofseats) variable equality-operator CONSTANT Example: if(averagegrade == 75.0) What about more than one condition? (Example: 0 x 10) 8 / 1 Logical Operators Logical Operators: Operators that can combine conditions to make more complicated selection statements. C Syntax Meaning True When && logical And Both are true logical Or Either is true! logical Not (negation) False Table: Logical Operators in C 9 / 1

Logical Operators Logical Expressions - expressions that involve conditional statement(s) and logical operator(s). Examples: (x >= 0 && x <=10) (temperature > 90.0 && humidity > 0.90)!(x >= 0 && x <=10) What about the following: Are we going to go or not? (go!go) 10 / 1 Tautologies & Contradictions A tautology is a logical expression that is always true Any non-zero constant (1, 1.5, 8, etc.) An expression that, when simplified, always ends up being true (go!go) is always true A contradiction is a logical expression that is always false The zero constant (0) An expression that, when simplified, always ends up being false (go &&!go) is always false 11 / 1 Distributivity The logical And can be distributed over a logical expression just as multiplication can be over an algebraic expression. a(b + c) = ab + ac a && (b c) is same as (a && b) (a && c) (Here, a, b, and c are relations like x < 5) When distributing the logical Not, And and Or are reversed! Example:!(x >= 0 && x <=10) (!(x >= 0)!(x <=10)) ((x < 0) (x > 10)) Best to simplify logical expressions as much as possible, but more important to keep code readable. 12 / 1

True and False C Convention For convenience when writing we identify zero with false and one with true C does not recognize the words true, false C has no built-in Boolean type! Instead, zero is identified with false Any non-zero value is identified with true Example: -1, 0.01, 386 are all true 13 / 1 Operator Tables Logical And The result of taking a logical And with two operands is true if and only if both operands are true. Otherwise it is false. Operand A Operand B Result 0 0 0 0 1 0 1 0 0 1 1 1 14 / 1 Operator Tables Logical And The result of taking a logical Or with two operands is true if and only if at least one of the operands is true. Otherwise it is false. Operand A Operand B Result 0 0 0 0 1 1 1 0 1 1 1 1 15 / 1

Operator Tables Logical And You can only apply a logical Not to a single operand. The result is that true gets flipped to false and vice versa. Operand Result 0 1 1 0 16 / 1 Operator Precedence Order of precedence for operators Precedence Operator High Function calls! + - & (unary) * / % + - (binary) < <= >= > ==!= && Low = Table: Order of Precedence for Operators 17 / 1 Short-Circuiting If the first operand of a logical Or is true, the whole expression is true regardless of the second operand. Similarly, if the first operand of a logical And is false, the whole expression is false regardless of the second operand. (true anything) is true (false && anything) is false By convention, in either case C does not bother to evaluate the second operand. This is known as short-circuiting 18 / 1

Programming Tip Writing pseudocode will help you to write logical expressions in plain English. Translate the expressions into valid C syntax Be sure that the original and the translation are logically equivalent You can use a int type to store true/false: int someboolean = 0; 19 / 1 Comparing Characters Recall that C uses partially weak typing C treats characters as integers in the range [0, 255] Thus, it makes sense that we can compare characters using relational and equality operators. Comparisons are based on the values used to encode letters (typically ASCII; Appendix A) Example: a < e is true since (in ASCII) 97 < 101 20 / 1 Comparing Characters Exercise Assuming ASCII encoding, what are the values of the following character comparisons? 1 B <= A 2 Z == z 3 A < a 4 5 <= 7 Answer: 21 / 1

Comparing Characters Exercise Assuming ASCII encoding, what are the values of the following character comparisons? 1 B <= A 2 Z == z 3 A < a 4 5 <= 7 Answer: 1 false since 66 > 65 21 / 1 Comparing Characters Exercise Assuming ASCII encoding, what are the values of the following character comparisons? 1 B <= A 2 Z == z 3 A < a 4 5 <= 7 Answer: 1 false since 66 > 65 2 false since 90 122 21 / 1 Comparing Characters Exercise Assuming ASCII encoding, what are the values of the following character comparisons? 1 B <= A 2 Z == z 3 A < a 4 5 <= 7 Answer: 1 false since 66 > 65 2 false since 90 122 3 true since 65 < 97 21 / 1

Comparing Characters Exercise Assuming ASCII encoding, what are the values of the following character comparisons? 1 B <= A 2 Z == z 3 A < a 4 5 <= 7 Answer: 21 / 1 1 false since 66 > 65 2 false since 90 122 3 true since 65 < 97 4 true since 53 55 Comparing Characters ASCII stands for American Standard Code for Information Interchange The ASCII character set was designed to preserve alpha-numeric order, so e.g. a is strictly less than b Capital letters are less than lower-case letters 22 / 1 The if Statement if Statement with Two Alternatives (If-Then-Else) if Statement with One Alternative A Comparison of One and Two Alternative if Statements Programming Style 23 / 1

If-Then-Else Statement Conditions are used to assign boolean (T,F) values to variables Example: senior_citizen = (age >= 65) 0 or 1 is assigned to senior_citizen depending on the value of age More often, conditions are used to make a choice between alternatives, through the if statement. If the condition is true, one statement is executed, otherwise, another statement is executed. 1 if (! senior_citizen ) 2 printf (" Your hamburger is $3.50\ n"); 3 else 4 printf (" Your hamburger is $2.50\ n"); 24 / 1 if Statement with One Alternative It is not necessary to specify an alternative (else statement) An if statement can determine to execute a statement or not 1 if( senior_citizen ) 2 price = price - 1.0; 25 / 1 Programming Tip Recall that division by zero is undefined (and dangerous) You can use an if statement to avoid such errors 1 if(x!= 0) 2 quotient = quotient / x; 26 / 1

Program Style Statements following the if statements should be indented else statement is at the same indentation as the if statement Statements following the else statements should be indented 27 / 1 Programming Tip Pitfall: Do not end an if statement with a semi-colon: 1 if( price < 0); 2 printf (" The product is free!\ n"); Syntactically correct; program will compile Essentially like if(price<0){}; Will not give expected results The if statement is ended by the semicolon Thus, The product is free! will be printed regardless of the value of price 28 / 1 if Statement with Compound Statements In previous slides, if and else statements have performed only one operation C always assumes that each if or else statement will be followed by one operation If more than one statement needs to be done for an if or else, we use {} to group a set of statements into one compound statement 29 / 1

if Statement with Compound Statements 1 if( pop_today > pop_yesterday ) 2 { 3 growth = pop_today - pop_yesterday ; 4 growth_pct = 100.0 * growth / pop_yesterday ; 5 printf (" Growth percentage = %.2 f.\n", growth_pct ); 6 } 30 / 1 Another Example 1 if ( crash_test_rating_index <= MAX_SAFE_CTRI ) 2 { 3 printf (" Car #% d: safe \n", auto_id ); 4 numofsafecars = numofsafecars + 1; 5 } 6 else 7 { 8 printf (" Car #% d: unsafe \n", auto_id ); 9 numofunsafecars = numofunsafecars + 1; 10 } If you omit the braces, what happens? 31 / 1 Tracing an if Statement Verifying the correctness of a C statement before running the program Catching logical errors will save a lot of time in debugging. A hand trace or desk check is a step-by-step simulation of each step of the program, as well as how the values of the variables change at each step. 32 / 1

Nested if Statements and Multiple-Alternative Decisions No decisions: Sequential program One decision: if-then (One alternative) if(cond) statement; Decision between two alternatives: if-then-else (Two alternative statements) if(cond) statement; else statement2; Decisions between many alternatives School level 33 / 1 Nested if Statements and Multiple-Alternative Decisions 1 if (x <= 0) 2 pre_school = pre_school + 1; 3 else 4 if (x <= 12) 5 public_school = public_school + 1; 6 else 7 univ = univ + 1; 34 / 1 Nested ifs vs. Sequence of ifs I Can instead use a sequence of if statements 1 if(x <= 0) 2 pre_school = pre_school + 1; 3 if(x <= 12 && x > 0) 4 public_school = public_school + 1; 5 if(x > 12) 6 univ = univ + 1; 35 / 1

Nested ifs vs. Sequence of ifs II Not as readable: since the sequence does not clearly show that exactly one of the three assignment statements is executed for a particular x. Less efficient because all three of the conditions are always tested. In the nested if statement, only the first condition is tested when x is not positive. Can lead to logical errors 36 / 1 Nested ifs vs. Sequence of ifs III 1 if( score >= 90) 2 grade = A ; 3 if( score >= 80) 4 grade = B ; 5 if( score >= 70) 6 grade = C ; What happens when score = 95? 37 / 1 if-else-if Statement Better solution: the if-else-if statement 1 if ( condition_1 ) 2 statement_1 3 else if ( condition_2 ) 4 statement_2 5. 6. 7 else if ( condition_n ) 8 statement_n 9 else 10 statement_e 38 / 1

Example Range Elimination We want to describe noise loudness measured in decibels with the effect of the noise. The following table shows the relationship between noise level and human perceptions of noises. Loudness in Decibels (db) Perception 50 or lower quiet 51-70 intrusive 71-90 annoying 91-110 very annoying above 110 uncomfortable Table: 39 / 1 Example in C code 1 if ( loudness <= 50 ) 2 printf (" quiet "); 3 else if ( loudness <= 70 ) 4 printf (" intrusive "); 5 else if ( loudness <= 90 ) 6 printf (" annoying "); 7 else if ( loudness <= 110 ) 8 printf (" very annoying "); 9 else 10 printf (" uncomfortable "); 40 / 1 Multiple-Alternative if, Order of Conditions With if-else-if statements, one and only one statement is ever executed Moreover the first satisfied condition is the one that is executed The order of the conditions can affect the outcome The order of conditions also affect program efficiency The most common cases (if known) should be checked first If loud noises are much more likely, it is more efficient to test first for noise levels above 110 db, then for levels between 91 and 110 db, and so on. 41 / 1

Code Exercise Exercise The Department of Defense would like a program that identifies single males between the ages of 18 and 26, inclusive. Design a logical expression that captures this. 42 / 1 Answer 1 /* Print a message if all criteria are met.*/ 2 if ( marital_status == S ) 3 if ( gender == M ) 4 if ( age >= 18 && age <= 26 ) 5 printf (" All criteria are met.\ n"); Can this be improved? 43 / 1 Better Solution 1 if ( maritial_status == S && 2 gender == M && 3 age >= 18 && 4 age <= 26 ) 5 printf (" All criteria are met.\ n"); Avoids overhead of executing the then part of each if statement in previous solution 44 / 1

Switch The switch statement is similar to a multiple-alternative if statement, but can be used only for type char or type int expressions. Useful when the selection depends on the value of a single variable (called the controlling variable) Expressions in the switch statement must cover all possible values of the controlling variable. Each viable expression case statement All other values fall-through (default:) statement. 45 / 1 Switch Example 1 # include <stdio.h> 2 int main ( void ) 3 { 4 char class ; 5 scanf ("%c", & class ); 6 switch ( class ) 7 { 8 case B : 9 case b : 10 printf (" Battleship \n"); 11 break ; 12 case C : 13 case c : 14 printf (" Cruiser \n"); 15 break ; 16 default : 17 printf (" Unknown ship class %c\n", class ); 18 } 19 return 0; 20 } 46 / 1 Common Errors You cannot use a string such as "Cruiser" or "Frigate" as a case label. The omission of the break statement at the end of an alternative causes the execution to fall through into the next alternative. Forgetting the closing brace of the switch statement body. 47 / 1

Nested if versus switch A nested if is more general then a switch statement if: Can check any number of any data type variables vs. one value for int or char data type. if: Can use a range of values, such as < 100 switch: More readable switch: Can not compare strings or double types switch: Can not handle a range of values in one case label Use the switch whenever there are ten or fewer case labels Use the default label whenever possible 48 / 1 Common Programming Errors I (0 <= x <= 4) is always true Associativity: first 0 <= x is evaluated (true or false) Thus, it evaluates to either 1 or and 0 In either case, both are less than 4 Thus the entire expression is true regardless of the value of x if(x = 10) is always true: the assignment operator is evaluated and x is given a value of 10, which is true 49 / 1 Common Programming Errors II Don t forget to parenthesize the condition. Don t forget the opening and closing brackets, { } if they are needed. When doing nested if statement, try to select conditions so that you can use the range-elimination multiple-alternative format. C matches each else with the closest unmatched if, so be careful so that you get the correct pairings of if and else statements. Can insert curly braces to get the desired behavior 50 / 1

Common Programming Errors III In switch statements, make sure the controlling expression and case labels are of the same permitted type. Remember to include the default case for switch statements. Don t forget the opening and closing brackets, { } for the switch statement. Don t forget the break statement. 51 / 1 Conditionals: Review I 1 if (x == 0) 2 statement_t ; 3 4 if (x == 0) 5 statement_t ; 6 else 7 statement_f ; 8 9 if (x == 0) { 10 statements_t ; 11 } 12 13 52 / 1 Conditionals: Review II 14 15 if (x == 0) { 16 statements_t 17 } 18 else { 19 statements_f 20 } 21 22 53 / 1

Conditionals: Review III 23 24 if (x >= 0) 25 if (x == 0) 26 statement_tt 27 else 28 statement_tf 29 else 30 statement_f 31 32 54 / 1 Conditionals: Review IV 33 34 switch (x) { case 1: 35 true if x == 1 statement 36 break ; 37 case 2: 38 true if x == 2 statement 39 break ; 40 default : 41 always true 42 } 55 / 1 Questions? 56 / 1