C Programming

Lecture 10: Switch-Case Logic, Break, Continue, and Goto
Dr. Mohsin Dar | Assistant Professor Cloud & Software Operations Cluster | SOCS | UPES
BTech First Semester | C Programming Course

1. Switch-Case Statement

The switch-case statement is a multi-way decision-making construct that allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Key Benefits of Switch-Case:

  • More readable than multiple if-else statements
  • More efficient for multiple conditions
  • Easy to maintain and debug
  • Better performance for large number of conditions

Syntax

switch (expression) {
    case constant1:
        // statements
        break;
    
    case constant2:
        // statements
        break;
    
    case constant3:
        // statements
        break;
    
    default:
        // default statements
        break;
}

Switch-Case Flow

Expression Evaluated
Match with Cases
Execute Case Block
Break/Continue

Example: Simple Calculator

#include <stdio.h>

int main() {
    char operator;
    float num1, num2, result;
    
    printf("Enter operator (+, -, *, /): ");
    scanf("%c", &operator);
    
    printf("Enter two numbers: ");
    scanf("%f %f", &num1, &num2);
    
    switch (operator) {
        case '+':
            result = num1 + num2;
            printf("%.2f + %.2f = %.2f", num1, num2, result);
            break;
            
        case '-':
            result = num1 - num2;
            printf("%.2f - %.2f = %.2f", num1, num2, result);
            break;
            
        case '*':
            result = num1 * num2;
            printf("%.2f * %.2f = %.2f", num1, num2, result);
            break;
            
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
                printf("%.2f / %.2f = %.2f", num1, num2, result);
            } else {
                printf("Error: Division by zero!");
            }
            break;
            
        default:
            printf("Error: Invalid operator!");
            break;
    }
    
    return 0;
}

Fall-through Behavior

Important: If you omit the break statement, control "falls through" to the next case. This can be intentional or a bug!
// Example: Grade Classification
switch (grade) {
    case 'A':
    case 'B':
        printf("Excellent performance!");
        break;
        
    case 'C':
        printf("Good performance!");
        break;
        
    case 'D':
    case 'F':
        printf("Need improvement!");
        break;
        
    default:
        printf("Invalid grade!");
}

2. Break Statement

The break statement is used to terminate loops and switch statements. When encountered, it causes the program to exit the nearest enclosing loop or switch statement immediately.

Uses of Break Statement:

1. In Switch Statements

Prevents fall-through behavior

2. In Loops

Exits the loop prematurely

3. In Nested Loops

Exits only the innermost loop

Example: Breaking out of a Loop

#include <stdio.h>

int main() {
    int i;
    
    printf("Numbers from 1 to 10, but stop at 5:\n");
    
    for (i = 1; i <= 10; i++) {
        if (i == 5) {
            printf("Breaking at %d\n", i);
            break; // Exit the loop when i equals 5
        }
        printf("%d ", i);
    }
    
    printf("\nLoop terminated\n");
    return 0;
}

Break in Nested Loops

#include <stdio.h>

int main() {
    int i, j;
    
    for (i = 1; i <= 3; i++) {
        printf("Outer loop: %d\n", i);
        
        for (j = 1; j <= 5; j++) {
            if (j == 3) {
                printf("  Breaking inner loop at j=%d\n", j);
                break; // Only breaks inner loop
            }
            printf("  Inner loop: %d\n", j);
        }
    }
    
    return 0;
}

3. Continue Statement

The continue statement skips the rest of the current iteration and moves to the next iteration of the loop. Unlike break, it doesn't exit the loop entirely.

Key Differences: Break vs Continue

  • Break: Terminates the entire loop
  • Continue: Skips current iteration, continues with next

Example: Skipping Even Numbers

#include <stdio.h>

int main() {
    int i;
    
    printf("Odd numbers from 1 to 10:\n");
    
    for (i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue; // Skip even numbers
        }
        printf("%d ", i);
    }
    
    printf("\n");
    return 0;
}

Continue in While Loop

#include <stdio.h>

int main() {
    int i = 0;
    
    printf("Numbers divisible by 3 (1 to 15):\n");
    
    while (i < 15) {
        i++;
        
        if (i % 3 != 0) {
            continue; // Skip numbers not divisible by 3
        }
        
        printf("%d ", i);
    }
    
    printf("\n");
    return 0;
}

Comparison Table

Aspect Break Statement Continue Statement
Purpose Terminates the entire loop Skips current iteration only
Control Flow Exits loop completely Jumps to next iteration
Usage in Switch Yes - prevents fall-through No - not applicable
Nested Loops Affects innermost loop only Affects innermost loop only

4. Goto Statement

