If Statement

The if statement allows your program to make decisions and execute different blocks of code based on certain conditions.

Think of an if statement like a traffic light for your code. Just as you stop at a red light and go on green, your program can execute different instructions based on whether a condition is true or false.

Basic Syntax

if (condition) {
    // Code to execute if condition is true
}

The condition inside the parentheses must evaluate to either true (non-zero) or false (zero).

Simple Example

#include <stdio.h>

int main() {
    int age = 18;
    
    if (age >= 18) {
        printf("You are eligible to vote!\n");
    }
    
    return 0;
}

In this example, since age is 18 and 18 >= 18 is true, the message will be printed.

Common Comparison Operators

OperatorDescriptionExample
==Equal tox == 5
!=Not equal tox != 5
>Greater thanx > 5
<Less thanx < 5
>=Greater than or equalx >= 5
<=Less than or equalx <= 5

Logical Operators

You can combine multiple conditions using logical operators:

#include <stdio.h>

int main() {
    int age = 25;
    int hasLicense = 1; // 1 means true, 0 means false
    
    if (age >= 18 && hasLicense) {
        printf("You can drive!\n");
    }
    
    if (age < 13 || age > 65) {
        printf("Special discount available!\n");
    }
    
    return 0;
}

Important Notes

  • Braces: While braces {} are optional for single statements, it's good practice to always use them for clarity
  • Indentation: Proper indentation makes your code more readable
  • Condition: The condition must be enclosed in parentheses
  • Zero is False: In C, 0 is considered false, and any non-zero value is considered true