5. The IF Statement Flashcards
control structures: a computer can proceed
- in a sequence
- selectively (branch) - making a choice
- repetitively (iteratively) - looping
If-Else statement
allows you to do diff things depending on a condition
condition
an expression whose value is true or false
symbols for conditions
> < == != >= <= !> etc
note on ==
cannot use = for conditions, as = is used for assigning
combining else and if
if ..
else if…
else ..
logical (boolean) expressions)
data type bool has logical values true and false
bool, true, false
reserved words
identifier true
has the value 1
identifier false
has the value 0
regional operators
allow comparisons
req 2 operands
return 1 if expresion true, 0 otherwise
comparing diff data types
unpredictable results produced
regional operators
== != < <= > >=
logical (boolean) operators
enable you to combine logical expressions
logical operators list
! (not)
&& (and)
|| (or)
putting !
putting ! in front of a logical expression reverses its value
eg of using logical operators
(x > 0 && x <= 50)
cannot write this:
0 < x <= 50)
precedence of operators
evaluated left to right
parentheses can override precedence
short-circuit evaluation
evaluation of logical expression stops when value of expression known
- if first part of && false, whole lot is false
- if first part of || true, whole lot is true
{ } and if statements
only use { } if you need to group together multiple statements within the if statement. Don’t use if there is only 1 statement in a branch
IF syntax
- condition must be in ()
- no ; after the condition
- can leave out ELSE if not needed
the keyword CONST
useful for values that are used multiple times in the program
using CONST
instead of if (temp > 37) ... use if (temp > NORMAL_TEMP), with NORMAL_TEMP being assigned to be 37 at the start
as it is more readable, otherwise significance of 37 not clear. Also makes it easier to change later on if you wanted to, for example, change it to 38
Notes on constants
common practice to name constants with all capitals
eg. PI, NORMAL_TEMP, TAXRATE, PRSI
Using const example
const double NORMAL_TEMP = 37;