Informatik I für D-MAVT (FS 2013)
Exercise 4 – Logical Operators &
Branching
Christian Schumacher
Agenda
2
Branching
relational operators
logical expressions: and, or, not
if, else if, else
switch
“? : “ operator
Arrays
introduction
argc and argv[] in main()
Relational operators
Used to compare two values
The whole term is called an expression (Ausdruck)
The result of the comparison is either TRUE (1) or FALSE (0)
Relational operators are evaluated after other arithmetic
operations
e.g., (1+2 < 1+3) is TRUE.
3
int a=3, b=5;
bool res;
res = a < b; //less
res = a <= b; //less or equal
res = a > b; //greater
res = a >= b; //greater or equal
res = a == b; //equal
res = a != b; //not equal
Difference between „=“ and „==“
= is the assignment operator
Changes the value of the variable on the left to the value on the right
The result (meaning the value of the expression) is equal to the
assignment value
== is the equality operator
Evaluates whether the 2 values on the left and the right are equal
The result can be either TRUE or FALSE
Example:
4
int a=3, b=5;
bool res;
res = (a == b); //“res“ is FALSE, because 3!=5
res = (a = b); //“res“ is TRUE, even though 3!=5.
//Also, a is set to 5!
Boolean Algebra: AND, OR, NOT
x AND y is TRUE if and only if both x and y are
TRUE.
x OR y is FALSE if and only if both x and y are
FALSE.
(x OR y is TRUE if either x, y or both are TRUE.)
NOT x is TRUE if x is FALSE, and vice versa.
5
AND 0 1
0 0 0
1 0 1
OR 0 1
0 0 1
1 1 1
NOT
0 1
1 0
Logical Operators in C++: &&, ||, !
Works on Boolean values (bool type)
6
bool a = true;
bool b = false;
logical AND a && b == false
a && a == true
logical OR a || b == true
b || b == false
logical NOT !a == false
!b == true
„if“ statement
If condition is TRUE, the instruction(s) inside the
code block { } are executed.
Otherwise, if condition is FALSE, the block is
jumped over.
7
if (condition) { DoSomething();
}
if (a==5) { cout << "a is equal to 5!\n“;
}
„else if“ statement
The „else if“-condition is only checked if the
preceding condition(s) are FALSE. It states an
alternative which is evaluated when the other
conditions are not met.
Otherwise, it behaves the same as an „if“ statement.
Many „if – else if – else if – else if...“ statements can
be chained to form a complex program flow.
8
if(firstCondition) { DoSomething(); } else if(secondCondition) { DoSomethingElse(); }
if(a==5) { cout << "a is equal to 5!\n"; } else if(a==10) { cout << "a is equal to 10!\n"; }
„else“ statement
The „else“ code block is executed if all other conditions are
FALSE.
Remember:
The program runs from top to bottom, line after line.
After one if/else if/else block { } is executed, the program jumps to
the bottom of the whole „if – else if – else“ statement.
9
if(firstCondition) { DoSomething(); } else if(secondCondition) { DoSomethingElse(); } else { IfEverythingElseFails(); }
switch statement
Switch statement replaces long chains of „if – else if – ...“ with
equality comparisons
Program jumps to the case corresponding to value of the
variable
The program jumps to default if the variable doesn‘t match
any cases
The default case is optional 10
switch (variable) {
case 0:
cout<<”variable is 0!\n";
break;
case 7:
cout<<”variable is 7!\n";
break;
default:
cout<<”variable is ???\n";
}
switch statement 2
In contrary to if/else if statements, the program does not jump to the
bottom after a case has been handled. This is why we need the
„break;“ command after every case that we want to treat individually.
Without break, everything that follows in the same „switch“ statement
is executed until we reach another break.
We don‘t need a break for the default case because it is placed at the
bottom anyway.
11
switch (variable) {
case 1:
case 3: //var. is either 1 or 3
DoSomething();
break;
default:
DefaultCase();
}
Comparison: if/else and switch
12
if (x == 1) {
cout << “x is 1” << endl;
}
else if (x == 2) {
cout << “x is 2” << endl;
}
else {
cout << “x is something else”
<< endl;
}
switch (x) {
case 1:
cout << “x is 1” << endl;
break;
case 2:
cout << “x is 2” << endl;
break;
default:
cout << “x is something else”
<< endl;
}
if/else statement switch statement
„? : “ operator
The „? : “ operator returns the first value if the
condition is TRUE, and the second value if the
condition is FALSE.
It can be used with any types of values.
13
value = condition ? valTrue : valFalse;
int bearDmg = isStrong ? 100 : 45;
string name = firstName ? "Hansulrich" : "Hubschmid";
any type (int, float, …) type bool same type as “value”
Introduction to arrays
This topic will be covered in more detail the next
week!
This week: Explanation for the „argv“ variable used
in the main() function.
14
Introduction to arrays 2
An array is a variable that holds many values of the same type
Number of elements defined in square brackets [ ]
The individual elements can be accessed using square
brackets [ ]:
15
float vectorA[3];
vectorA[0] = 3.1f; float f = vectorA[1];
Arrays are zero-based: Their indices go from 0 to size-1!
First element of vectorA is vectorA[0]
Last element of vectorA is vectorA[2]
argc and argv in main()
argc: argument count
argv: argument vector
argv is an array of „char *“ (C strings, meaning „text“), as
indicated by the brackets [ ]
Each element of argv (argv[0], argv[1], ..., argv[argc-1]) holds
one program argument in text form
Often converted using atof() or similar functions (see ex. 2)
More on C strings next week!
16
int main(int argc, char *argv[]) { //... }
argc and argv in main() 2
When running a program from the terminal, arguments can be
passed to it like shown in the example command above.
In Eclipse, use Run -> Run Configurations -> Arguments
argv[0] (first element) always contains the program path and
name and has no further meaning.
17
./MyProgram 47 11 Cologne
index argv
0 ./MyProgram
1 47
2 11
3 Cologne
argc = 4;
On the „char“ variable type
A char variable usually uses 1 Byte of memory
Only 256 different values (i.e., characters) can be stored
Char variables are stored as numbers internally.
Implications:
Chars can be cast to and from other numeric data types
(such as ints or floats)
Integer operations and comparisons (+, -, <, >, etc.) can
be used with chars
char a = 'a', b = 'b';
bool res = a < b; //TRUE
On the „char“ variable type
Value of a char variable represents a character
Corresponding character given by ASCII table
Easily found with Google
Use ' ' to assign characters
char a = 'G'; is identical to char a = 71;
… … …
Exercise hints
Task 1: Keep operator priority in mind
&& evaluated before ||
Task 1/5: Take a look at an ASCII table
Characters 'a' to 'z' and 'A' to 'Z' form two
separate intervals within the ASCII values
20
Exercise 2 recap
Variable type affects what you read with cin vs.
Decimal places may get lost if you use int
Keep integer division in mind
9/5 is not the same as 9.0/5.0 (in C++)
21
int a;
cin >> a;
float b;
cin >> b;