32
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 New (2 nd ) homework is assigned last week will be due next week 26 th October Wednesday 19:00 About functions and if-else statements Common Submission Mistakes In HW1, some students submitted empty/wrong files Make sure that you send the cpp file; otherwise we cannot grade rar 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 Please submit the required files only, not the entire project folder General rules about homeworks Use of global variables (variables defined outside of functions) prohibited No abrupt program termination in the middle of the program. Modularity and code duplication are important Code duplication must avoided

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

Embed Size (px)

Citation preview

Page 1: 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

AnnouncementsHW1 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

New (2nd) homework is assigned last weekwill be due next week 26th October Wednesday 19:00 About functions and if-else statements

Common Submission Mistakes In HW1, some students submitted empty/wrong files

Make sure that you send the cpp file; otherwise we cannot grade rar 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 Please submit the required files only, not the entire project folder

General rules about homeworksUse of global variables (variables defined outside of functions) prohibitedNo abrupt program termination in the middle of the program.Modularity and code duplication are important

Code duplication must avoided

Page 2: 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

Summary of what we learned last weekFunctions – Divide and conquerFunctions with ParametersLocal variables vs Parameters

Scope

Page 3: 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

Textbook Sections 4.2, 4.3, 4.4 and 4.7

Conditional Statements(if–else)

Page 4: 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

Conditional StatementsSo 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 YTL.

You achieve conditional execution with if-else statements

Page 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

Syntaxif (<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 ( )

Page 6: 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

Another Syntax (without { })

if (<condition>)<statement_true>;

else<statement_false>;

if (<condition>) <statement_true>;

• Can be used when there is only one statement• Not suggested (we will see why)

Page 7: 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

Flow diagram of if-else

test condition

truestatements

true

nextstatement

false

falsestatements

Page 8: 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

Example (not in the book)Write a program that inputs two integer numbers and

displays the maximum one.Two solutions

using if and else togetherusing only if (no else)

Page 9: 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

Solution 1 – with_if_else.cppint 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;

}

Page 10: 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

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;

}

Page 11: 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

Boolean type and expressions The condition in an if statement must be a Boolean expression

(named for George Boole) Values are true or falsebool 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 valueif (3 * 4 – 8)

cout << "hello";else

cout << "bye" ; prints hello

boolean output yields 0 (for false) or 1 (true) cout << (4 < 5);

prints 1

Page 12: 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

< 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

Relational Operators Relational operators are used to compare values:

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)

Page 13: 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

ExamplesLet’s look at some examples with literals to better see

the boolean results.

23 >= 45 false 49.0 == 7*7 true34-3 != 30+1 false

string s1= "elma", s2= "armut", s3= "Elma";s1 < s2 falses3 < s1 true

Why s3 < s2 is true? ‘E’ has a smaller code than ‘a’ Uppercase letters have smaller codes than lowercase letters

Page 14: 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

Logical operatorsBoolean expressions can be combined using

logical operators: AND, OR, NOTIn C++ we use && || ! respectively

A B A || B A && B

true true true true

true false true false

false true true false

false false false false

A ! A

true false

false true

Page 15: 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

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 operatorif (num >= 0 && num <= 100)cout << "number in the range";

elsecout << "number is out of range";

• Solution 2: using logical AND and NOT operators

if ( ! (num >= 0 && num <= 100) )cout << "number is out of range";

elsecout << "number is in the range";

• Solution 3: using logical OR operatorif (num < 0 || num > 100)cout << "number is out of range";

elsecout << "number is in the range";

Page 16: 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

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

Page 17: 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

Operator Precedence - RevisitedUpper 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 left-to-right

<< >> stream insertion and extraction left-to-right

< <= > >= inequality comparison operators left-to-right

== != equal, not equal comparison left-to-right

&& logical and left-to-right

|| logical or left-to-right

= += -= *= /= %=

assignment operators right-to-left

Page 18: 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

Operator Precedence Examplescout << num1 < year;

syntax error (very cryptic)the problem is that << has precedence over <

does not compile as intendedSolution: cout << (num1 < year);Advice: use parenthesized expressions in cout

What about (0 <= num <= 100) for range check?not a syntax errorbut 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

Page 19: 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

Nested if statementsif/else statements are inside other if/else statementsMethod to select from multiple choicesExample: input a numeric grade and display messages

according to its value0 .. 50 low51 .. 70 average71 .. 100 goodotherwise invalid grade

Page 20: 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

Nested if ExampleExample: input a numeric grade and display messages

