Table of Contents

    if Statement

    if Statement
    Figure: if Statement

    DECISION CONTROL STATEMENTS

    if Statement

    The if statement is used to execute a block of code only when a specific condition is TRUE. It is the most basic and important decision control statement in programming — enabling programs to make choices and respond intelligently to different conditions.

    What is an if Statement?

    The if statement is a decision control structure that allows a program to make decisions. It checks a given condition, and if the condition is TRUE, the statements inside the if block are executed. Otherwise, they are skipped.

    It is the foundation of conditional logic in programming and forms the base for more complex constructs like if-else, if-else if-else, and nested decisions.

    Key Idea: The if statement is the most basic decision control structure. It allows a program to execute specific code only when a condition is TRUE — making programs logical and intelligent.

    Real-Life Analogy

    An if statement is like deciding whether to carry an umbrella. IF it's raining, then take the umbrella. If not, no action is needed. This exact logic is how the if statement works in programming.

    Key Features of if Statement

    The if statement has several important features that make it essential for writing conditional code.

    1

    Evaluates a Condition

    Checks logical expression

    The if statement evaluates a condition or logical expression. The result is either TRUE or FALSE.

    2

    Executes Code Only if TRUE

    Conditional execution

    If the condition evaluates to TRUE, the code inside the if block is executed.

    3

    Skips Code if FALSE

    No action taken

    If the condition evaluates to FALSE, the code inside the if block is skipped and program continues with the next statement.

    4

    Controls Program Flow

    Branches execution

    The if statement controls the flow of execution by branching the program based on conditions.

    5

    Simple and Easy to Use

    Beginner-friendly

    The if statement is easy to write and understand, making it a natural starting point for learning decision-making in programming.

    Syntax (General Form)

    The general syntax of the if statement is the same across most programming languages, with slight variations in punctuation.

    if (condition) {
        // Statements to execute
        // if condition is TRUE
    }

    If the condition is TRUE, the statements inside the block { } are executed. If the condition is FALSE, the block is skipped.

    SYNTAX RULE
    if ( condition ) { statements }

    Flowchart Representation

    The flowchart of an if statement uses a diamond (decision) symbol to check the condition and directs the flow based on the result.

    Start
       ↓
    Is Condition TRUE?
       ├── Yes → Execute Statements
       └── No  → Skip (Do Nothing)
       ↓
    Stop
    Explanation The flow enters the diamond and checks the condition. If Yes (TRUE), it executes the statements. If No (FALSE), it skips them.

    Working of if Statement

    The if statement works in a simple three-step process:

    1

    Condition is Checked

    Evaluation phase

    The program evaluates the condition inside the parentheses of the if statement.

    2

    If TRUE — Execute Statements

    Execution phase

    If the condition evaluates to TRUE, the statements inside the if block are executed.

    3

    If FALSE — Skip and Continue

    Skip phase

    If the condition evaluates to FALSE, the control skips the block and moves to the next statement in the program.

    Simple Example If age >= 18, then print "You are eligible to vote".

    Code Examples in Different Languages

    Let's write the same "voting eligibility check" program in three popular programming languages using the if statement.

    Example in C

    #include <stdio.h>
    
    int main() {
        int age;
        printf("Enter your age: ");
        scanf("%d", &age);
    
        if (age >= 18) {
            printf("You are eligible to vote.\n");
        }
        return 0;
    }

    Example in Java

    import java.util.*;
    
    public class IfExample {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter your age: ");
            int age = sc.nextInt();
    
            if (age >= 18) {
                System.out.println("You are eligible to vote.");
            }
        }
    }

    Example in Python

    age = int(input("Enter your age: "))
    
    if age >= 18:
        print("You are eligible to vote.")
    Output If the user enters 20, the output will be: "You are eligible to vote."
    If the user enters 15, nothing is printed (block is skipped).

    Condition Results

    The behavior of the if statement depends entirely on the evaluation of its condition.

    Condition Result Action
    TRUE (Yes) Condition is satisfied Execute statements inside the if block
    FALSE (No) Condition is not satisfied Skip the if block and move to next statement

    Common Comparison Operators

    The if statement uses comparison operators to evaluate conditions. These operators return either TRUE or FALSE.

    Operator Meaning Example
    == Equal to a == b
    != Not equal to a != b
    > Greater than a > b
    < Less than a < b
    >= Greater than or equal to a >= b
    <= Less than or equal to a <= b

    Logical Operators with if

    Multiple conditions in an if statement can be combined using logical operators.

    Operator Meaning Example
    && (AND) Both conditions must be TRUE (age >= 18 && age <= 60)
    || (OR) At least one condition must be TRUE (marks >= 90 || attendance == 100)
    ! (NOT) Reverses the condition !(isLoggedIn)

    Real-Life Example — Traffic Signal System

    The traffic signal system is a great real-life example that uses multiple if statements to determine the driver's action.

    if (light == "RED") {
        printf("Stop the vehicle");
    }
    if (light == "YELLOW") {
        printf("Get Ready");
    }
    if (light == "GREEN") {
        printf("Go");
    }
    Explanation Each if statement checks the current signal color and prints the appropriate action.

    More Practical Examples

    Example 1: Check if a Number is Positive

    if (num > 0) {
        printf("The number is positive");
    }

    Example 2: Check Passing Marks

    if (marks >= 40) {
        printf("You have passed the exam");
    }

    Example 3: Check Discount Eligibility

    if (purchaseAmount >= 1000) {
        printf("You get a 10%% discount!");
    }

    Example 4: Login Validation

    if (password == "admin123") {
        printf("Login Successful");
    }

    Example 5: Check Adult Eligibility

    if age >= 18 and age <= 60:
        print("You are an adult")

    Advantages of if Statement

    Advantages

    • Simple and easy to understand
    • Enables conditional execution
    • Foundation of decision-making in programming
    • Works with all data types and expressions
    • Supported in every programming language
    • Can be combined with logical operators
    • Enables validation and error checking

    Limitations

    • Only handles the TRUE case (use if-else for both)
    • Multiple ifs can become hard to read
    • Too many nested ifs reduce code clarity
    • Not efficient for multiple discrete cases (use switch)
    • Can lead to bugs if conditions are not tested well

    Tips for Using if Statement

    Best Practices

    • Write clear and simple conditions.
    • Always use correct comparison operators (e.g., == for equality, not =).
    • Indent code properly for readability.
    • Do not forget the semicolon (;) after statements in C and Java.
    • Test both TRUE and FALSE cases while debugging.
    • Use meaningful variable names to improve code readability.
    • Avoid comparing floating-point numbers directly using ==.
    • Use curly braces { } even for single statements — it prevents bugs.
    • Combine multiple conditions using logical operators for cleaner code.
    • Refactor multiple if statements into if-else if chains when they are related.

    Common Mistakes to Avoid

    Mistake 1: Using = instead of ==

    • Wrong: if (a = 5)
    • Correct: if (a == 5)
    • Note: = assigns, == compares

    Mistake 2: Missing Braces

    • Can cause unintended behavior
    • Always use { }
    • Prevents future bugs

    Mistake 3: Semicolon After if

    • Wrong: if (x > 0);
    • This creates an empty statement
    • Correct: if (x > 0) { ... }

    Mistake 4: Incorrect Indentation

    • Hard to read code
    • Can cause logic errors
    • Use consistent indentation

    Did You Know?

    Interesting Fact

    The concept of decision making (if statement) is the foundation of Artificial Intelligence, Automation, and Smart Systems. Every intelligent decision — from ATM PIN verification to self-driving cars — begins with the humble if statement.

    Frequently Asked Questions

    Q1. What is an if statement?

    An if statement is a decision control structure that executes a block of code only when a specified condition is TRUE.

    Q2. What happens when the condition is FALSE?

    When the condition is FALSE, the code inside the if block is skipped and the program continues with the next statement.

    Q3. Can I write multiple if statements?

    Yes, you can write multiple if statements, each checking its own condition independently.

    Q4. What is the difference between = and == in an if statement?

    = is used for assignment, while == is used for comparison. In an if statement, always use ==.

    Q5. Can I use if without curly braces?

    Yes, if the block contains only one statement. However, using curly braces is always recommended for clarity and future maintenance.

    Q6. Can I combine multiple conditions in an if statement?

    Yes, you can combine multiple conditions using logical operators like && (AND), || (OR), and ! (NOT).

    Key Takeaways

    • The if statement executes code only if a condition is TRUE.
    • If the condition is FALSE, the block is skipped.
    • It is the most basic decision control structure.
    • Uses comparison and logical operators.
    • Can be used in any programming language.
    • Forms the base of if-else, else-if, and nested decisions.
    • Essential for validation, input checking, and program logic.
    • Practice and clarity are the keys to mastering if statements.

    Key Takeaway

    The if statement is the most basic decision control structure. It allows a program to execute specific code only when a condition is TRUE — making programs logical and intelligent. Mastering the if statement is the first step toward becoming a strong programmer.

    Best of Luck! Practice more examples, think logically, and build strong programming skills!

    Flowchart = Visual Thinking → Smart Solutions → Better Results! 🚀