The goto statement provides an unconditional jump from the goto statement to a labeled statement within the same function. It transfers control directly to the specified label.

Warning: The goto statement is generally discouraged in modern programming as it can make code difficult to read and maintain. It can lead to "spaghetti code" - code with complex and tangled control flow.

Syntax

goto label;
// ... other statements ...
label:
    // statements to execute

Example: Basic Goto Usage

#include <stdio.h>

int main() {
    int num;
    
    start: // Label
        printf("Enter a positive number: ");
        scanf("%d", &num);
        
        if (num <= 0) {
            printf("Invalid input! Please try again.\n");
            goto start; // Jump back to label
        }
        
        printf("You entered: %d\n", num);
        return 0;
}

Better Alternative without Goto

#include <stdio.h>

int main() {
    int num;
    
    do {
        printf("Enter a positive number: ");
        scanf("%d", &num);
        
        if (num <= 0) {
            printf("Invalid input! Please try again.\n");
        }
    } while (num <= 0);
    
    printf("You entered: %d\n", num);
    return 0;
}

When Goto Might Be Acceptable

Limited Use Cases:

  • Breaking out of deeply nested loops
  • Error handling in system programming
  • Cleanup code in functions with multiple exit points
  • State machine implementations

Example: Breaking from Nested Loops

#include <stdio.h>

int main() {
    int i, j, found = 0;
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int target = 5;
    
    // Using goto to break from nested loops
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            if (matrix[i][j] == target) {
                printf("Found %d at position [%d][%d]\n", target, i, j);
                goto found_target;
            }
        }
    }
    
    printf("Target not found\n");
    
    found_target:
        printf("Search completed\n");
        return 0;
}

Why Avoid Goto?

  • Readability: Makes code flow difficult to follow
  • Maintainability: Hard to debug and modify
  • Structure: Breaks structured programming principles
  • Alternatives: Modern control structures are more elegant

5. Practical Examples and Best Practices

Example 1: Menu-Driven Program

#include <stdio.h>

int main() {
    int choice;
    float radius, area, circumference;
    
    do {
        printf("\n=== CIRCLE CALCULATOR ===\n");
        printf("1. Calculate Area\n");
        printf("2. Calculate Circumference\n");
        printf("3. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                printf("Enter radius: ");
                scanf("%f", &radius);
                area = 3.14159 * radius * radius;
                printf("Area = %.2f\n", area);
                break;
                
            case 2:
                printf("Enter radius: ");
                scanf("%f", &radius);
                circumference = 2 * 3.14159 * radius;
                printf("Circumference = %.2f\n", circumference);
                break;
                
            case 3:
                printf("Goodbye!\n");
                break;
                
            default:
                printf("Invalid choice! Please try again.\n");
                break;
        }
    } while (choice != 3);
    
    return 0;
}

Example 2: Number Pattern with Continue

#include <stdio.h>

int main() {
                    int i, j;
    
    printf("Pattern (skipping multiples of 3):\n");
    
    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= 10; j++) {
            if (j % 3 == 0) {
                continue; // Skip multiples of 3
            }
            printf("%2d ", j);
        }
        printf("\n");
        
        if (i == 3) {
            printf("Breaking after row 3\n");
            break; // Exit outer loop
        }
    }
    
    return 0;
}

🎯 Programming Exercises

Try these exercises to practice the concepts:

Best Practices Summary

✅ Do:

  • Always use break in switch cases (unless intentional fall-through)
  • Use continue to skip iterations cleanly
  • Prefer structured control flow over goto
  • Include default case in switch statements
  • Use meaningful variable names and comments

❌ Avoid:

  • Using goto unless absolutely necessary
  • Missing break statements in switch (unintentional fall-through)
  • Complex nested control structures
  • Infinite loops without proper exit conditions

6. Summary and Key Takeaways

Switch-Case

  • Multi-way decision making
  • More efficient than multiple if-else
  • Requires break to prevent fall-through
  • Always include default case

Break Statement

  • Terminates loops and switch statements
  • Exits only the innermost structure
  • Essential in switch statements
  • Useful for early loop termination

Continue Statement

  • Skips current iteration
  • Continues with next iteration
  • Only works in loops
  • Cleaner than nested if-else

Goto Statement

  • Unconditional jump to label
  • Generally discouraged
  • Can create spaghetti code
  • Use structured alternatives

Control Flow Decision Tree

Need Multi-way Decision?
Use Switch-Case
Need Early Exit?
Use Break/Continue

Next Lecture Preview

Coming Up in Lecture 11:

  • Functions in C Programming
  • Function Declaration and Definition
  • Parameter Passing Techniques
  • Local vs Global Variables
  • Recursion Concepts