91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.

Slides:



Advertisements
Similar presentations
Quadratic Equations.
Advertisements

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
If Statements & Relational Operators Programming.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Chapter 6 Horstmann Programs that make decisions: the IF command.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Flow control 1: if-statements (Liang 72-80) if(radius < 0) { System.out.println(“cannot get area: radius below zero”); } else { double area = radius *
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Solving Quadratic Equations Section 1.3
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Copyright © 2003 Pearson Education, Inc. Slide 2-1 Problem Solving with Java™ Second Edition Elliot Koffman and Ursula Wolz Copyright © 2003 Pearson Education,
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 While’s – The Basic Idea Set of operations is repeated as.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Selection Structures (if & switch statements) (CS1123)
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
CS31: Introduction to Computer Science I Discussion 1A 4/9/2010 Sungwon Yang
CONDITIONAL STATEMENTS OVERVIEW.  Many times we want programs to make decisions  What drink should we dispense from the vending machine?  Should we.
C++ Programming: Basic Elements of C++.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Program Outline // this slide illustrates the basic outline.
Fundamental Programming: Fundamental Programming Introduction to C++
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Review the following: if-else One branch if Conditional operators Logical operators Switch statement Conditional expression operator Nested ifs if –else.
1 Example: Solution of Quadratic Equations We want to solve for real values of x, for given values of a, b, and c. The value of x can be determined from.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Chapter 4 Selection: the if-else and switch-case instructions.
Input Validation 10/09/13. Input Validation with if Statements You, the C++ programmer, doing Quality Assurance (by hand!) C++ for Everyone by Cay Horstmann.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Introduction to Computer Sciences References: [1] Fortran 95/2003 for Scientists and Engineers (3e) by Stephen J. Chapman. [2] Using Fortran 90 by Chester.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Fundamental Programming Fundamental Programming Data Processing and Expressions.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Bill Tucker Austin Community College COSC 1315
The Ohio State University
Chapter 4 – C Program Control
Chapter 3 Control Statements
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
The Selection Structure
Operators and Expressions
Control Statement Examples
Introduction to C++ Programming
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Chapter 4 - Program Control
Summary Two basic concepts: variables and assignments Basic types:
Chapter 5: Control Structure
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Life is Full of Alternatives
Selection Control Structure
Presentation transcript:

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage do dishes if you have less than $100 visit the bank withdraw $100 – cash on hand endif drive to Loblaws if potatoes are less than 20 cents a pound buy 10 pounds of potatoes else buy 5 pounds of carrots buy some lettuce endif drive to the LCBO etc. Do only if the “condition” is true. Do one or the other of these actions.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 2 Basic If Flowchart if (true or false expression) { } Test Condition Execute Statements Is true Is false

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 3 If.. Else Flowchart if (true or false expression) { } else { } Test Condition Execute True Part Is false Is true Execute False Part

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 4 Bool “Bool” is a new type (like “int” and “double” except in that we’re dealing with a different kind of values). int: possible values = 0, 1, 2, -9, etc. double: possible values = , etc. bool: possible values = true, false “True” and “false” are bool constants, just as 0 is an int constant and 4.3 is a double constant. We can have bool variables, just as we can have int and double variables. Note: if you have an older compiler which doesn’t recognize “bool”, place the following after your include directives: typedef enum { false = 0, true = 1} bool;

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 5 C++ Basic If Details Basic If Statement: if (boolean expression) { any number of statements } “boolean expression” is an expression which evalauates to a bool value (e.g. either “true” or “false”). It will often involve “relational” operators (next slide) which compare two values and produce a true/false result. The above format is actually the combination the fundamental C++ if statement (which allows only one statement to be conditionally executed) and the C++ “block statement” (which bundles a number of statements together). If this makes sense (see the text for details), fine. Otherwise just pretend that the fundamental if statement is as shown above.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 6 Relational Operators <is less than >is greater than <=is less than or equal to >=is greater than or equal to == is equal to != is not equal to These operators compare two “arithmetic” (int or double) values and produce a bool result. PrecedenceOperatorsAssociativity Highestunary -Right castRight * / %Left binary - +Left Left Lowest == != Left

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 7 Sample If Program // include’s omitted void main (void) { int a, b, temp; cout << “Please enter two values: “; cin >> a >> b; if (a > b) { // the standard way of swapping values temp = a; a = b; b = temp; } cout << “The values in order are “ << a << “ and “ << b << endl; } // end main

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 8 Bool Conversions (1) C++ is (unfortunately) very generous in letting us use bool values in situations which require a arithmetic value (and vice versa). It is permissable, for example, to assign a bool value to an int variable, or to add two bools. Rule 1: If a bool value is used in a situation where an arithmetic value is required, the bool value is automatically converted to int. - false is converted to zero - true is converted to a non-zero value (normally 1) Rule 2: If an arithmetic value is used in a situation where a bool value is required, the arithmetic value is automatically converted to bool. - zero is converted to false - non-zero values are converted to true

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 9 Bool Conversions (2) These automatic conversions are of little if any practical value, and C++ would be a better language is they weren’t performed. They are essentially an unfortunate legacy of the history of C and C++, and result in two very nasty pitfalls for the unwary. int a = 4, b = 20; if (5 < a < 8) { // we will get here (surprise 1)... } if (b = 16) { // note missing second ‘=‘ // we will get here (surprise 2)... }

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 10 C++ If..else Details If..Else Statement: if (boolean expression) { any number of statements } else { any number of statements } “boolean expression” is an expression which evalauates to a bool value. The above format is actually the combination the fundamental C++ if..else statement (which allows only one statement in each of the true and false parts executed) and two block statements. If this makes sense (see the text for details), fine. Otherwise just pretend that the fundamental if statement is as shown above.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 11 Sample If..Else Program // include’s omitted void main (void) { int a, b, largest; cout << “Please enter two values: “; cin >> a >> b; if (a >= b) { largest = a; } else { largest = b; } cout << “The largest of the values is “ << lasrgest << endl; } // end main

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 12 Nested If’s The statements inside an if may include further if statements. This is known as “nested if’s”. void main (void) { int a, b; cout << “Please enter two values: “; cin >> a >> b; if (a < b) { cout << “The 1st value is smaller.” << endl; } else { if (a > b) { cout << “The 1st value is bigger.” << endl; } else { cout << “The values are equal.” << endl; } } // end main

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 13 Quadratic Example (1) A “quadratic” is an equation of the form: ax 2 + bx + c = 0 where “a”, “b”, and “c” are constants. Example: 2x 2 – 11x + 15 = 0 In general, quadratics have two solutions (known as the “roots”). In the example given, “x” may be either 2.5 or 3. 2(2.5) 2 – 11(2.5) + 15 = 13.5 – = 0 2(3) 2 – 11(3) + 15 = 18 – = 0 a is 2 b is –11 c is 15

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 14 Quadratic Example (2) The formula for the roots is as follows: If the discriminant is negative there are no real roots (because we can’t take the square root of a negative value). If the discriminant is zero there is only one root (because we get the same answer whether we add or subtract the square root). Otherwise there are two roots. See sample program quad.cpp. -b +/- b2 – 4ac 2a “discriminant”

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 15 C++ Multi-way If Multi-way If Statement: if (boolean expression) { any number of statements } else if (boolean expression) { any number of statements } else if (boolean expression) { any number of statements... } else { // the else part is optional any number of statements } The statements associated with the first true expression are executed. If no conditions are true, the statements in the else part (if there is one) are executed. Not a fundamental C++ statement (just a way of combining if..else and block statements).

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 16 Multi-way If Example if (discriminant < 0) { // no real solutions cout <<... } else if (discriminant == 0) { // one solution solution_1 =... cout <<... } else { // two solutions solution_1 =... solution_2 =... cout <<... } Neater and easier to follow than the nested if’s used in the first quadratic sample program, and reflects the fact that we’re dealing with a three- way choice. See sample program quad-m.cpp.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 17 Logical Operations AND – result is true if both operands are true. if it is sunny AND you have money visit the beach we are to visit the beach only if it is sunny and we also have some money. OR – result is true if either operand is true. if you have cash OR you have a credit card go shopping we are to go shopping if we have either some cash or a credit card. NOT – result is true if the operand is false. if NOT you have money drop by the bank we are to drop by the bank if we don’t have any money

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 18 Logical Operators &&AND ||OR !NOT These operators operate on bool values and produce bool results. PrecedenceOperatorsAssociativity Highestunary - ! (not)Right castsRight * / %Left binary - +Left Left == != Left && (and) Left Lowest || (or) Left

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 19 Logical Operators Example (1) Checking that the latitude and longitude entered by the user are valid... cin >> lat_1 >> lng_1; if ( (lat_1 > 90.0) || (lat_1 < -90.0) || (lng_1 > 180.0) || (lng_1 < ) ) { // input is invalid cout << “...”; return; // in main = “stop” } The boolean expression evaluates to true if the input is invalid and to false otherwise. If main is declared as “int main”, the return statement must include a value. By convention a non-zero value is used when stopping because of an error.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 20 Logical Operators Example (2) The same effect can be achieved (if in a less intuitive way) using AND and NOT. cin >> lat_1 >> lng_1; if ( !( (lat_1 <= 90.0) && (lat_1 >= -90.0) && (lng_1 <= 180.0) && (lng_1 >= ) ) ) { // input is invalid cout << “...”; return; // in main = “stop” } The boolean expression within !(...) evaluates to true if the input is valid and to false otherwise. The ! flips true to false and vice versa, making the whole expression true if the input is invalid and false otherwise. This is an example of “deMorgan’s Law”.

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 21 Triangle Example (1) We want a program which will read in three values and output whether or not they represent a triangle (e.g. 3, 4, and 5 represent a triangle, but 1, 10, and 2 don’t). If the values do in fact represent a triangle, the program is also to output the angles of the triangle (in degrees) and whether or not any of them exceed 90 degrees. A B C c a b Cos A = ((b 2 + c 2 ) – a 2 ) / 2bc

Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 22 Triangle Example (2) Three values do not represent a triangle if any one of them is greater than or equal to the sum of the other two. In the diagram below, “b” exceeds the sum of “a” and “c”. a c b cout << “...”; cin >> a >> b >> c; if ( (a >= (b + c)) || (b >= (a + c)) || (c >= (a + b)) ) { // we don’t have a triangle... } else { // we do have a triangle... } See sample program triang.cpp.