Lecture no 3 Control statements.

Slides:



Advertisements
Similar presentations
Selection in Python If statements.
Advertisements

CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Logic & program control part 2: Simple selection structures.
Dale/Weems/Headington
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
Flow of Control is Sequential unless a “control structure” is used to change that there are 2 general types of control structures: Selection (also called.
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
1 Chapter 3 Topics Constants of Type int and float l Evaluating Arithmetic Expressions l Implicit Type Coercion and Explicit Type Conversion l Calling.
1 CS150 Introduction to Computer Science 1 Relational Operators and the If Statement 9/22/08.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
Admin Office hours 2:45-3:15 today due to department meeting if you change addresses during the semester, please unsubscribe the old one from the.
Data Types, Expressions and Functions (part I)
Basic Elements of C++ Chapter 2.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Conditions, Logical Expressions, and Selection Control Structures Sumber dari :
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
1 Numeric Types, Expressions, and Output. 2 Chapter 3 Topics  Constants of Type int and float  Evaluating Arithmetic Expressions  Declaration for Numeric.
Numeric Types, Expressions, and Output 1. Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
1 Chapter 3 Numeric Types, Expressions, and Output CS185/09 - Introduction to Programming Caldwell College.
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
OPERATORS.
C++ Programming: Basic Elements of C++.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPS120: Introduction to Computer Science Operations Lecture 9.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
1 Chapter 3 Numeric Types, Expressions, and Output.
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Conditions, Logical Expressions, and Selection Control Structures.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Programming in C++
2/4/2016Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs.
C++ Data Types Check sample values of? ‘4’
Chapter 3 Numeric Types, Expressions, and Output.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
CS221 C++ Basics. C++ Data Types structured array struct union class address pointer reference simple integral char short int long bool floating float.
1 A Simple “Hello World” Example #include // input-output library using namespace std; int main() // function main { cout
1 Lecture Three I/O Formatting and Arithmetic Dr. Sherif Mohamed Tawfik.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3 Numeric Types, Expressions, and Output
Operators and Expressions
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Lecture 3 Expressions Richard Gesick.
Chapter 7 Additional Control Structures
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Presentation transcript:

Lecture no 3 Control statements

Selection in C++ If statements

Selection If or if / else statement choosing between mutually exclusive possibilities Two forms if (logical expression) statement; else statement;

Logical Expressions relational operators binary operators ==, !=, <=, >=, >, < binary operators work on any type of data, be careful about matching types watch out for = and == produce a bool result

Syntax of if statement if (logical expression) statement; don't put semicolon after condition indentation helps humans, doesn't matter to compiler can't start statement with "else"

Syntax of if statement if (x > 0) y = sqrt(x); if (x > y) t = x; x = y; y = t; // what goes with the if?

If-Then Statement TRUE expression FALSE statement Determine whether or not to execute a statement (which can be a single statement or an entire block) TRUE expression FALSE statement

Examples output larger of two numbers don't allow sqrt of negative number don't allow overflow determining even or odd give student another chance at a question

Visual Aid Decision tree

Example What is output? Why? int age; age = 20; if (age = 16) { cout << “Did you get driver’s license?”; }

Example What is output? Why? int age; age = 30; if (age < 18) cout << “Do you drive?”; cout << “Too young to vote”;

Example What is output? Why? int number; number = 0; if (number = 0) cout << “Zero value”; else cout << “Non-zero value”;

Logical Operators And && Or || Not ! binary operators used to combine bool values produce a bool result truth tables operator precedence ! then && then ||

Logical Expression Meaning Description ! p NOT p ! p is false if p is true ! p is true if p is false p && q p AND q p && q is true if both p and q are true. It is false otherwise. p || q p OR q p || q is true if either p or q or both are true. It is false otherwise.

Converting English to logic "0 is less than x is less than 5" "x is 5 or 6" "x is bigger than 5 and less than 10" impossible situations "dead code" always true always false

Write an expression for each taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22

Some Answers (taxRate > .25) && (income < 20000) (temperature <= 75) || (humidity < .70) (age > 21) && (age < 60) (age == 21) || (age == 22)

What went wrong? This is only supposed to display “HEALTHY AIR” if the air quality index is between 50 and 80. But when you tested it, it displayed “HEALTHY AIR” when the index was 35. int AQIndex; AQIndex = 35; if (50 < AQIndex < 80) cout << “HEALTHY AIR“;

Analysis of Situation AQIndex = 35; According to the precedence chart, the expression (50 < AQIndex < 80) means (50 < AQIndex) < 80 because < is Left Associative (50 < AQIndex) is false (has value 0) (0 < 80) is true.

Corrected Version int AQIndex; AQIndex = 35; if ((50 < AQIndex) && (AQIndex < 80)) cout << “HEALTHY AIR“;

Nested if's the statement to be executed in an if statement can be another if

Example 100.0 average = 100.0; if (average >= 60.0) float average; average = 100.0; if (average >= 60.0) if (average < 70.0) cout << “Marginal PASS”; else cout << “FAIL”; FAIL is printed; WHY? The compiler ignores indentation and pairs the else with the second if 100.0 average

Example Quadrant determination

if .. else provides two-way selection between executing one of 2 clauses (the if clause or the else clause) TRUE FALSE expression if clause else clause

What happens if you omit braces? if ((carDoors == 4) && (driverAge > 24)) premium = 650.00; cout << “ LOW RISK “; else premium = 1200.00; cout << “ HIGH RISK ”; monthlyPayment = premium / 12.0 + 5.00; Compile error occurs: The “if clause” is the single statement following the if

Another form of nested if's if (condition) statement; else if (condition) else

Comparing Strings Two objects of type string (or a string object and a C string) can be compared using the relational operators A character-by-character comparison is made using the ASCII character set values If all the characters are equal, then the 2 strings are equal. Otherwise, the string with the character with smaller ASCII value is the “lesser” string

myState > yourState true string myState; string yourState; myState = “Texas”; yourState = “Maryland”; Expression Value myState == yourState false myState > yourState true myState == “Texas” true

Test Plan if (x + y > 0) cout << "safe"; else if (x > 3) cout << "high"; else cout << "low";

Test Plan Case Input Output (expected) Output (actual) x + y > 0 "safe" x + y <=0, x > 3 x = 5, y=-7 "high" x+y <=0, x <= 3 x = 2, y=-3 "low"

Operator Meaning Associativity ! NOT Right *, / , % Multiplication, Division, Modulus Left + , - Addition, Subtraction Left < Less than Left <= Less than or equal to Left > Greater than Left >= Greater than or equal to Left == Is equal to Left != Is not equal to Left && AND Left || OR Left = Assignment Right 31

Comparing Real Values Do not compare floating point values for equality, compare them for near-equality. float myNumber; float yourNumber; cin >> myNumber; cin >> yourNumber; if (fabs (myNumber - yourNumber) < 0.00001) cout << “They are close enough!” << endl;

Lecture 3-b

Data Types, Expressions and Functions (part I)

Topics constants of type int and float evaluating arithmetic expressions implicit type coercion and explicit type conversion calling a value-returning function using function arguments using C++ library functions in expressions

Standard Data Types in C++ Integral Types represent whole numbers and their negatives declared as int, short, or long Floating Types represent real numbers with a decimal point declared as float or double Character Type represents single characters declared as char

Samples of C++ Data Values int sample values 4578 -4578 0 float sample values 95.274 95. .265 9521E-3 -95E-1 95.213E2 char sample values ‘B’ ‘d’ ‘4’ ‘?’ ‘*’

Scientific Notation 2.7E-4 means 2.7 x 10 - 4 = 2.7000 = 27000.0 2.7000 = 27000.0 2.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.00027

More About Floating Point Values Floating point numbers have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing Examples 18.4 500. .8 -127.358 Alternatively, floating point values can have an exponent, as in scientific notation--the number preceding the letter E doesn’t need to include a decimal point (E can be upper or lower case) Examples 1.84E1 5E2 8E-1 -.127358E3

Division Operator The result of the division operator depends on the type of its operands If one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type (truncates!!) Examples 11 / 4 has value 2 11.0 / 4.0 has value 2.75 11 / 4.0 has value 2.75 11.0 / 4 has value 2.75

Find the Middle //*************************************************** // FreezeBoil program // This program computes the midpoint between // the freezing and boiling points of water #include < iostream > using namespace std; const float FREEZE_PT = 32.0; // Freezing point of water const float BOIL_PT = 212.0; // Boiling point of water int main() { float avgTemp; // Holds the result of averaging // FREEZE_PT and BOIL_PT

Find the Middle (continued) cout << “Water freezes at “ << FREEZE_PT << endl; cout << “ and boils at “ << BOIL_PT << “ degrees.” << endl; avgTemp = FREEZE_PT + BOIL_PT; avgTemp = avgTemp / 2.0; cout << “Halfway between is “; cout << avgTemp << “ degrees.” << endl; return 0; }

