CSE 251 Dr. Charles B. Owen Programming in C1 Flow Control and Booleans 1. Please get logged in. 2. Open a new terminal window Applications/Accessories/Terminal.

Slides:



Advertisements
Similar presentations
Chapter 2 Flow of Control. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 2-2 Learning Objectives Boolean Expressions Building, Evaluating.
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.
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.
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Lecture 4 Introduction to Programming in C Prof. Dr. Arne Kutzner Hanyang University / Seoul Korea.
Conditional Statement
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Computer programming Lecture 4. Lecture 4: Outline Making Decisions [chap 6 – Kochan] –The if Statement –The if-else Construct –Logical Operators –Boolean.
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.
1 if and if-else statements. 2 Relational Operators x < y < is an operator x and y are its operands ( x < y ) is called a logical expression. Logical.
CPS120: Introduction to Computer Science Decision Making in Programs.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
1 Conditional statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Chapter 6: Control Structures Computer Programming Skills Second Term Department of Computer Science Foundation Year Program Umm Alqura.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Chapter 5 Logic; Got Any?. Flow of Control The order in which the computer executes statements in a program Control Structure A statement used to alter.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Introduction to Computing Lecture 05: Selection (continued) Introduction to Computing Lecture 05: Selection (continued) Assist.Prof.Dr. Nükhet ÖZBEK Ege.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
Week 8: Decisions Bryan Burlingame 21 October 2015.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
Introduction to C Programming CE Lecture 3 Control Structures in C.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
IT CS 200: C ONDITION Lect. Napat Amphaiphan. T HE ABILITY TO CONTROL THE FLOW OF YOUR PROGRAM, LETTING IT MAKE DECISIONS ON WHAT CODE TO EXECUTE 2.
Control statements Mostafa Abdallah
CSCI 171 Presentation 3. Operators Instructs C to perform some operation Assignment = Mathematical Relational Logical.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
Introduction to Programming Using C Basic Logic. 2 Contents Conditional programming If statement Relational operators Compound statements Loops While.
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Loops and Repetition condition statement true false int count = 1 count
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
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.
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Making Decisions.
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: Making Decisions.
Introduction to Programming
Decision Making.
Selection Control Structure
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

CSE 251 Dr. Charles B. Owen Programming in C1 Flow Control and Booleans 1. Please get logged in. 2. Open a new terminal window Applications/Accessories/Terminal 3. Open a web browser Applications/Internet/Iceweasel Web Browser 4. Go to 5. Open Step 3: Flow Control and Booleans

CSE 251 Dr. Charles B. Owen Programming in C2 Today: Flow Control and Booleans Flow Control if, switch Boolean Logic =, >, !=

CSE 251 Dr. Charles B. Owen Programming in C3 rlc.c #include /* * Simple program to compute the resonant frequency of * an RLC circuit */ int main() { double l; /* Inductance in millihenrys */ double c; /* Capacitance in microfarads */ double omega; /* Resonance frequency in radians per second */ double f; /* Resonance frequency in Hertz */ printf("Enter the inductance in millihenrys: "); scanf("%lf", &l); printf("Enter the capacitance in microfarads: "); scanf("%lf", &c); omega = 1.0 / sqrt((l / 1000) * (c / )); f = omega / (2 * M_PI); printf("Resonant frequency: %.2f\n", f); }

CSE 251 Dr. Charles B. Owen Programming in C4 rlc.c #include /* * Simple program to compute the resonant frequency of * an RLC circuit */ int main() { double l; /* Inductance in millihenrys */ double c; /* Capacitance in microfarads */ double omega; /* Resonance frequency in radians per second */ double f; /* Resonance frequency in Hertz */ printf("Enter the inductance in millihenrys: "); scanf("%lf", &l); printf("Enter the capacitance in microfarads: "); scanf("%lf", &c); omega = 1.0 / sqrt((l / 1000) * (c / )); f = omega / (2 * M_PI); /* Convert radians per sec to Hertz */ printf("Resonant frequency: %.2f\n", f); } Note the use of comments to tell: a) what the program does, b) what some lines of code do, and c) what the variables are.

