You are on page 1of 35

if Statements

Slide 2

Introduction
Three program structures: Sequence
Statements in the given order

Condition statement (branching)


Chooses between two (or more) sequences depending on some condition
if <condition exists>{ <do P> } else { <do Q> }

Iteration statement (looping)


repetitively execute a given sequence
while <condition exists>{ <do P> }

Slide 3

Structured programming
Any program can be written as a sequence of three basic program structures!!! 1. sequences, 2. conditionals, 3. and iterations

Slide 4

The fundamental if-else Statement


Choose between two alternative actions depending on a test (on the values of variables).
Syntax if (Expression) Action1 else Action2 If Expression is true then true execute Action1 otherwise execute Action2 Action1 Example if(v == 0) cout << "v is 0"; else cout << "v is not 0"; Expression false

Action2

Slide 5

Its common in everyday life

if <it's sunny>{ <go to beach with sun block> } else{ <go to beach with umbrella> }

Slide 6

Example: Finding the Big One


int main() { int value1; int value2; int larger; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2) larger = value1; else larger = value2; cout << "Larger of inputs is: " << larger << endl; return 0; }

Slide 7

Example: Absolute Value (1st )


// program to read number & print its absolute value #include <iostream.h> int main(){ int value; int absvalue; cout << "Enter integer: "; cin >> value; if(value < 0) absvalue = -value; else absvalue = value; cout << "The absolute value is " << absvalue << endl; return 0; }

Slide 8

When the action is more than one statement


Put multiple action statements within braces
if <it's raining>{ <take umbrella> <wear raincoat> } else { <take sunbathing stuff> }

Slide 9

Example: Absolute Value (2nd)


// program to read number & print its absolute value #include <iostream.h> int main(){ int value; int absvalue; // absolute value cout << "Enter integer: "; cin >> value; if (value < 0) { absvalue = -value; cout << "The input value is positive and its absolute value is " << absvalue << endl; } else { absvalue = value; cout << "The input value is negative and its absolute value is " << absvalue << endl; } return 0; }

Slide 10

How to create an expression for a test?


An expression for a test (a boolean expression) has one of the two values: true or false.

Using relational operators Using boolean (logical) operators

Slide 11

Using Relational Operators


Relational operators are used to compare two values Math C++ Plain English = == equals [example: if(a==b) ]
[ (a=b) means put the value of b into a ]

< >

< <= > >= !=

less than less than or equal to greater than greater than or equal to not equal to

Slide 12

Relational Expressions
Examples:
numberOfStudents < 200 10 > 20 20 * j == 10 + i

Slide 13

Using Boolean (logical) operators


Boolean operators can be used to form more complex conditional expressions

Logical AND operator Logical OR operator Logical NOT operator (x>5) && (x<10) (x>10) || (x<5) !(x>5)

&& || !

Examples:

Warning!

& and | are also operators

Slide 14

A Boolean Type

C++ contains a type (new!!!) named bool which can have one of two values

true false

(corresponds to non-zero value) (corresponds to zero value)

Example logical expressions bool P = true; bool Q = false; bool R = true; bool S = P && Q; bool T = !Q || R; bool U = !(R && !Q);

Slide 15

Operator Precedence
Which comes first? ( ) / >= != =

Answer:
<

* + <= ==

% >

Slide 16

Summary of Operator Precedence


Precedence of operators (from highest to lowest)

arithmetic relational

logical

Parentheses Unary operators Multiplicative operators Additive operators Relational ordering Relational equality Logical and Logical or Assignment

( ) ! * / % + < <= >= > == != && || =

Slide 17

Example:

5 != 6 || 7 <= 3 (5 !=6) || (7 <= 3)


5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

Slide 18

Boolean expressions

Arithmetic expression: use arithmetic operators +,,*,/, to produce a number as the final result Boolean expression: use relational operators <,>, ==, and boolean operators AND (&&), OR (||), NOT (!) to produce one of the two values true (1) and false (0) as the final result

New type: bool, true, false Old versions of C++, simulated boolean type by int with 0/1 Example: bool cond; cond = true; cond = (x>y);

If (BOOLEAN EXPRESSION)

