LEARN MATE Request book Contact us quizes Books Home
if...else statement
Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. An if statement looks as follows: if (condition) { // block of code to be executed if the condition is true } condition can be any expression that evaluates to true or false. See Boolean for an explanation of what evaluates to true and false. If condition evaluates to true, statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You may also compound the statements using else if to have multiple conditions tested in sequence, as follows:

if (20 > 18) { printf("20 is greater than 18"); } In the case of multiple conditions only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ ... }) . In general, it's good practice to always use block statements, especially when nesting if statements: if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code: int time = 20; if (time < 18) { printf("Good day."); } else { printf("Good evening."); } // Outputs "Good evening." If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example: int x = 20; int y = 18; if (x > y) { printf("x is greater than y"); }