Modulus Operator The modulus operator % can only be used with integer type operands and always has an integer type result Its result is the integer type remainder of an integer division Example 11 % 4 has value 3 because R = ? ) 4 11

More C++ Operators RAM int age; age = 8; age = age + 1; age 8 9

Prefix Form Increment Operator int age; age = 8; ++age; 8 age 9 age

Postfix Form Increment Operator int age; age = 8; age++; 8 age 9 age

Decrement Operator int dogs; dogs = 100; dogs--; 100 dogs 99 dogs

Which Form to Use When the increment(or decrement) operator is used in a “stand alone” statement solely to add one(or subtract one) from a variable’s value, it can be used in either prefix or postfix form USE EITHER dogs--; --dogs;

BUT... You can use increment or decrement operators INSIDE other statements example: y = ++x; example: if ( x ++ > 0) cout << x; You can write very confusing statements! example: x = x ++ + ++ x; // compiles! This is NOT a good idea!!!! Use ++ and -- in stand alone statements only!

What is an Expression in C++? An expression is a valid arrangement of variables, constants, and operators In C++ each expression is evaluated to a value of a given type The value of the expression 9.3 * 4.5 is 41.85 The type of the expression 9.3 * 4.5 is float

Operators can be binary involving 2 operands 2 + 3 unary involving 1 operand - 3 ternary involving 3 operands don't!

