Lesson 3 Progress
0%
Lesson 3  ·  Conditionals

if, else if, else

Make your programs smart — execute different code depending on conditions. Real programs make hundreds of decisions every second.

Syntax & Operators
if / else
else if chains
Nested if
switch-case
📖

What Are Conditionals?

A conditional tells the program: "If this is true — do this. Otherwise — do something else." Every decision in a program is a conditional. Without them, programs would do the same thing every time regardless of input.

  • if — runs a block when condition is true
  • else if — checks another condition if the previous was false
  • else — runs when nothing above matched
  • switch — cleaner way to match one variable against many exact values
OperatorMeaningExampleResult
==Equal toage == 18true if age is 18
!=Not equalscore != 0true if score is not 0
>Greater thantemp > 100true if temp exceeds 100
<Less thanprice < 500true if price is under 500
>=Greater or equalmarks >= 35true if marks is 35 or above
&&AND — both trueage>=18 && id==1both must be true
||OR — either trueday==6 || day==7either condition works
!NOT — reverses!foundtrue if found is false
⚠️ = is assignment. == is comparison.
if (x = 5) sets x to 5 — always true — silent bug!
if (x == 5) checks if x equals 5 — correct!
example 1
1

Exam Pass or Fail

simple if / else

The simplest conditional — two outcomes. If marks are 50 or above the student passes, otherwise they fail. Uses a single if / else with one comparison operator.

Example 1 · exam_result.c
exam_result.c
C
#include <stdio.h>

int main() {
    int marks;

    printf("Enter your marks (0-100): ");
    scanf("%d", &marks);

    if (marks >= 50) {
        printf("Result: PASS ✓\n");
        printf("Congratulations!\n");
    } else {
        printf("Result: FAIL ✗\n");
        printf("Please study harder.\n");
    }

    return 0;
}
terminal — two runs
output
Enter your marks: 72
Result: PASS ✓
Congratulations!

Enter your marks: 38
Result: FAIL ✗
Please study harder.
💡 Both branches run the same printf — only the message changes. This is the power of conditionals — same code structure, different behaviour based on data.
example 2
2

Grade Calculator — A, B, C, D, F

else if chain

Five outcomes instead of two. C checks conditions top to bottom and stops at the first true one. This is why we check the highest value first — if marks >= 90 is checked before >= 80, so 95 correctly gets an A, not a B.

Example 2 · grade_calc.c
grade_calc.c
C
#include <stdio.h>

int main() {
    int marks;

    printf("Enter marks (0-100): ");
    scanf("%d", &marks);

    if      (marks >= 90) printf("Grade: A — Excellent!\n");
    else if (marks >= 80) printf("Grade: B — Very Good\n");
    else if (marks >= 70) printf("Grade: C — Good\n");
    else if (marks >= 50) printf("Grade: D — Pass\n");
    else if (marks >= 0)  printf("Grade: F — Fail\n");
    else                   printf("Invalid marks!\n");

    return 0;
}
terminal
output
Enter marks: 95  →  Grade: A — Excellent!
Enter marks: 83  →  Grade: B — Very Good
Enter marks: 71  →  Grade: C — Good
Enter marks: 55  →  Grade: D — Pass
Enter marks: 30  →  Grade: F — Fail
Enter marks: -5  →  Invalid marks!
example 3
3

Electricity Bill Calculator

real world slab system

A real-world use case — electricity bills use slab pricing. First 100 units at one rate, next 200 at another, beyond 300 at a higher rate. This shows how conditionals solve practical problems with different rates for different ranges.

Example 3 · electricity_bill.c
electricity_bill.c
C
#include <stdio.h>

int main() {
    int   units;
    float bill = 0;

    printf("Enter units consumed: ");
    scanf("%d", &units);

    if (units <= 100) {
        bill = units * 2.50;          // Rs 2.50 per unit
    } else if (units <= 300) {
        bill = (100 * 2.50)           // first 100 units
             + (units - 100) * 4.00; // next units at 4.00
    } else {
        bill = (100 * 2.50)           // first 100 units
             + (200 * 4.00)           // next 200 units
             + (units - 300) * 6.00; // beyond 300 at 6.00
    }

    printf("\n--- ELECTRICITY BILL ---\n");
    printf("Units used : %d\n",      units);
    printf("Amount Due : Rs %.2f\n", bill);

    return 0;
}
terminal — three different inputs
output
Units: 80  →  Amount Due : Rs 200.00   (80 × 2.50)
Units: 200 →  Amount Due : Rs 650.00   (100×2.50 + 100×4.00)
Units: 400 →  Amount Due : Rs 1850.00  (100×2.50 + 200×4.00 + 100×6.00)
example 4
4

