- Normally, programs have sequential control flow
- However, more complex problems require decisions
- Conditionals are how we can make some code execute under some condition(s) and/or other, different code to execute under other conditions
if-statements,if-elsestatements,if-else-ifstatements- Conditionals rely on some logical condition
if(<condition>) {
//the code inside this block will execute if and only
//if the <condition> evaluates to true
}
if(<condition>) {
//block A
} else {
//block B
}
if(<condition1>) {
//block A
} else if (<condition2>){
//block B
} else {
//block C
}<, >, <=, >=- Equality operator:
== - Inequality operator:
!= - All of these numeric comparison operators can operate on literals (fixed, hardcoded values), variables, or expressions
- Work in both languages for the 3 basic types
int a;
double b, c;
if(a == 0) {
//...
}
//alternatively you could, but shouldn't do:
if(0 == a) {
//...
}
//compare values stored in two variables:
if(a == b) {
//...
}
//you can also use expressions:
if(b * b - 4 * a * c < 0) {
//...
}
//you can, but shouldn't: tautology
if(10 < 20) {
//....
}- Any logical expression can be negated using a single
! (a == b)has a negation of!(a == b)but really should rewrite this as(a != b)- Ex:
(a <= b)has a negation of!(a <= b)but really you should write(a > b)
- Often, you'll want to use boolean variables (variables that can hold a truth value, either true or false)
- In C: there are no boolean variables, there is no keyword "true" nor "false"
- Instead: you use an
intvariable- False is always 0
- True is anything else, ie any non-zero value (5, 3.5, -2, etc.)
- But, the convention is to use 1 for true
- In Java: you have a
booleanvariable type that can be assigned the valuestrueorfalse
boolean isStudent;
isStudent = true;
isStudent = false;
if(isStudent) {
System.out.println("You get a 20% discount!");
}
if(!isStudent) {
System.out.println("You do not get a discount!");
}int isStudent;
//set it to true:
isStudent = 1;
//set it to false:
isStudent = 0;
if(isStudent) {
printf("You get a discount\n");
}
if(!isStudent) {
printf("full price\n");
}- You can combine logical statements to form more complex logical statements using "connectives" or logical operators
- The logical AND is true if and only if both of its operands (sides) are true
- Syntax:
&& - Ex:
a && bwhere a and b are expressions or variables, etc. - This is true if and only if
ais true andbis true - It is false when either
ais false orbis false or they are both false
- Syntax:
- The logical OR operator is true if at least one of its operands is true
- Syntax:
|| - Example:
a || b - true if
ais true or ifbis true or if both are true - false when both
aandbare false
- Syntax:
- Fact:
!(a && b)(DeMorgan's Law) is equivalent to(!a || !b)
if(a > 10 && a < 20) {
//a = 5: false
//a = 15: true
//a = 25: false
}
if(a == b && a < 10) {
//a = 5, b = 5: true
//a = 5, b = 10: false
//a = 10, b = 10: false
}
if(a > 10 || a < 20) {
//a = 5: true
//a = 15: true
//a = 25: true
}
if(a == b || a < 10) {
//a = 5, b = 5: true
//a = 5, b = 10: true
//a = 10, b = 10: true
}- Consider the following C code:
if(0 <= a <= 10) {
...
}- IN C, the above code will compile, and execute and will not work for certain values (ex: 20)
- C will evaluate the first expression giving a value (say 1) and then the second expression, giving an overall true value
- Solution:
if(0 <= a && a <= 10) {
...
}-
In Java, the above mistake is not even possible: it is a compiler error
-
Consider the following code:
//C:
int a = 5;
if(a = 10) { ... }-
The above will compile and run but give bad results
-
a = 10is an assignment, which assigns the value of 10 toaand 10 is true, thus the condition will always evaluate to true -
This mistake is not possible in Java
-
Keep an eye out for such things by using a good font!
-
Consider the following code:
if(a == 10); {
printf("a is 10!\n");
}-
An empty code block may or may not execute, but the code block in curly brackets is not bound to the conditional statement
-
Make your life easier in C: use gcc as a linter
- Lint: not necessarily "dirt" (or syntax errors) but likely stuff in code that we don't want or didn't actually intend to have
- gcc can be used as a simple linter using the flag
-Wall(warnings, all of them)
- Consider a logical and:
a && b- If
aevaluates to false, does it matter what the value ofbis? - NO; since the first one is false, then whether or not the second is true does not matter, the entire expression evaluates to false
- Neither programming language wastes time evaluating the second expression
- If
- Consider a logical or:
a || b- If
aevaluate to true, does it matter what the value ofbis? - NO, the first being true, makes the entire statement true, so the second is irrelevant
- Neither programming language wastes time evaluating the second expression
- If
- This called "short circuiting"
- Why? Its more efficient to skip operations if you can.
- Today: all languages still do this because of familiarity
- Programmers expect this behavior and program toward it: they often use programming idioms to exploit it
- In C, always remember to use the
-Wallflag with gcc to catch "bad" code - In Java: don't ignore the warnings, take care of them
- In both languages, you can compare single
charvalues
char initial = 'C';
if(initial == 'c' || initial == 'C') {
//...
}- In neither language can you (or should you) use the
==sign for other than numerical/orcharvalues. - Ie: you cannot use
==to compare strings in EITHER language
String a = "hello";
String b = "goodbye";
String c = "hello";
if(a == c) {
//this will never be true
}- In both languages,
==compares memory addresses not the contents - In both languages, you need to use a function (or method) to make such a comparison
- In Java:
-
a.equals(b)(returnstrueif the contents ofaandbare the same) -
a.equalsIgnoreCase(b)(this disregards differences in upper/lower case) -
a.compareTo(b): returns anintvalue that represents which string comes first (in ASCII/lexicographic order) - It is a comparator pattern: it returns
- if
$a < b$ then it returns something negative - if
$a = b$ then it returns zero - if
$a > b$ then it returns something positive
- if
-
- In C:
-
strcmp(a, b)is also a comparator pattern - It is included in the string libarary,
#include <string.h> - Revisit this when we look at strings
-
Write a program that reads a decibel level from the user (using command line arguments) and gives the user a description of the sound level.
* 0 - 60 Quiet
* 61 - 70 Conversational
* 71 - 90 Loud
* 91 - 110 Very Loud
* 111 - 129 Dangerous
* 130 - 194 Very Dangerous
* < 0 or 195+