1_pdfsam_lecture2 - if statements Basic form: if( condition...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the 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!); } if-else 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); = if-else 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.); if-else 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 non-zero 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

This note was uploaded on 01/10/2010 for the course CS 2022 at Cornell University (Engineering School).

Page1 / 6

1_pdfsam_lecture2 - if statements Basic form: if( condition...

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