CS 111 - 3/4/14 If Statements - Selection Statements The program will select whether or not to execute a block of code If-then statement - If the given condition is true then we execute a block of code otherwise we do nothing. Syntax: if ( ) { ; } Example: absolute value int x = 52; if ( x < 0 ) { x = -x; } If-then-else statement - we have two bodies of code. The then-body and the else-body. If the condition is true the then-body gets executed if the condition is false the else-body gets executed Syntax if ( ) { ; } else { ; } Example: place the larger of the values in variable x and y into the variable z int x, y, z; x = 5; y = 10; if ( x > y ) { z = x; } else { z = y; } If the bodies only have a single statement, the curly braces are not needed: int x, y, z; x = 5; y = 1; if ( x > y ) z = x; else { z = y; w = 0; } We can select from any number of choices by using multiple if statements together This approach is often called "nested if" statements or "else-if" statements Syntax: if ( ) { ; } else if ( ) { ; } else if ( ) { ; } else if ( ) { ; } else if ( ) { ; } else if ( ) { ; } Example: Assigning letter grades double overallPercent; char letter; if ( overallPercent >= 90.0 ) letter = 'A'; else if ( overallPercent >= 80.0 ) letter = 'B'; else if ( overallPercent >= 70.0 ) letter = 'C'; else if ( overallPercent >= 60.0 ) letter = 'D'; else letter = 'F';