Presentation is loading. Please wait.

Presentation is loading. Please wait.

If Statements.

Similar presentations


Presentation on theme: "If Statements."— Presentation transcript:

1 If Statements

2 Boolean Expressions Bools are a data type which take on two values:
1. true (1) 2. false (0)

3 Boolean Expressions Bools can be used in a variety of expressions to express different logical statements. a && b – true if both a and b are true a || b – true if at least one of a and b are true !a true if a is false Other expressions produce bools: a < b – true if a is less than b a > b – true if a is greater than b a <= b – true if a is less than or equal to b a >= b – true if a is greater than or equal to b a == b – true if a equals b a != b – true if a does not equal b

4 Boolean Expressions Try evaluating these expressions! In the following expressions a is true, b is false, c is 0, d is 1. 1. a && b 2. (b || b) && a 3. b || (b && a) 4. !a == b 5. !(b || (!a)) 6. (a && b) || (c < d) 7. a + b 8. -2 < -1 < 1

5 Conditionals Sometimes we want to make choices.
If statements enable that! int money = 10; if (money < 5) {cout << “lentils for dinner” << endl;} else if (money < 10) {cout << “burgers for dinner” << endl;} else {cout << “lobsters for dinner” << endl;}

6 Basic Syntax if (condition) { ... } else if (condition) } else }

7 Sample Program #include <iostream> using namespace st
int main() { double x = 0; cout << “Please input a number: \n”; cin >> x; if (x < 0) {cout << “x is negative”;} else if (x < 1) {cout << “x >= 0 and x <= 1”;} else {cout << “x >= 1”;} }

8 Problems using if statements
1. Write an if statement that will print out “Yes” if at least one of the numbers a, b, and c are positive. Base Code: If (_____) cout << “Yes”; 2. You are given an integer a. Write an if statement which will print out “fizz” if a is divisible by 3, “buzz” if a is divisible by 5 and “fizzbuzz” if a is divisible by both 3 and 5. (Hint: use % to check divisibility)

9 Gotchas Assigning instead of testing for equality. What happens in the following statement? int a = 0; if (a = 1) cout << “a equals 1”; ”a = 1” sets a to 1, and then returns the value of a. So it prints when it should not

10 Challenge Program What does the following program output? What are the values of a and b after if statement? int a = 0; bool a = 0, b = 1; if (a = b) cout << “1: true\n”; else cout << “1: false\n”; if (a = 0) cout << “2: true\n”; cout << “2: false\n”; if (b = a) cout << “3: true\n”; cout << “3: false\n”;


Download ppt "If Statements."

Similar presentations


Ads by Google