CSci 125 Lecture 10 Martin van Bommel. Simple Statements Expression followed by semicolon...

Post on 27-Dec-2015

213 views 0 download

Transcript of CSci 125 Lecture 10 Martin van Bommel. Simple Statements Expression followed by semicolon...

CSci 125

Lecture 10

Martin van Bommel

Simple Statements

• Expression followed by semicolon

• Assignments

total = n1 + n2;• Function calls

printf(”Hello.\n”);• Useless statements

n1 + n2;

Embedded Assignments

• Assignment expression can be used as part of a larger expression in a statement

• Its value is the value assigned

z = (x = 6) + y;• x is assigned value 6, then z assigned 6 + y• Difficult to read• Used rarely and only when makes sense

Multiple Assignments

• Embedded assignments useful to set several variables to the same value

n1 = n2 = n3 = 0;• Assignment operator evaluated right to left

• Avoid mixed types; e.g. double d and int i

d = i = 1.5;• Assigns i value 1, thus 1 assigned to d

Statement Blocks

• Sequence of statements that specify a coherent unit enclosed in curly braces

• E.g. if, for, while statement bodies

{

statement1

statement2

. . .

}

Boolean Data

• Conditionals test expressions whose values are either TRUE or FALSE

• George Boole - developed algebra for T/F

• Standard C has no Boolean type

• We use the integer 0 for FALSE and the integer 1 for TRUE

Relational Operators

• Compare two atomic values (not strings)

• Precedence after +/-

> Greater than < Less than

>= Greater or equal <= Less or equal

• Next level of precedence

== Equal != Not equal

Logical Operators

• Operate on other Boolean values (in order of precedence)

! Not (TRUE if operand FALSE)

&& And (TRUE if both TRUE)

|| Or (TRUE if either TRUE)

Example 1

• “x is not equal to either 2 or 3”

if (x != 2 || x != 3)• No, it should be

if (!(x == 2 || x == 3))• or

if (x != 2 && x != 3)

Example 2

• “x is in the range from 0 to 10 exclusive”

if (0 < x < 10)• No, it should be

if (0 < x && x < 10)

Short-Circuit Evaluation

• Evaluating

exp1 && exp2 or

exp1 || exp2

evaluates expressions from left to right

• If answer known before both evaluated, second expression not evaluated

(x != 0) && (y % x == 0)

Flags

• Variables used for testing truth values

int done;• Assign value to indicate state of flag

done = 0;

or

done = 1;

Setting Flags

• To set a flag on a condition, could useif (input == -1) {

done = 1;} else {

done = 0;}

• Better to simply use

done = (input == -1);

Testing a Flag

• To test whether done has value TRUE, could use

if (done == 1)• Better to simply use

if (done)• Test for truth value 1 is redundant

Boolean Example

• Leap year every fourth year, except centuries, then just every fourth century– year is divisible by 4 but not by 100, or– year is divisible by 400

• Try((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)