This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: if statements
Basic form: if( condition ) statement;
statement is executed i condition is true Example:
if( 2 < 5 ) ssprintf(Surprise! 2 is less than 5\n); statement can also be multiple lines of code surrounded by braces, e.g.
if( 2 < 5 ) { ssprintf(Surprise! 2 is less than 5\n); ssprintf(What a shock!); } ifelse statements
if(cond) statement1 else statement2;
statement1 is executed i condition is true statement2 is executed i condition is false Example:
if( a < 5 ) ssprintf(a < 5\n); else { ssif( a < 8 ) ssssprintf(a < 8\n); sselse ssprintf(a >= 8\n); } if( a < 5 ) ssprintf(a < 5\n); else if( a < 8 ) ssprintf(a < 8\n); else ssprintf(a >= 8\n); = ifelse statement pitfall
What does this code do?
if( a > 70 ) ssif( a < 80 ) ssssprintf(grade = C); else ssprintf(grade < C); ssprintf(Fail.\n); printf(done.); if( a > 70 )
{ = ssif( a < 80 ) ssssprintf(grade = C); sselse ssssprintf(grade < C);
} printf(Fail.\n); printf(done.); ifelse statement pitfall
What does this code do?
if( a > 70 ) if( a > 70 ) ssif( a < 80 ) ssssprintf(grade = C); else ssprintf(grade < C); ssprintf(Fail.\n); printf(done.);
{ ssif( a < 80 ) ssssprintf(grade = C);
} = else
{ ssprintf(grade < C); ssprintf(Fail.\n);
} printf(done.); Relational Operators
C has the following relational operators: a == b True i a equals b a != b True i a does not equal b a < b True i a is less than b a > b True i a is greater than b a <= b True i a is less than or equal to b a >= b True i a is greater than or equal to b a && b True i a is true and b is true a  b True i at least one of a or b is true !a True i a is false Booleans in C
C does not have a boolean type Instead, conditional operators evaluate to integers
0 if false, 1 if true if(condition) checks whether condition is nonzero This makes possible some programming tricks: int a; /* some code */ if(!a) ssprintf(a is zero!); s int a,b; /* some code */ b = ((b * 3) / 5) * !(a < 0); = ...
View
Full Document
 '08
 CRANDALL
 Equals sign, relational operator

Click to edit the document details