Announcements Homework 1 will be assigned this week,

Slides:



Advertisements
Similar presentations
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Advertisements

1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
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.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Announcements HW1 grades are announced at SUCourse You may see Belal Amro at his office hour for homework grades at FENS 2014 on Wednesday 10:40-12:30.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
If-else, switch, while, for, do-while Control Statements.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
1 09/15/04CS150 Introduction to Computer Science 1 Life is Full of Alternatives Part 2.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
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.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
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,
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.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
The Ohio State University
Chapter 3 Selection Statements
Chapter 3 Control Statements
if-else, switch, while, for, do-while
Selections Java.
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.
Chapter 4: Making Decisions.
CMPT 201 if-else statement
EGR 2261 Unit 4 Control Structures I: Selection
Announcements General rules about homeworks
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Making Decisions.
Announcements 2nd homework is due this week Wednesday (October 18)
Control Structures – Selection
Chapter 4: Control Structures I (Selection)
Announcements General rules about homeworks
Announcements General rules about homeworks
Announcements 3rd homework is due this week Wednesday (March 15)
Chapter 7 Conditional Statements
Chapter 4 Selection.
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
CS150 Introduction to Computer Science 1
Announcements Homework 1 will be assigned this week,
Chapter 2: Introduction to C++.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Summary of what we learned yesterday
Announcements General rules about homeworks
Announcements HW1 is due TODAY.
Presentation transcript:

Announcements Homework 1 will be assigned this week, will be due on July 14th, next Friday, at 19:00 Common Submission Mistakes Make sure that you send the cpp file; otherwise we cannot grade Please submit the required files only, not the entire project folder 7z, rar and tar format is not allowed for compression; please use zip Do not use blanks, Turkish characters, special symbols in the filenames Only English alphabet letters, digits and underscore are allowed General rules about homeworks Add the following at the end of your code to get a prompt at the end: cin.ignore(); cin.get(); Write comments in your program Use of global variables (variables defined outside of functions) prohibited Modularity and code duplication are important Code duplication must be avoided

Summary of what we learned yesterday Functions – Divide and conquer Functions with Parameters Local variables vs Parameters Scope

Conditional Statements (if–else) Textbook Sections 4.2, 4.3, 4.4 and 4.7

Conditional Statements So far statements of our programs execute sequentially one after another. What happens when we want to execute a statement depending on a condition? e.g. If it snows, announce that the schools are on vacation e.g. If there is enough money in the bank account, give the money we want to execute one statement when a condition holds and another statement when a condition does not hold? e.g. If dollar is high, sell dollar. Otherwise, buy dollar. we want to select from many statements according to one or more criteria (selection). e.g. If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high, sell euro and buy dollar. If both of them are high, sell both and buy TL. You achieve conditional execution with if-else statements

Syntax <condition> must be in parantheses ( ) if (<condition>) { <statement_true_1>; ... <statement_true_N>; } else <statement_false_1>; <statement_false_N>; If condition is TRUE then statement_true_1 … statement_true_N are executed, if condition is FALSE statement_false_1 … statement_false_N are executed. if (<condition>) { <statement_true_1>; ... <statement_true_N>; } else and statement_false’s are optional if condition is FALSE then nothing will be executed and execution continues with the next statement in the program <condition> must be in parantheses ( )

Another Syntax (without { }) if (<condition>) <statement_true>; if (<condition>) <statement_true>; else <statement_false>; Can be used when there is only one statement Not suggested (we will see why)

Flow diagram of if-else test condition true false Loops start with testing a condition first: if the condition is false, the loop exits and moves to the next statement. If the condition is true, the loop statements execute and move to the beginning of the loop. This continues until the condition becomes false. Hence this enables the repetition of the loop statements. true statements false statements next statement

Example (not in the book) Write a program that inputs two integer numbers and displays the maximum one. Two solutions using if and else together using only if (no else)

