ITM102 Structured Programming in C

Structured Programming in CUnit 29 min read

Control Structures & Syntax in C

Unit 2 of Structured Programming in C covers C’s core syntax rules, decision-making (if-else, switch), and loops (for, while, do-while), with visual traces, real-world applications, and exam-focused comparisons.

TAKEAWAYS:

  • Master if-else ladders, switch-case, and loop syntax to solve branching/logic problems.
  • Understand loop control (break, continue, goto) and their impact on program flow.
  • Trace variable changes step-by-step in loops/conditions to debug efficiently.
  • Apply control structures to real scenarios (e.g., eSewa’s transaction validation, Daraz’s order processing).
  • Avoid common pitfalls like infinite loops or dangling else in nested conditions.

1. Basic Syntax Rules in C

C enforces strict syntax for readability and compiler compatibility. Key rules:

  • Case sensitivity: int x; ≠ int X;.
  • Semicolons: Every statement ends with ;.
  • Braces {}: Required for blocks (e.g., loops, if bodies).
  • Comments:
    // Single-line comment
    /* Multi-line
       comment */
    

2. Decision-Making Statements

A. if-else Ladder

Syntax:

if (condition1) {
    // Code if true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Default code
}

Example: Validate a user’s eSewa PIN (3 attempts max).

int pin = 1234, attempts = 0;
while (attempts < 3) {
    int input;
    printf("Enter PIN: ");
    scanf("%d", &input);
    if (input == pin) {
        printf("Access granted!");
        break;
    } else {
        attempts++;
        printf("Wrong PIN. %d attempts left.\n", 3 - attempts);
    }
}

Trace Table:

Step input attempts Output
1 9999 1 "Wrong PIN. 2 attempts left."
2 5678 2 "Wrong PIN. 1 attempt left."
3 1234 2 "Access granted!"

Real-World Tie:

  • eSewa App: Uses nested if-else to check transaction limits, PIN validity, and bank balance before processing payments.

B. switch-case

Syntax:

switch (variable) {
    case value1: // Code; break;
    case value2: // Code; break;
    default:     // Default code
}

Example: Menu-driven program for a bank ATM.

int choice;
printf("1. Check Balance\n2. Withdraw\n3. Exit\n");
scanf("%d", &choice);
switch (choice) {
    case 1: printf("Balance: Rs. 5000\n"); break;
    case 2: printf("Enter amount: "); break;
    default: printf("Invalid choice.\n");
}

Visual Trace:

flowchart TD
    A["Start"] --> B["Input choice"]
    B --> C{"choice == 1"}
    C -->|"Yes"| D["Print Balance"]
    C -->|"No"| E{"choice == 2"}
    E -->|"Yes"| F["Prompt for amount"]
    E -->|"No"| G["Print 'Invalid'"]

Comparison Table:

Feature if-else switch-case
Use Case Complex conditions (e.g., ranges) Discrete values (e.g., menus)
Performance Slower for many conditions Faster for large case lists
Syntax Flexible (any expression) Requires break for each case

Real-World Tie:

  • Pathao Driver App: Uses switch-case to handle ride status updates (e.g., case 1: "Trip accepted", case 2: "Driver assigned").

3. Looping Constructs

A. for Loop

Syntax:

for (initialization; condition; increment) {
    // Loop body
}

Example: Calculate the total cost of a Daraz order with 5% discount if order > Rs. 2000.

float total = 0, price;
for (int i = 0; i < 3; i++) {
    printf("Enter item %d price: ", i+1);
    scanf("%f", &price);
    total += price;
}
if (total > 2000) total *= 0.95;
printf("Final total: Rs. %.2f\n", total);

Trace Table:

Step i price (input) total (accumulated)
1 0 800.00 800.00
2 1 1500.00 2300.00
3 2 300.00 2600.00 → 2470.00 (5% off)

B. while Loop

Syntax:

while (condition) {
    // Loop body
}

Example: Simulate a traffic light cycle (red: 30s, green: 20s, yellow: 5s).

int time = 0;
while (time < 55) {
    if (time < 30) printf("Red\n");
    else if (time < 50) printf("Green\n");
    else printf("Yellow\n");
    time++;
    delay(1000); // Simulate 1-second delay
}

Visual Trace:

flowchart LR
    A["Start"] --> B["time = 0"]
    B --> C{"time < 30"}
    C -->|"Yes"| D["Print 'Red'"]
    C -->|"No"| E{"time < 50"}
    E -->|"Yes"| F["Print 'Green'"]
    E -->|"No"| G["Print 'Yellow'"]
    D --> H["time++"]
    F --> H
    G --> I["End (time >= 55)"]
    H --> C

C. do-while Loop

Syntax:

do {
    // Loop body
} while (condition);

