If-else

Comprehensive study notes, diagrams, and exam preparation for If-else.

If-else

Definition

if-else is a conditional control statement used to perform different actions depending on whether a specified condition evaluates to true or false.

In programming, a condition is an expression that compares values or checks a state, and it returns a Boolean result:

  • true if the condition is satisfied
  • false if the condition is not satisfied

The if part executes when the condition is true, while the else part executes when the condition is false.

General form:

if (condition)
    statement(s) for true case
else
    statement(s) for false case

Example:

if (marks >= 40)
    printf("Pass");
else
    printf("Fail");

Here, if marks is 40 or more, the program prints Pass; otherwise, it prints Fail.


Main Content

1. First Concept: if Statement

  • The if statement is the simplest decision-making structure in programming.
  • It checks a condition and executes a block of code only when that condition is true.

The if statement is used when you want to perform an action under a specific condition, but you do not necessarily need an alternative action. It is like saying: “If this happens, do something.” If the condition is false, the program skips the block and continues with the next instruction.

Syntax:

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

Example:

int age = 18;
if (age >= 18)
{
    printf("You are eligible to vote.");
}

Explanation:

  • The condition age >= 18 is true because age is 18.
  • Therefore, the message is displayed.

Important points:

  • The condition must evaluate to a Boolean-like result.
  • In many languages, non-zero values may be treated as true.
  • The block can contain one statement or multiple statements.
  • Braces {} improve readability and prevent errors.

Use case examples:

  • Checking whether a number is positive
  • Displaying a message only if a file exists
  • Allowing access only if a password is correct

ASCII visual flow:

     Start
       |
   Check condition
     /     \
  True     False
   |         |
 Execute   Skip block
 block       |
       \     /
        Next step

2. Second Concept: if-else Statement

  • The if-else statement provides two possible paths: one for true and one for false.
  • It is used when a program must choose between two alternative actions.

This structure is more powerful than a simple if because it guarantees that one of the two blocks will run. It helps programs respond appropriately in both cases. For example, a user can either be shown “Access granted” or “Access denied” depending on the result of a login check.

Syntax:

if (condition)
{
    // true block
}
else
{
    // false block
}

Example:

int number = 7;

if (number % 2 == 0)
{
    printf("Even number");
}
else
{
    printf("Odd number");
}

Explanation:

  • If the remainder when dividing by 2 is 0, the number is even.
  • Otherwise, it is odd.

Important points:

  • Exactly one block runs: either the if block or the else block.
  • The else block does not have a condition.
  • It improves clarity when two outcomes are possible.

Practical uses:

  • Checking pass/fail results
  • Determining whether a user is eligible for a discount
  • Showing different messages based on status

Example in real life:

  • If it is raining, take an umbrella; otherwise, do not take one.

ASCII visual flow:

            Condition
           /         \
       True           False
        |               |
   Run if block     Run else block
        \               /
                 End

3. Third Concept: else if Ladder and Nested if-else

  • else if is used when there are multiple conditions to check one after another.
  • Nested if-else means placing one if-else inside another if or else block.

These concepts are extensions of basic if-else and are very important when a program needs more than two outcomes. For example, grading systems, menu selections, and classification problems often require multiple conditions.

else if Ladder

This is used when several conditions are checked in sequence. The first true condition is executed, and the rest are ignored.

Example:

int marks = 76;

if (marks >= 90)
{
    printf("Grade A");
}
else if (marks >= 75)
{
    printf("Grade B");
}
else if (marks >= 60)
{
    printf("Grade C");
}
else
{
    printf("Grade D");
}

Explanation:

  • The program checks conditions from top to bottom.
  • The first condition that becomes true determines the output.
  • If none are true, the final else runs.

Nested if-else

A nested if-else is when one decision structure is placed inside another.

Example:

int age = 20;
int hasID = 1;

if (age >= 18)
{
    if (hasID == 1)
    {
        printf("Entry allowed");
    }
    else
    {
        printf("ID required");
    }
}
else
{
    printf("Not allowed due to age");
}

Explanation:

  • First, age is checked.
  • If age is valid, then the ID check is performed.
  • This is useful when one condition depends on another.

Important points:

  • else if is ideal for multiple exclusive conditions.
  • Nested if-else is ideal for hierarchical or dependent decisions.
  • Overuse of nesting can reduce readability, so indentation is important.

Common examples:

  • Student grading
  • Traffic signal handling
  • Choosing shipping charges based on location and weight
  • Checking both permission and availability

Working / Process

1. The program evaluates the condition

  • The expression inside the if is tested first.
  • This expression usually compares values using operators such as ==, !=, >, <, >=, <=.
  • Logical operators like &&, ||, and ! may also be used.

2. The condition produces a result

  • If the result is true, the program enters the if block.
  • If the result is false, the program moves to the else block if present.
  • In an else if ladder, the program continues checking until it finds a true condition.

3. The selected block executes and the program continues

  • Only the chosen block runs.
  • After execution, the program moves to the next statement after the entire if-else structure.
  • This ensures controlled, organized decision-making.

Example workflow for a simple if-else:

Input value
    |
Check condition
    |
  True? ---- Yes ---> Execute if block
    |
   No
    |
Execute else block
    |
Continue program

Example:

int temperature = 35;

if (temperature > 30)
{
    printf("Hot day");
}
else
{
    printf("Normal day");
}
printf("Done");

Process:

  • The condition temperature > 30 is checked.
  • Since it is true, Hot day is printed.
  • Then Done is printed after the decision block finishes.

Advantages / Applications

Makes programs decision-oriented

  • if-else allows a program to react differently in different situations instead of following one fixed path.
  • This is essential for interactive programs and real-world logic.

Improves flexibility and user interaction

  • Programs can respond to user input, sensor values, or changing data.
  • Examples include login validation, age verification, and menu selection.

Widely used in almost every programming problem

  • if-else appears in simple scripts and large-scale applications.
  • It is used in grading systems, validation checks, game logic, and business rules.

Other important applications:

  • Input validation
  • Error handling
  • Comparing values
  • Classifying data
  • Controlling loops and program flow
  • Implementing business rules such as discounts, taxes, and eligibility

Example application:

if (balance >= withdrawal_amount)
{
    printf("Transaction approved");
}
else
{
    printf("Insufficient balance");
}

This is used in banking systems to verify whether a withdrawal can proceed.


Summary

  • if-else is a decision-making statement used to choose between actions based on conditions.
  • It helps programs run different code paths depending on whether a condition is true or false.
  • It is a basic but powerful concept used in nearly all programming languages.
  • Important terms to remember: condition, Boolean, if, else, else if, nested if-else