Slide 19

Alternative ways of writing choice statements

If statement Nested if If-else-if statement Switch statement

Slide 20

The if Statement
Syntax
if(Expression) Action Expression

If the Expression is true then execute Action Action is either a single statement or a group of statements within braces Example: absolute value
if(value < 0) value = -value;

true

false

Action

Slide 21

Example: Absolute Value (3rd )


// program to read number & print its absolute value #include <iostream.h> int main(){ int value; cout << "Enter integer: "; cin >> value; if(value < 0) value = -value; cout << "The absolute value is " << value << endl; return 0; }

Slide 22

Example: Sorting Two Numbers

int value1; int value2; int temp; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2){ temp = value1; value1 = value2; value2 = temp; } cout << "The input in sorted order: " << value1 << " " << value2 << endl;

Slide 23

Nested if Statements

Nested means that one complete statement is inside another


if <condition 1 exists>{ <do A> if <condition 2 exists>{ <do B> if <condition 3 exists>{ <do C> } <do D> } <do E> } <do F: sleep>

Slide 24

Nested if Statements

Example:
if <it's Monday>{ if <it's 9:00 am>{ if <it's raining>{ <bring umbrella> } <go to COMP 104> } <call your friends> }

Slide 25

if-else-if Statements
if <condition 1 exists>{ <do Q> } else if <condition 2 exists>{ <do R> } else if <condition 3 exists>{ <do S> } else{ <do T> }

Q R S T

Slide 26

if <Mon, Wed AM>{ <goto ICSM121> } else if <Tues, Thurs AM>{ <goto MTHS001> } else if <1PM or 7PM>{ <eat> } else{ <sleep> }

Slide 27

Selection
Often we want to perform a particular action depending on the value of an expression Two ways to do this

if-else-if statement
if-else

statements glued together

switch statement
An

advanced construct

Slide 28

switch Statement
An alternative way of writing nested if-else-if statements for multiple choice.
switch (Expression) { case constant_1: action1; break; case constant_2: action2; break; case constant_n: actionN; break; default: actionDefault } if Exp==constant_1 { action1; } else if Exp==constant_2 { action2; } else if { } else{ actionDefault }

Slide 29

Example using if-else-if:


if(score >= 90) cout << "Grade = A" else if(score >= 80) cout << "Grade = B" else if(score >= 70) cout << "Grade = C" else if(score >= 60) cout << "Grade = D" else cout << "Grade = F" << endl; << endl; << endl; << endl; << endl;

Slide 30

Example using switch:


switch(int(score)/10){ case 10: case 9: cout << break; case 8: cout << break; case 7: cout << break; case 6: cout << break; default: cout << } Logical OR "Grade = A" << endl; "Grade = B" << endl; "Grade = C" << endl; "Grade = D" << endl; "Grade = F" << endl;

This version is much easier to understand!

Another example:
int left; int right; char oper; cout << "Enter simple expression: "; cin >> left >> oper >> right; cout << left << " " << oper << " " << right << " = "; switch (oper) { case '+' : cout << left + right << endl; break; case '-' : cout << left - right << endl; break; case '*' : cout << left * right << endl; break; case '/' : cout << left / right << endl; break; default: cout << "Illegal operation" << endl; }

Slide 32

Dangling Else Problem


Problem: Nested if statements can seem ambiguous in their meaning. What is the value of c after the following is executed?
int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else c = 3;

Slide 33

C++ groups a dangling else with the most recent if. The following indentation shows how C++ would group this example (answer: c=1).
int a=-1, b=1, c=1; if(a>0) if(b>0) c = 2; else // dangling else grouped to nearest if c = 3;

Slide 34

Use extra brackets { } to clarify the intended meaning, even if not necessary.
int a=-1, b=1, c=1; if(a>0){ if(b>0) c = 2; else // parenthesis avoid dangling else c = 3; }

Slide 35

Summary on condition statement

The fundamental If-else statement if, nested if, if-else-if, switch Bool type and boolean expression for a test true/false relational operators (==, <, ) logical operators (&&, ||, !) Full table of operator precedence (c++ technicality)

You might also like