Example: Validate user input for a Ncell recharge PIN (must be 4 digits).

int pin;
do {
    printf("Enter 4-digit PIN: ");
    scanf("%d", &pin);
} while (pin < 1000 || pin > 9999);
printf("Valid PIN!\n");

Comparison Table:

Loop Type Execution Order Use Case Risk of Infinite Loop
for Pre-check Known iterations (e.g., arrays) High if increment is wrong
while Pre-check Unknown iterations (e.g., user input) High if condition never false
do-while Post-check At least one execution (e.g., menus) Low (runs once)

Real-World Tie:

  • NTC Traffic Management System: Uses while loops to monitor real-time vehicle counts at intersections and trigger signals based on congestion.

4. Loop Control Statements

Statement Purpose Example
break Exit loop immediately if (balance < 0) break;
continue Skip current iteration if (item == "out of stock") continue;
goto Jump to labeled line (rare) goto retry; (avoid overuse)

Example: Process a queue of Kathmandu traffic routes, skipping blocked roads.

char routes[] = {'A', 'B', 'C', 'D'};
for (int i = 0; i < 4; i++) {
    if (routes[i] == 'B') continue; // Road B is blocked
    printf("Take route %c\n", routes[i]);
}

Output:

Take route A
Take route C
Take route D

5. Nested Control Structures

Combine loops/conditions for complex logic. Example: Bank Loan Eligibility Check.

int income, age;
printf("Enter income (Rs.): ");
scanf("%d", &income);
printf("Enter age: ");
scanf("%d", &age);
if (income >= 50000) {
    if (age >= 21 && age <= 60) {
        printf("Loan approved!\n");
    } else {
        printf("Age not eligible.\n");
    }
} else {
    printf("Income too low.\n");
}

Visual Trace:

flowchart TD
    A["Start"] --> B["Check income >= 50000"]
    B -->|"No"| C["Print 'Income too low'"]
    B -->|"Yes"| D["Check age 21-60"]
    D -->|"No"| E["Print 'Age not eligible'"]
    D -->|"Yes"| F["Print 'Loan approved!'"]

In the Real World

  1. eSewa Transaction Validation:

    • Uses if-else ladders to check:
      • User login credentials (if (username == stored_user && password == stored_pass)).
      • Transaction amount (else if (amount > balance) { reject; }).
      • OTP verification (else if (otp == generated_otp) { process; }).
  2. Daraz Order Processing:

    • for loops iterate through cart items to calculate subtotal, tax, and shipping cost.
    • switch-case handles payment methods:
      switch (payment_method) {
          case 1: // Khalti
              verify_khalti_payment();
              break;
          case 2: // Credit Card
              verify_card_details();
              break;
      }
      
  3. Pathao Driver App:

    • while loops monitor GPS coordinates to update ride progress:
      while (distance_to_destination > 0.1) {
          update_location();
          distance_to_destination = calculate_distance();
      }
      

Exam Tip

  1. Syntax Precision:

    • Memorize the exact syntax for else-if ladders (no colon : in C!).
    • Example: ❌ else if (x > 10): → ✅ else if (x > 10) { ... }.
  2. Trace Tables:

    • For every loop/condition, create a table showing variable changes per iteration (as above). Examiners love step-by-step traces!
  3. Common Pitfalls:

    • Infinite Loops: Always ensure loop conditions can become false (e.g., i++ in for).
    • Dangling else: Use braces {} to avoid ambiguity in nested if-else.
      // Ambiguous without braces:
      if (x > 5)
          if (y > 10)
              printf("A");
          else
              printf("B"); // Does this else belong to x or y?
      
  4. Real-World Scenarios:

    • Link your answers to apps like eSewa (validation), Daraz (order processing), or NTC (traffic signals). Examiners reward contextual understanding.
  5. Code Structure:

    • Use meaningful variable names (e.g., max_attempts instead of x).
    • Indent blocks clearly to match logical hierarchy.

Practice Question: Write a program to simulate a Khalti payment gateway that:

  1. Asks for amount and merchant ID.
  2. Validates the merchant ID (must be 8 digits).
  3. Uses a do-while loop to re-prompt if invalid.
  4. Simulates payment success/failure with a random number (e.g., rand() % 2).

Solution Trace:

flowchart LR
    A["Start"] --> B["Input amount, merchant_id"]
    B --> C{"merchant_id is 8 digits?"}
    C -->|"No"| D["Print 'Invalid ID'"]
    D --> B
    C -->|"Yes"| E["Generate random success/failure"]
    E -->|"Success"| F["Print 'Payment done!'"]
    E -->|"Failure"| G["Print 'Payment failed'"]

Based on the TU BITM syllabus for Structured Programming in C (ITM102), unit 2.

Discussion

Loading…