Login System — Nested if

if inside an if

Nested if means placing an if statement inside another if. The inner if only runs if the outer if is already true. This is perfect for multi-step checks — like first verifying username, then verifying password.

Example 4 · login_check.c
login_check.c
C
#include <stdio.h>
#include <string.h>

int main() {
    char username[30], password[30];

    printf("Enter username: ");
    scanf("%s", username);

    printf("Enter password: ");
    scanf("%s", password);

    // Outer if: check username first
    if (strcmp(username, "admin") == 0) {

        // Inner if: only reached if username is correct
        if (strcmp(password, "1234") == 0) {
            printf("✓ Login successful! Welcome, admin.\n");
        } else {
            printf("✗ Wrong password.\n");
        }

    } else {
        printf("✗ Username not found.\n");
    }

    return 0;
}
terminal — three scenarios
output
username: admin  password: 1234  →  ✓ Login successful!
username: admin  password: 9999  →  ✗ Wrong password.
username: guest  password: 1234  →  ✗ Username not found.
💡 strcmp returns 0 when strings are equal. Never use username == "admin" — that compares memory addresses, not string content. Always use strcmp() from string.h.
example 5
5

Simple Menu with switch-case

switch statement

When checking one variable against many exact values, switch is cleaner than a long if-else chain. Each case handles one value. Always end with break to prevent fall-through. The default catches anything not matched.

Example 5 · atm_menu.c
atm_menu.c
C
#include <stdio.h>

int main() {
    int   choice;
    float balance = 5000.00;

    printf("=== ATM MENU ===\n");
    printf("1. Check Balance\n");
    printf("2. Deposit\n");
    printf("3. Withdraw\n");
    printf("4. Exit\n");
    printf("Enter choice: ");
    scanf("%d", &choice);

    switch (choice) {

        case 1:
            printf("Balance: Rs %.2f\n", balance);
            break;

        case 2: {
            float amount;
            printf("Enter deposit amount: ");
            scanf("%f", &amount);
            balance += amount;
            printf("New balance: Rs %.2f\n", balance);
            break;
        }

        case 3: {
            float amount;
            printf("Enter withdraw amount: ");
            scanf("%f", &amount);
            if (amount <= balance) {
                balance -= amount;
                printf("Dispensing Rs %.2f\n", amount);
            } else {
                printf("Insufficient funds!\n");
            }
            break;
        }

        case 4:
            printf("Thank you. Goodbye!\n");
            break;

        default:
            printf("Invalid option!\n");
    }

    return 0;
}
terminal — choice 1 and 3
output
Choice 1: Balance: Rs 5000.00
Choice 3: Enter withdraw: 1500  →  Dispensing Rs 1500.00
Choice 3: Enter withdraw: 9000  →  Insufficient funds!
Choice 9: Invalid option!
quiz
Q

Quick Quiz

Question 1 of 4

In an if / else if / else chain with marks = 85 and conditions (>=90), (>=80), (>=70) — which runs?

Question 2 of 4

What happens if you write if (x = 10) instead of if (x == 10)?

Question 3 of 4

What does forgetting break in a switch case cause?

Question 4 of 4

To check if two strings are equal in C you should use:

Lesson Checklist

  • I know all comparison operators ==, !=, >, <, >=, <=
  • I know && (AND), || (OR), ! (NOT) logical operators
  • I understand = (assign) vs == (compare) — the most common bug
  • I can write a simple if / else program (pass/fail)
  • I can write an else if chain (grade calculator)
  • I understand C checks conditions top-to-bottom, first true wins
  • I can write nested if — an if inside another if
  • I can write a switch-case with break and default
  • I use strcmp() to compare strings, not ==
  • I completed the quiz