Lesson 14: Conditional Logic: The if Statement
Decision-making structures allow a program to execute different blocks of code based on conditions.
Basic if Statement
The if statement executes a block of code only if the specified condition is true (non-zero).
Syntax: c if (condition) { // Statements executed if the condition is TRUE } // Execution continues here regardless
Example
c int score = 85;
if (score >= 90) { printf("Excellent grade!\n"); }
score = 92; if (score >= 90) { printf("Congratulations!\n"); }
Omitting Braces
If the if statement body contains only one single statement, the curly braces ({}) can be omitted. However, using braces is highly recommended for clarity and preventing bugs when adding future statements.
c int is_logged_in = 1; if (is_logged_in) printf("User is active.\n"); // Single statement, no braces needed
The Condition Check
Remember that C treats 0 as False and any non-zero value as True.
c int error_code = 0; // Success if (error_code) { // This block will NOT execute because error_code is 0 (False) }
int flag = 100; if (flag) { // This block WILL execute because flag is non-zero (True) }