according to its value0 .. 50 low51 .. 70 average71 .. 100 goodotherwise invalid grade

Several solutions exist (not in the book)First solution: if’s are after if’s

see if_after_if.cppSecond solution: if’s are after else’s

see if_after_else.cpp or if_after_else2.cpp

Page 21: 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

if (<condition_1>)

{

if (<condition_2>)

{

if (<condition_3>)

{

<statements_alltrue>;

}

else

{

< statements_true_1and2>;

}

}

else

{

<statements_true_1_only>;

}

}

else

{

<statements_1_false>;

}

Nested if-else Syntax 1if condition_1 is TRUE then check

condition_2

if condition_2 is TRUE then check

condition_3if condition_3 is TRUE

statements_alltrue are executed,

if condition_3 is FALSEstatements_true_1and2 are executed,

if condition_2 is FALSEstatements_true_1_only are executed,

if condition_1 is FALSEstatements_1_false are executed,

Page 22: 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

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>;

}

Nested if-else Syntax 2 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 thenstatement_2true_1 … statement_2true_N are executed,

if condition_2 is FALSE then check condition_3 and if condition_3 is TRUE thenStatement_3true_1 … statement_3true_N are executed,

… if condition_(N-1) is FALSE then

statement_allfalse_1 … statement_allfalse_N are executed.

Page 23: 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

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; } }

Page 24: 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

Dangling Else Problemif ( 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) ifelse belongs to the most recent if

Solution: use braces (see next slide)

Page 25: 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

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 ifif – else matching rule

Each else belongs to the nearest if for which there is no else and in the same compound block

Page 26: 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

Functions OverviewFunctions are

sequence of statements with its own local variablessupports modularity, reduces code duplication

Data transfer between function to be called and caller functionby means of parameterscurrently one-way

from caller function into function to be calledLater we will see how to return data back to the caller

function

Page 27: 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

Function Prototype (from 2.6)Functions definition has two parts

function heading name, parameters, return type

function body (local variables and statements within curly brackets)

void display (string name){ cout << “Hello ” << name << endl;}

Like variables, a function must be declared before its first callProblem of function declaration order

You cannot call a function before you declare itSOLUTION: You may define function prototypes (a copy of

the heading) at the beginning without function declarations

Page 28: 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

Function Prototype – Example Problem

What is the problem below (program order.cpp) ?

void Hi (string name){ cout << "Hi " << name << endl; Greetings();}

void Greetings(){ cout << "Things are happening inside this computer" << endl;}

int main(){ Hi("Fred"); return 0;}

Greetings() is called in Hi() but it is declared afterwards

Page 29: 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

Function Prototype – SolutionAdd function prototypes to the beginning (order2.cpp)

#include <iostream>#include <string>using namespace std;

void Hi(string);void Greetings();

void Hi (string name){ cout << "Hi " << name << endl; Greetings();}

void Greetings(){ cout << "Things are happening inside this computer"

<< endl;}

int main(){ Hi("Fred"); return 0;}

Prototypes

Function

Declarations

Page 30: 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

Function Prototypes*** Do not forget semicolon after the prototype

definition ***no semicolon after the parameters in normal definition

Sometimes prototypes are not necessaryif the order of function calls allowsbut it is good programming practice to have them

Parameter names are not needed in prototypesbut it is OK if you have the parameter names

In #included files we have the functions’ prototypes onlyimplementations of function bodies are in libraries or in other

cpp files they are linked together

Page 31: 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

You can use enum type when you want to define all the possible values for your typetype for CardSuittype for colors

Type definition syntaxenum TypeName {list of literals separated by comma};

Type definition exampleenum CardSuit {spade, heart, diamond, club};

You can define variables of enum types, you can use them as parameters and return types throughout the cpp fileAn enum type must be defined at global level (after

using namespace std; and before the function declarations)

Enumerated Types (Section 9.3.4)

Page 32: 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

Enum types Example use

enum CardSuit {spade, heart, diamond, club};

CardSuit c;c = club;

Each constant of an enum type has an associated integer code starting from 0 spade is 0, heart is 1, diamond is 2, club is 3

Displaying an enum type variable actually displays its integer codecout << c; // displays 3

Cannot assign an integer to an enum variablec = 2; // illegalc = CardSuit(2); // legal, c becomes diamond

Cannot input into an enumcin >> c; // invalid

Can use comparison operators (<, >, <=, >= operators compare codes)

if (c <= heart)cout << "hi" << endl;