CSE 251 Dr. Charles B. Owen Programming in C5 rlc.c #include /* * Simple program to compute the resonant frequency of * an RLC circuit */ int main() { double l; /* Inductance in millihenrys */ double c; /* Capacitance in microfarads */ double omega; /* Resonance frequency in radians per second */ double f; /* Resonance frequency in Hertz */ printf("Enter the inductance in millihenrys: "); scanf("%lf", &l); printf("Enter the capacitance in microfarads: "); scanf("%lf", &c); omega = 1.0 / sqrt((l / 1000) * (c / )); f = omega / (2 * M_PI); printf("Resonant frequency: %.2f\n", f); } Note the use of indentation

CSE 251 Dr. Charles B. Owen Programming in C6 rlc.c #include /* * Simple program to compute the resonant frequency of * an RLC circuit */ int main() { double l; /* Inductance in millihenrys */ double c; /* Capacitance in microfarads */ double omega; /* Resonance frequency in radians per second */ double f; /* Resonance frequency in Hertz */ printf("Enter the inductance in millihenrys: "); scanf("%lf", &l); printf("Enter the capacitance in microfarads: "); scanf("%lf", &c); omega = 1.0 / sqrt((l / 1000) * (c / )); f = omega / (2 * M_PI); printf("Resonant frequency: %.2f\n", f); } Indentation is necessary to make your program readable!

CSE 251 Dr. Charles B. Owen Programming in C7 Sequential Execution Statement 1 Statement 2 Statement n...

CSE 251 Dr. Charles B. Owen Programming in C8 Selective Execution boolean expression statement 1statement 2 true false

CSE 251 Dr. Charles B. Owen Programming in C9 if statements The if statement Fundamental means of flow control How we will make decisions Boolean expressions The actual determination of the decision if(age > 39) printf(“You are so old!\n”); age > 39 c == 0 l <= 0 (age >= 18) && (age < 65)

CSE 251 Dr. Charles B. Owen Programming in C10 Structure of an if statement if(expression1) statement1; else if(expression2)/* Optional */ statement2; else/* Optional */ statement3; If expression1 is true, execute statement1. Otherwise, test to see if expression2 is true. If so, execute statement2. Otherwise, execute statement3. The expressions are boolean expressions that resolve to a true or a false.

CSE 251 Dr. Charles B. Owen Programming in C11 Basic Boolean Expressions true false age < 18 divisor == 0 size > ch == ‘X’ Some operators: < Less than <= Less than or equal to == Equal !=Not equal >= Greater than or equal to > Greater than Some operators: < Less than <= Less than or equal to == Equal !=Not equal >= Greater than or equal to > Greater than Important: The test for equality is ==, not =. This is the most common error in a C program.

CSE 251 Dr. Charles B. Owen Programming in C12 Example if statements if(age < 18) printf(“Too young to vote!\n”); if(area == 0) printf(“The plot is empty\n”); else printf(“The plot has an area of %.1f\n”, area); if(val < 0) printf(“Negative input is not allowed\n”); else if(val == 0) printf(“A value of zero is not allowed\n”); else printf(“The reciprocal is %.2f\n”, 1.0 / val); < Less than <= Less than or equal to == Equal !=Not equal >= Greater than or equal to > Greater than < Less than <= Less than or equal to == Equal !=Not equal >= Greater than or equal to > Greater than 1 Note the indentation

CSE 251 Dr. Charles B. Owen Programming in C13 Blocks printf(“This is a statement\n”); { printf(“All items in a curly brace\n”); printf(“as if there are one statement”); printf(“They are executed sequentially”); } Single Statement Block

CSE 251 Dr. Charles B. Owen Programming in C14 Where is this useful? if(value > 0) { result = 1.0 / value; printf("Result = %f\n", result); } If the expression is true, all of the statements in the block are executed

CSE 251 Dr. Charles B. Owen Programming in C15 Where is this useful? if(value > 0) { result = 1.0 / value; printf("Result = %f\n", result); } Will these two sections of code work differently? if(value > 0) result = 1.0 / value; printf("Result = %f\n", result);

CSE 251 Dr. Charles B. Owen Programming in C16 Where is this useful? if(value > 0) { result = 1.0 / value; printf("Result = %f\n", result); } Yes! if(value > 0) result = 1.0 / value; printf("Result = %f\n", result); Will always execute! 2

