06a-Expressions

06a-Expressions - < less than >=...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Arithmetic Expressions • Operations on numerical types • Operations: + “addition” - “subtraction” ultiplication” * “multiplication” / “division” (different for int vs. double ) % “remainder” • Precedence (in order): () highest * , / , % + , - lowest Operators in same precedence category evaluated left to right
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Type Casting • Treat one type as another for one operation int x = 3; double y; y = x / 2; // y = 1.0 y = (double)x / 2; y = 5.9; x = (int)y; x = 7; y = x; // fine: y = 7.0 x = y; // error // y = 1.5 // x = 5
Background image of page 2
Expression Short-hands int x = 3; x = x + 1; x += 1; x++; x = x + 5; x += 5; x = x – 1; x -= 1; x--; x = x * 3; x *= 3; x = x / 2; x /= 2;
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Boolean Expressions • Boolean expression is just a test for a condition • Essentially, evaluates to true or false • Value comparisons: == “equals” (note: not single = ) != “not equals” (cannot say <> ) > “greater than”
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: &lt; less than &gt;= greater than or equal to &lt;= less than or equal to More Boolean Expressions Boolean comparisons (in order of precedence): ! not !p if p is true, then !p is false, and vice versa &amp;&amp; and &amp;&amp; q nly true if d e both true p &amp;&amp; q only true if p and q are both true || or p || q true if p or q (or both) are true boolean p = (x != 1) || (x != 2); p is always true , you really want: boolean p = (x != 1) &amp;&amp; (x != 2); Short Circuit Evaluation Stop evaluating boolean expression as soon as we know the answer Consider: p = (5 &gt; 3) || (4 &lt;= 2); The test (4 &lt;= 2) is not performed! Example of useful case: p = (x != 0) &amp;&amp; ((y / x) == 0); Avoid division by 0, since ((y / x) == 0) is not performed...
View Full Document

This note was uploaded on 08/24/2011 for the course CS 106A taught by Professor Sahami,m during the Spring '08 term at Stanford.

Page1 / 6

06a-Expressions - &amp;amp;lt; less than &amp;amp;gt;=...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online