Writing a program with conditionals

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
16/27/ :53 PM6/27/ :53 PM6/27/ :53 PMLogic Control Structures Arithmetic Expressions Used to do arithmetic. Operations consist of +,
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
J-1 University of Washington Computer Programming I Switch Statement © 2000 UW CSE.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Other Conditional Methods. Conditional Operator Conditional Operator (?:) Conditional operator ( ?: ) – Ternary operator: 3 arguments expression1 ? expression2.
Flow of Control Part 1: Selection
Introduction to Computing Lecture 05: Selection (continued) Introduction to Computing Lecture 05: Selection (continued) Assist.Prof.Dr. Nükhet ÖZBEK Ege.
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.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
G-1 10/4/99 CSE / ENGR 142 Programming I Conditionals © 1999 UW CSE.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
Boolean Expressions and if-else Statements Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
1 CS1001 Lecture Overview Java Programming Java Programming Arrays Arrays.
142 H -1 Conditionals Essential feature for a computer language Conditional Statement: allows the computer to choose between several paths depending on.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
Control statements Mostafa Abdallah
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
Making Decisions in c. 1.if statement Imagine that you could translate a statement such as “If it is not raining, then I will go swimming” into the C.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
Lecture 3 Selection Statements
The Ohio State University
CSE1301 Sem Selection Lecture 25 Lecture 9: Selection.
Week 3 Part 2 Kyle Dewey.
CprE 185: Intro to Problem Solving (using C)
Control Structures and Data Files
Week 3 - Friday CS222.
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.
EGR 2261 Unit 4 Control Structures I: Selection
Boolean Expressions and if-else Statements
Conditionals & Boolean Expressions
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Relational & Logical Operators
Introduction to Programming
Other Conditional Methods
C Programming Variables.
Relational and Logical Operators
Lecture3.
The Java switch Statement
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
EECE.2160 ECE Application Programming
Introduction to Computing Lecture 04: Booleans & Selection
Relational and Logical Operators
Relational and Logical Operators
EECE.2160 ECE Application Programming
Relational and Logical Operators
EECE.2160 ECE Application Programming
CSCE 206 Lab Structured Programming in C
Problem 1 Given n, calculate 2n
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Writing a program with conditionals Example: print the percentage tax based on income if income < 15000 0% if 15000  income < 30000 18% if 30000  income < 50000 22% if 50000  income < 100000 28% if 100000  income 31% Simple solution if (income<15000) printf(“No tax\n”); if (income>=15000 && income<30000) printf(“18%% tax\n”); if (income>=30000 && income<50000) printf(“22%% tax\n”); if (income>=50000 && income<100000) printf(“28%% tax\n”); if (income>=100000) printf(“31%% tax\n”); Mutually exclusive: only one is true 142 I -1

Using nested ifs if (income < 15000) else if (income < 30000) Cascaded ifs if (income < 15000) printf(“No tax\n”); else if (income < 30000) printf(“18%% tax\n”); else if (income < 50000) printf(“22%% tax\n”); else if (income < 100000) printf(“28%% tax\n”); else printf(“31%% tax\n”); which can be written order of the conditions is important. Conditions are successively inclusive. if (income < 15000) printf(“No tax\n”); else if (income < 30000) printf(“18%% tax\n”); else if (income < 50000) printf(“22%% tax\n”); else if (income < 100000) printf(“28%% tax\n”); else printf(“31%% tax\n”); 142 I -2

Other Examples 1) Read 3 characters Print the first one in alphabetical order e.g. p, g and m, print g Reminder: character: individual character keyboard (or an escape sequence ‘\n’) in C, char However, for the computer, characters are just integers: different character sets ASCII, EBCDIC... (see text appendix) …< & < … < 5 < … < A < B < … < a < … < z < … < } < … 38 53 65 66 97 122 125 The computer can compare characters (in a program, use <, >, <=, >=, !=, ==) 142 I -3

char first(char c1, char c2, char c3) { char first; first = c1; as a function: char first(char c1, char c2, char c3) { char first; first = c1; if (c2<first) first = c2; if (c3<first) first = c3; return first; } 2) Input 2 characters Rearrange them in sorted order Output them in sorted order e.g. input ra, output ar char c1, c2, temp; printf(“Enter 2 characters: ”); scanf(“%c%c”,&c1,&c2); if (c2<c1) { temp = c1; c1 = c2; c2 = temp; } printf("In alphabetical order: %c %c",c1,c2); why not c1 = c2; c2 = c1; ? 142 I -4

De Morgan’s law !(P && Q) is equivalent to !P || !Q e.g. if ( !(age > 50 && smoker == ‘Y’) ) printf(“Cheaper health insurance”); is equivalent to if ( age <= 50 || smoker != ‘Y’ ) printf(“Cheaper health insurance”); Check with a logical table P, Q are conditions T and F stand for True and False T F F T F T F T F T 142 I -5

Operator Precedence Check inside cover of the text == ! - + != -(unary) - + == != * / % < > <= >= && || lower precedence (evaluate last) higher (evaluate first) Consider a = 2; b = 4; z = (a+3 >=5 && !(b<5)) || a*b+b != 7; What is the value of z (1 or 0)? (Recall that True is 1 and False is 0) z is 1 142 I -6

Pitfalls of if (1) What is wrong in each of these code snippets? printf is not part of the if statement if (x>10); printf(“x>10”); obscure: better x!=0 if (x) printf(“x is non zero”); if (x=10) printf(“x is 10”); = is not a relational operator! Use == Whatever the value of x before, after executing this statement x is 10 142 I -7

Pitfalls of if (2) if (0 <= x <= 10) printf(“x is between 0 and 10”); What happens if x = 11? x is between 0 and 10 is printed! (0<=x is true thus 1 and 1<=10) Write: if (0<=x && x<=10) printf(“x is between 0 and 10”); Also: In C, & and | are operators for binary numbers NOT the same as && and || 142 I -8

Avoid: Using == and != with doubles: Because of round off errors, 2 equivalent mathematical computations can lead to different results double x; x=(sqrt(2)+sqrt(2))*(sqrt(2)+sqrt(2)); if (x == 8.0) printf(“x is 8.0”); printf is not executed with some compilers long winded ifs (difficult to understand): /* how many days in a month */ if (month == 1) days = 31; else if (month == 2) days = 28; ... 12 of these (without including the leap year case!) Can do better! 142 I -9

Better Best: using switch if (month == 4 || month == 6 || days = 30; /* April, June, Sept, Nov */ else if (month == 2) days = 28; /* February */ else days = 31; /* all the rest */ Best: using switch switch(month) { case 2: days = 28; break; case 4: case 6: case 9: case 11: days = 30; default: days = 31; } printf(“There are %i days in that month”,days); if month is 6, execution within switch starts here and ends here 142 I -10

Syntax of switch switch(control expression) { case constant1: ... statement1; statement2; break; case constant3: case constant4: statement3; statement4; default: statement5; } an int or a char must be a constant e.g. 1, 2 , -3 ‘A’, ‘c’, ‘@’... do not forget fall through (everything between the case line and the next break is executed) optional but might prevent a fall through when adding cases after the default (e.g. in a subsequent update) 142 I -11

another switch example char order; printf("Please, type b or l to order\n"); printf("Breakfast (b) or lunch (l): "); scanf("%c",&order); switch(order) { case ‘b’: case ‘B’: printf(“Breakfast\n”); break; case ‘l’: case ‘L’: printf(“Lunch\n”); default: printf(“Sorry, I don’t understand”); } 142 I -12