CSE 251 Dr. Charles B. Owen Programming in C17 Nested Blocks if(bobsAge != suesAge) /* != means "not equal" */ { printf("Bob and Sue are different ages\n"); if(bobsAge > suesAge) { printf("In fact, Bob is older than Sue\n"); if((bobsAge - 20) > suesAge) { printf("Wow, Bob is more than 20 years older\n"); } What does this do?

CSE 251 Dr. Charles B. Owen Programming in C18 Importance of indentation if(bobsAge != suesAge) /* != means "not equal" */ { printf("Bob and Sue are different ages\n"); if(bobsAge > suesAge) { printf("In fact, Bob is older than Sue\n"); if((bobsAge - 20) > suesAge) { printf("Wow, Bob is more than 20 years older\n"); } See how much harder this is to read?

CSE 251 Dr. Charles B. Owen Programming in C19 Boolean Expressions An expression whose value is true or false In C: – integer value of 0 is “false” – nonzero integer value is “true” Example of Boolean expressions: – age < 40 – graduation_year == 2010 Relational operator

CSE 251 Dr. Charles B. Owen Programming in C20 #include int main() { const bool trueVar = true, falseVar = false; const int int3 = 3, int8 = 8; printf("No 'boolean' output type\n"); printf("bool trueVar: %d\n",trueVar); printf("bool falseVar: %d\n\n",falseVar); printf("int int3: %d\n",int3); printf("int int8: %d\n",int8); } Library that defines: bool, true, false What does the output look like?

CSE 251 Dr. Charles B. Owen Programming in C21 #include int main() { const bool trueVar = true, falseVar = false; const int int3 = 3, int8 = 8; printf("No 'boolean' output type\n"); printf("bool trueVar: %d\n",trueVar); printf("bool falseVar: %d\n\n",falseVar); printf("int int3: %d\n",int3); printf("int int8: %d\n",int8); } Library that defines: bool, true, false What does the output look like?

CSE 251 Dr. Charles B. Owen Programming in C22 // Example3 (continued…) printf("\nint3 comparators\n"); printf("int3 == int8: %d\n",(int3 == int8)); printf("int3 != int8: %d\n",(int3!=int8)); printf("int3 < 3: %d\n",(int3 < 3)); printf("int3 <= 3: %d\n",(int3 <= 3)); printf("int3 > 3: %d\n",(int3 > 3)); printf("int3 >= 3: %d\n",(int3 >= 3)); Comparing values of two integer constants What does the output look like?

CSE 251 Dr. Charles B. Owen Programming in C23 // Example3 (continued…) printf("\nint3 comparators\n"); printf("int3 == int8: %d\n",(int3 == int8)); printf("int3 != int8: %d\n",(int3!=int8)); printf("int3 < 3: %d\n",(int3 < 3)); printf("int3 <= 3: %d\n",(int3 <= 3)); printf("int3 > 3: %d\n",(int3 > 3)); printf("int3 >= 3: %d\n",(int3 >= 3));

CSE 251 Dr. Charles B. Owen Programming in C24 More Examples char myChar = ‘A’; – The value of myChar==‘Q’ is false (0) Be careful when using floating point equality comparisons, especially with zero, e.g. myFloat==0

CSE 251 Dr. Charles B. Owen Programming in C25 Suppose? What if I want to know if a value is in a range? Test for: 100 ≤ L ≤ 1000?

CSE 251 Dr. Charles B. Owen Programming in C26 You can’t do… if(100 <= L <= 1000) { printf(“Value is in range…\n”); } This code is WRONG and will fail.

CSE 251 Dr. Charles B. Owen Programming in C27 Why this fails… if((100 <= L) <= 1000) { printf(“Value is in range…\n”); } C Treats this code this way Suppose L is Then 100 <= L is true, so (100 <= L) evaluates to true, which, in C, is a 1. Then it tests 1 <= 1000, which also returns true, even though you expected a false.

CSE 251 Dr. Charles B. Owen Programming in C28 Compound Expressions Want to check whether -3 <= B <= -1 – Since B = -2, answer should be True (1) But in C, the expression is evaluated as – ((-3 <= B) <= -1) (<= is left associative) – (-3 <= B) is true (1) – (1 <= -1) is false (0) – Therefore, answer is 0!

CSE 251 Dr. Charles B. Owen Programming in C29 Compound Expressions Solution (not in C): (-3<=B) and (B<=-1) In C: (-3<=B) && (B<=-1) Logical Operators – And: && – Or: || – Not: !

CSE 251 Dr. Charles B. Owen Programming in C30 Compound Expressions #include int main() { const int A=2, B = -2; printf("Value of A is %d\n", A); printf("0 <= A <= 5?: Answer=%d\n", (0<=A) && (A<=5)); printf("Value of B is %d\n", B); printf("-3 <= B <= -1?: Answer=%d\n", (-3<=B) && (B<=-1)); }

CSE 251 Dr. Charles B. Owen Programming in C31 Compound Expressions #include int main() { const int A=2, B = -2; printf("Value of A is %d\n", A); printf("0 <= A <= 5?: Answer=%d\n", (0<=A) && (A<=5)); printf("Value of B is %d\n", B); printf("-3 <= B <= -1?: Answer=%d\n", (-3<=B) && (B<=-1)); } Correct Answer!!! True (1)

CSE 251 Dr. Charles B. Owen Programming in C32 Compound Expressions #include int main() { const int A=2, B = -2; printf("Value of A is %d\n", A); printf("0 <= A <= 5?: Answer=%d\n", (0<=A) && (A<=5)); printf("Value of B is %d\n", B); printf("-3 <= B <= -1?: Answer=%d\n", (-3<=B) && (B<=-1)); } Correct Answer!!! True (1) &&

CSE 251 Dr. Charles B. Owen Programming in C33 Truth Tables NotAndOr

CSE 251 Dr. Charles B. Owen Programming in C34 Truth Tables NotAndOr

CSE 251 Dr. Charles B. Owen Programming in C35 Truth Tables NotAndOr

CSE 251 Dr. Charles B. Owen Programming in C36 Truth Tables NotAndOr

CSE 251 Dr. Charles B. Owen Programming in C37 Truth Tables NotAndOr 3 Our comparison operators: = >

CSE 251 Dr. Charles B. Owen Programming in C38 Precedence & Associativity Relational operators have precedence and associativity (just like arithmetic operators) Use ( ) when in doubt Can you guess what’s the answer?

CSE 251 Dr. Charles B. Owen Programming in C39 ( ((A + B) > 5) && ( ((A=0) ((A + B) – 2)) ) ( (6 > 5) && ( ((A=0) ((A + B) – 2)) ) ( 1 && ( ( 0 ((A + B) – 2)) ) ( 1 && ( 1 > ( 2 – 2) ) ) ( 1 && ( 1 > 0 ) ) ( 1 && 1 ) Answer: 1 Precedence: +/- > < &&

CSE 251 Dr. Charles B. Owen Programming in C40 Associativity “=“ is right associative Example: X=Y=5 right associative: X = (Y=5) expression Y=5 returns value 5: X = 5

CSE 251 Dr. Charles B. Owen Programming in C41 You should refer to the C operator precedence and associative table See for example, prec.htm prec.htm Or just use parentheses whenever you’re unsure about precedence and associativity

CSE 251 Dr. Charles B. Owen Programming in C42 Switch Statement A less general substitute for the multibranch if. It is used for selecting among discrete values (int), i.e. not continuous values. switch (int_expression) { case_list: statement_list; case_list: statement_list; default: statement_list; } Switch & Functions

CSE 251 Dr. Charles B. Owen Programming in C43 Behavior The int_expression is evaluated. If the value is in a case_list, execution begins at that statement_list and continues through subsequent statement_lists until: break, return, or end of switch. Switch & Functions

CSE 251 Dr. Charles B. Owen Programming in C44 #include void main() { int gender; printf("Enter your gender (male=1, female=2): "); scanf("%d",&gender); switch(gender) { case 1: printf("You are a male\n"); break; case 2: printf("you are a female\n"); break; default: printf("Not a valid input\n"); break; }

CSE 251 Dr. Charles B. Owen Programming in C45 switch(gender) { case 1: printf("You are a male\n"); break; case 2: printf("you are a female\n"); break; default: printf("Not a valid input\n"); break; } 4