Some of the C++ Operators Precedence Operator Description Higher ( ) Function call + Positive (unary) - Negative (unary) * Multiplication / Division % Modulus(remainder) + Addition (binary) - Subtraction (binary Lower = Assignment

Precedence Precedence determines which operator is applied first in an expression having several operators higher precedence operators are done first

Associativity Left to right associativity means that in an expression having 2 operators with the same priority, the left operator is applied first In C++ the binary operators *, /, %, +, - are all left associative Expression 9 - 5 - 1 means (9 - 5) - 1 4 - 1 3

Evaluate the Expression 7 * 10 - 5 % 3 * 4 + 9 (7 * 10) - 5 % 3 * 4 + 9 70 - 5 % 3 * 4 + 9 70 -(5 % 3) * 4 + 9 70 - 2 * 4 + 9 70 - ( 2 * 4) + 9 70 - 8 + 9 (70 - 8 ) + 9 62 + 9 71

Parentheses Parentheses can be used to change the usual order Parts in() are evaluated first Evaluate (7 *(10 - 5) % 3) * 4 + 9 (7 * 5 % 3 ) * 4 + 9 ( 35 % 3) * 4 + 9 2 * 4 + 9 8 + 9 17

Assignment Operator semantics Variable = Expression First the expression on right is evaluated Then the resulting value is stored in the memory location of variable on left NOTE: An automatic implicit type coercion occurs after evaluation but before the value is stored if the types differ for expression and variable

What value is stored? float a; float b; a = 8.5; b = 9.37; a = b; 8.5

What is stored? float someFloat; ? someFloat = 12; // Causes implicit type conversion ? 12.0 someFloat

What is stored? int someInt; ? someInt = 4.8; // Causes implicit type conversion ? 4 someInt

Type Casting is Explicit Conversion of one Type to another int(4.8) has value 4 float(5) has value 5.0 float(7/4) has value 1.0 float(7) / float(4) has value 1.75

Some Expressions age = 8 8 - age - 8 5 + 8 13 5 / 8 0 6.0 / 5.0 1.2 int age; Example Value age = 8 8 - age - 8 5 + 8 13 5 / 8 0 6.0 / 5.0 1.2 float(4 / 8) 0.0 float(4) / 8 0.5

What values are stored? float loCost; float hiCost; loCost = 12.342; float(int(loCost * 100.0 + 0.5)) / 100.0; hiCost = float(int(hiCost * 100.0 + 0.5)) / 100.0;

Values were rounded to 2 decimal places loCost 12.34 12.35 hiCost

Functions Recall every C++ program must have a function called main Program execution always begins with function main Any other functions are subprograms and must be called

Function Calls One function calls another by using the name of the called function together with() containing an argument list x = sqrt (25.0); A function call temporarily transfers control from the calling function to the called function (that's why it's a control structure)

Value-Returning Functions HEADER FILE FUNCTION EXAMPLE VALUE OF CALL <cstdlib> abs(i) abs(-6) 6 <cmath> pow(x,y) pow(2.0,3.0) 8.0 fabs(x) fabs(-6.4) 6.4 <cmath> sqrt(x) sqrt(100.0) 10.0 sqrt(x) sqrt(2.0) 1.41421 <cmath> log(x) log(2.0) .693147 <cctype> isupper(c) isupper('A') true

Write C++ Expressions for The square root of b2 - 4ac sqrt(b * b - 4.0 * a * c) The square root of the average of myAge and yourAge sqrt((myAge + yourAge) / 2)

Function Call A function call temporarily transfers control to the called function’s code When the function’s code has finished executing, control is transferred back to the calling block

Function Call Syntax FunctionName ( Argument List ) The argument list is a way for functions to communicate with each other by passing information The argument list can contain zero, one, or more arguments, separated by commas, depending on the function