0% found this document useful (0 votes)
18 views7 pages

W3 Branches

Learn C++ 3

Uploaded by

Ro Ben
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

W3 Branches

Learn C++ 3

Uploaded by

Ro Ben
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

W3-branches

February 4, 2021

1 Week 3 - branches
1.1 Setup
[18]: #include <iostream>
#include <string>
using namespace std;

1.2 Recap (useful also for Test 1)


What are expressions? A: something that has a value, type, and possibly a side effect. More
precisely, this something is a sequence of operands, operators, and parentheses.
[2]: // example of integer expression
int a = 23; // declaration with initialization
(2*a*a - 67)/2; // value: 495; type: int; side effect: none.

[2]: 495

[3]: a = 4*4.1;
// expression: value 16, type: double; side effect: variable a is assigned␣
,→value 16

[3]: 16

Note: value of operator = (assignment) is the value of the expression to the right of =.

[4]: cout << (2*a*a - 67) / 2 << endl;


// actually also an expression: value: cout; type: stream class; side effect:␣
,→output

222

[4]: @0x7f4941b56b60

In the expression above, what are the: 1. Operands: cout, 2, a, 67, endl. 2. Operators: «, *, -, /.
What is the role of ()?

1
1.2.1 Order of evaluating operators
1. Precedence: which operator is evaluated first when there are many of different kinds?
1. Math order: - (unary) has higher precedence than *,/,% which has higher precedence
than +,- (binary operators)
2. « (output) has low precedence, so we can write nice output statements without too many
().
3. = (assignment) has low precedence, so we can write nice assignment statements without
too many ().
4. For the full list, see (https://en.cppreference.com/w/cpp/language/operator_precedence).
2. Associativity: which operator is evaluated first when there are many operators of the same
kind?
1. Math associativity: *, /, +, -: left to right.
2. «, »: left to right.
3. = (assignment): right to left(!).

[5]: a = 3;
4*-a+5 // 1st do - (unary) -> -3; 2) * next : 4 times -3 = -12; 3) + next.

[5]: -7

[6]: // declare two integer variables x, y and assign value 1 to both.


int x,y=1; // two declarations, only the second is initialized.
cout << x << " " << y ;

0 1

[7]: // declare 2 ints, initialize to 1


int x1, y1;
x1 = y1 = 1; // works because = (assignment) is right associative
cout << x1 << " " << y1;

1 1

[8]: // output the value of variable a but write a nice message


cout << "Variable a is " << a;

Variable a is 3

1.2.2 Practice with evaluating expressions

[9]: 1/2/2.0 // -> 0 / 2.0 -> 0.0

[9]: 0.0000000

[10]: 1/(2*2.0) // -> 1/4.0 -> 0.25

[10]: 0.25000000

2
[11]: 3 * -2 + 2 / (0.5 / 2) // unary first -> 3 * (-2) + 2 / (0.5 / 2)
// () next -> 3 * (-2) + 2 / 0.25
// * next -> -6 + 2 / 0.25
// / next -> -6 + 8.0 = 2.0

[11]: 2.0000000

[12]: int a = 9;
cout << 2 * a / (a+1);

2 Boolean expressions
A new type: Boolean, and two new literals (constant value of type bool). Boolean types are actually
integers. True equivalent to non-zero; false equivalent to zero.
[13]: bool eligible = false;
cout << eligible << endl;
// if we want to see the bool literals:
cout << boolalpha << eligible;

0
false

[14]: bool eligible = false;


cout << eligible << endl;
// if we want to see the bool literals:
cout << boolalpha << eligible;

false
false
boolalpha modifies the state of cout until it is reset, for example until we output the flag noboolalpha.
[15]: bool eligible = false;
cout << eligible << endl;
// if we want to see the bool literals:
cout << noboolalpha << eligible;

false
0

2.1 Relational operators


Relational (a.k.a comparison) operators evaluate to a boolean value: <, >, <= (for ≤), >= (for
≥), == (for equality, not assignment), != (for ̸=).

3
Semantics (meaning) of comparison operators: 1. Like in math for numerical operands. 2. Lexico-
graphic (dictionary) order for string type operands.

[16]: // try some relational operators here:


cout << boolalpha;
cout << (2 < 3) << endl;
cout << (2 <= 3) << endl;
cout << (3 < 3) << endl; // false because 3 is equal to 3, not less
cout << (3 <= 3) << endl; // true because 3 equals 3
cout << (2 == 3) << endl;
cout << (2 != 3) << endl;
cout << (2 = 3) << endl; // error

input_line_32:10:12: error: expression is not


assignable
cout << (2 = 3) << endl; // error
~ ^

Interpreter Error:

Note please be careful about not confusing = (assignment) with == (comparison) operator.

[ ]: int a = 2;
cout << boolalpha;
cout << (a == 3) << endl;
cout << (a = 3) << endl; // interpreted as true because 3 is not zero.

Comparison can be used with string expressions. In this case, a string A is less than another string
B if A appears before B in dictionary order (lexicographic order).
Exception: Unlike in a dictionary, there is a distinction between uppercase and lowercase letters.
Uppercase letters appear before all of the lowercase letters!
[ ]: cout << boolalpha;
cout << (string("cat") < "dog") << endl;
cout << (string("cat") < "Dog") << endl;

Exception 2: we can compare text expressions of the type string. We cannot compare, for example,
two string literals, because a string literal is not of type string actually. A string literal has type
called “c-string” (more about this later).

[ ]: cout << ("cat" < "Dog") << endl;

4
3 Simple if statements

Statement: use block statements: { one or more statements separated by ; }.


Example: Write code to read the GPA and output the eligible scholarship(s).

Scholarship A

Min GPA 3.5

[ ]: double gpa;
cin >> gpa;

Simple ifs: use sequentially, when branches do not depend on each other. For example, one is
eligible for any number of scholarships.

Scholarship A Scholarship B Scholarship C

Min GPA 3.5 3.65 3.80

[ ]: double gpa;
cin >> gpa;

5
4 If Else statements

Use: 1. When EITHER the true branch OR the false branch must be executed. Ex: print if eligible
for Scholarship A, otherwise print “not eligible”. 2. Nesting if statements on the else branch is very
useful. Ex: test for ranges.
[ ]: // read GPA and print Eligible for Schlarship A / Not eligible.
double gpa;
cin >> gpa;

Example for testing ranges: read a temperature in C. Print:

Temperature (C) below 0 between 0 and 20 between 20 and 25 higher than 25

Cold Pleasant Warm Hot

Strategy 1. List boundary values in order: 0, 20, 25. 2. Start from one end, ex low to high (also
high to low possible) 3. Nest if-else statements on the else branch. Do not use {} on the else
nested branches (improves readability of the code). 4. Test boundary values with ≤ if coming low
to high (≥ if coming high to low).
Strategy: identify a simple test that could tell, without a doubt, the outcome of at least one of
the branches (true or false). Here, there are 2 test, test with 0 and with 25.

[ ]: // design code coming low to high (I mean, start with 0)


float temp;
cin >> temp;
if (temp < 0) {
cout << "cold";
}
else if (temp < 20) {
cout << "pleasant";
}
else if (temp < 25) {
cout << "warm";
} else {
cout << "hot";

6
}

[ ]: // design code coming high to low

4.1 Logical operators

Operator AND OR NOT

C++ operator && || !

Practice: given integer variable a which you read from input. Test if a is between 10 and 100
(including the boundary values).

[ ]: cout << true << " " << ! true << endl;
cout << (true && false) << endl;
cout << (true || false);

Practice: given integer variable a which you read from input. Test if a is not between 10 and 100
(including the boundary values). Translate 10 ≤ a ≤ 100 in English using AND, OR, NOT, greater
and equal to, etc… a is greater or equal to 10 AND a is less than or equal to 100.
[21]: int a;
cin >> a;
cout << boolalpha << ((a >= 10) && (a <= 100));

134
false

4.2 Logical operators and shortcut


If the outcome of a logical operator is determined by the value of its first argument, ten the second
argument is not evaluated (any side effects will not happen for the second argument).

[22]: int a=0;


bool orex = true || (a=-1);
cout << a;

[23]: int a=0;


bool orex = false || (a=-1);
cout << a;

-1
Homework: How would this code be revised to test the AND operator shortcup property?
[ ]:

You might also like