Solution 1 – with_if_else.cpp int main () { int num1, num2, max; cout << "Enter two numbers: "; cin >> num1 >> num2; if (num1 > num2) // check if first number is larger than the second one max = num1; // if so maximum is the first number } else max = num2; // otherwise maximum is the second number cout << "maximum of these two numbers is: " << max << endl; return 0;

Solution 2 – with_if.cpp (no else) int main () { int num1, num2, max; cout << "Enter two numbers: "; cin >> num1 >> num2; max = num1; // default assignment - maximum is the first number if (num2 > max) // check if second number is larger than the first one max = num2; // if so update the maximum, if not do nothing } cout << "maximum of these two numbers is: " << max << endl; return 0;

Boolean type and expressions The condition in an if statement must be a Boolean expression (named for George Boole) Values are true or false bool is a built-in type like int, double int degrees; bool isHot = false; cout << "enter temperature: “; cin >> degrees; if (degrees > 35) { isHot = true; } Boolean values have numeric equivalents false is 0, true is any nonzero value if (3 * 4 – 8) cout << "hello"; else cout << "bye" ; prints hello boolean output yields 0 (for false) or 1 (true) cout << (4 < 5); prints 1

Relational Operators Relational operators are used to compare values: < less than number < 5 <= less than or equal number <= 0 > greater than num1 > num2 >= greater than or equal num1 >= num2 == equality check num1 == 0 != inequality check num1 != num2 They take two operands operands can be literals, variables or expressions Used for many types numeric comparisons string comparisons (lexicographical, i.e. alphabetical) boolean comparisons (false is less than true)

Examples Let’s look at some examples with literals to better see the boolean results. 23 >= 45 false 49.0 == 7*7 true 34-3 != 30+1 false string s1= "elma", s2= "armut", s3= "Elma"; s1 < s2 false s3 < s1 true Why s3 < s2 is true? ‘E’ has a smaller code than ‘a’ Uppercase letters have smaller codes than lowercase letters

Logical operators Boolean expressions can be combined using logical operators: AND, OR, NOT In C++ we use && || ! respectively A B A || B A && B true false A ! A true false

Example Range check: between 0 and 100 (includes 0 and 100), or not? If so, display a message saying that the number is in the range. If not, the message should say “out of the range”. Solution 1: using logical AND operator if (num >= 0 && num <= 100) cout << "number in the range"; else cout << "number is out of range"; Solution 2: using logical AND and NOT operators if ( ! (num >= 0 && num <= 100) ) cout << "number is in the range"; Solution 3: using logical OR operator if (num < 0 || num > 100)

De Morgan’s Rules (Section 4.7) Compare solution 2 and 3 two conditions are equivalent ( ! (num >= 0 && num <= 100) ) ( num < 0 || num > 100 ) De Morgan’s Rules (assume a and b are two boolean expressions) ! (a && b) = !a || !b ! (a || b) = !a && !b De Morgan’a Rules can be generalized to several expressions (e.g. 4 boolean expressions case) ! (a && b && c && d) = !a || !b || !c || !d ! (a || b || c || d) = !a && !b && !c && !d

Operator Precedence - Revisited Upper operator groups have precedence Operator Explanation Associativity + - ! plus and minus signs, logical NOT right-to-left * / % multiplication, division and modulus left-to-right + - addition, subtraction << >> stream insertion and extraction < <= > >= inequality comparison operators == != equal, not equal comparison && logical and || logical or = += -= *= /= %= assignment operators

Operator Precedence Examples cout << num1 < year; syntax error (very cryptic) the problem is that << has precedence over < does not compile as intended Solution: cout << (num1 < year); Advice: use parenthesized expressions in cout What about (0 <= num <= 100) for range check? not a syntax error but that expression does not make a range check. It is always true. Why? What is the value of !12+5&&32/35 ? result is 0

Nested if statements if/else statements are inside other if/else statements Method to select from multiple choices Example: input a numeric grade and display messages according to its value 0 .. 50 low 51 .. 70 average 71 .. 100 good otherwise invalid grade

Nested if Example Example: input a numeric grade and display messages according to its value 0 .. 50 low 51 .. 70 average 71 .. 100 good otherwise invalid grade Several solutions exist (not in the book) First solution: if’s are after if’s see if_after_if.cpp Second solution: if’s are after else’s see if_after_else.cpp or if_after_else2.cpp

Nested if-else Syntax 1 if condition_1 is TRUE then check condition_2 if (<condition_1>) { if (<condition_2>) if (<condition_3>) <statements_alltrue>; } else < statements_true_1and2>; <statements_true_1_only>; <statements_1_false>; if condition_1 is TRUE then check condition_2 if condition_2 is TRUE then check condition_3 if condition_3 is TRUE statements_alltrue are executed, if condition_3 is FALSE statements_true_1and2 are executed, if condition_2 is FALSE statements_true_1_only if condition_1 is FALSE statements_1_false are executed,

Nested if-else Syntax 2 if condition_1 is TRUE then if (<condition_1>) { <statement_1true_1>; ... <statement_1true_N>; } else if (<condition_2>) <statement_2true_1>; <statement_2true_N>; else if (<condition_3>) <statement_3true_1>; <statement_3true_N>; else <statement_allfalse_1>; <statement_allfalse_N>; if condition_1 is TRUE then statement_1true_1 … statement_1true_N are executed, if condition_1 is FALSE then check condition_2 and if condition_2 is TRUE then statement_2true_1 … statement_2true_N if condition_2 is FALSE then check condition_3 and if condition_3 is TRUE then Statement_3true_1 … statement_3true_N … if condition_(N-1) is FALSE then statement_allfalse_1 … statement_allfalse_N are executed.

Short-circuit Evaluation Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far. Rule: Evaluate the first (leftmost) boolean subexpression. If its value is enough to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. if (count != 0 && scores/count < 60) { cout << "low average" << endl; } In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated. In this way, we avoid “division by zero” error (that would cause to crash the execution of the program) Alternative method to avoid division by zero without using short-circuit evaluation: if (count != 0) if (scores/count < 60) cout << "low average warning" << endl;

Dangling Else Problem What does it display for x=4? if ( x % 2 == 0) if ( x < 0 ) cout << x << " is an even, negative number" << endl; else cout << x << " is an odd number" << endl; What does it display for x=4? The problem is that it displays “odd number” message for positive even numbers and zero. Reason is that, although indentation says the reverse, else belongs to second (inner) if else belongs to the most recent if Solution: use braces (see next slide)

Solution to Dangling Else Problem if ( x % 2 == 0) { if ( x < 0 ) cout << x << " is an even, negative number"<< endl; } else cout << x << " is an odd number" << endl; Now else belongs to the first if if – else matching rule Each else belongs to the nearest if for which there is no else and in the same compound block