CSC115 C Programming

C ProgrammingUnit 513 min read

Control Statements in C – if‑else, switch, loops, break & continue

Unit 5 of C Programming: this note explains all selection, jump and looping statements, their syntax, flow of control, worked traces, comparison tables, common pitfalls and how they are examined in TU/PU/NEB papers.

Key points

  • Selection statements (if‑else, switch) decide which block of code executes based on conditions.
  • Jump statements (break, continue, goto, return) alter the normal sequential flow inside loops or functions.
  • Looping statements (while, do‑while, for) repeat a block of code; each has a distinct use‑case and termination condition.
  • Break terminates the nearest enclosing loop or switch, while continue skips the remaining statements of the current iteration.
  • Common syntax errors (missing semicolons, mismatched parentheses, incorrect scanf format) cause compilation failures and must be checked carefully.

1. Introduction to Control Statements

Control statements are the building blocks of program logic. They enable a C program to make decisions, repeat actions, and jump out of the normal sequential execution path. The three families covered in this unit are:

Family Purpose Typical Keywords
Selection Choose one among many alternatives if, else, else if, switch
Jump Transfer control abruptly break, continue, goto, return
Looping (Iteration) Repeat a block of statements while, do … while, for

Understanding the flow diagram of each statement is essential for writing correct and efficient code.


2. Selection Statements

2.1 if Statement

Syntax

if (condition) {
    /* statements executed when condition is true */
}
  • condition must be an expression that evaluates to an integer (0 = false, non‑zero = true).
  • If the condition is false, the block is skipped.

Worked Example

int x = 7;
if (x % 2)               // true because 7%2 = 1 (non‑zero)
    printf("Odd\n");

Trace: x % 2 → 1 → true → prints “Odd”.

2.2 if‑else Statement

Syntax

if (condition) {
    /* true‑branch */
} else {
    /* false‑branch */
}

Only one of the two blocks executes.

Example

int age = 20;
if (age >= 18)
    printf("Adult\n");
else
    printf("Minor\n");

Trace: age >= 18 → true → prints “Adult”.

2.3 Nested if and else if Ladder

When more than two mutually exclusive cases are needed, we chain else if.

Syntax

if (cond1) {
    /* block1 */
} else if (cond2) {
    /* block2 */
} else if (cond3) {
    /* block3 */
} else {
    /* default block */
}

Example – Grade Calculator

int marks = 85;
if (marks >= 90)
    printf("A\n");
else if (marks >= 80)
    printf("B\n");
else if (marks >= 70)
    printf("C\n");
else
    printf("D or F\n");

Trace: marks >= 90 false → marks >= 80 true → prints “B”.

2.4 switch Statement

Used when a single variable is compared against many constant integral values.

Syntax

switch (expression) {
    case const1:
        /* statements */
        break;
    case const2:
        /* statements */
        break;
    /* … */
    default:
        /* statements */
}
  • break is crucial; without it, execution “falls through” to the next case.
  • default is optional but recommended for unexpected values.

Example – Day of Week

int day = 3;
switch (day) {
    case 1: printf("Monday\n");    break;
    case 2: printf("Tuesday\n");   break;
    case 3: printf("Wednesday\n"); break;
    default: printf("Invalid\n");
}

Trace: day matches case 3 → prints “Wednesday” → break exits the switch.

2.5 Comparison: if‑else vs switch

Feature if‑else switch
Condition type Any relational expression (>, <, ==, &&, etc.) Integral constant expression only
Number of cases Unlimited, each can be a different expression Limited to discrete constant values
Readability Better for range checks (e.g., x > 10 && x < 20) Cleaner for equality checks against many constants
Performance Compiled to a series of conditional jumps Often compiled to a jump table → faster for many cases
Fall‑through Not possible (each block is separate) Possible if break omitted (useful in some algorithms)

When to prefer: Use if‑else for range or complex logical tests; use switch when testing a single variable against many constant values.


3. Jump Statements

Jump statements interrupt the normal flow and transfer control to another point in the program.

3.1 break

  • Terminates the nearest enclosing for, while, do‑while, or switch.
  • Control passes to the statement immediately after the terminated block.

Example – Searching in an Array

int a[] = {5, 12, 7, 9, 3};
int target = 7, i, found = 0;
for (i = 0; i < 5; ++i) {
    if (a[i] == target) {
        found = 1;
        break;          // exit loop as soon as we find the element
    }
}
if (found) printf("Found at index %d\n", i);

Trace: Loop iterates i=0 (5), i=1 (12), i=2 (7) → condition true → break → exits loop, prints index 2.

3.2 continue

  • Skips the remaining statements in the current iteration and proceeds with the next iteration of the loop.
  • Does not exit the loop; only the current cycle is aborted.

Example – Print only odd numbers

for (int i = 1; i <= 10; ++i) {
    if (i % 2 == 0)
        continue;          // skip even numbers
    printf("%d ", i);
}

Output: 1 3 5 7 9

3.3 goto

  • Transfers control to a labeled statement anywhere in the same function.
  • Generally discouraged because it makes code hard to read and maintain, but occasionally used for error‑handling cleanup.

Syntax

goto label;
...
label:   /* target */
    /* statements */

Example – Simple error handling

int readFile(const char *name) {
    FILE *fp = fopen(name, "r");
    if (!fp) goto error;
    /* normal processing */
    fclose(fp);
    return 0;
error:
    printf("Cannot open file\n");
    return -1;
}

3.4 return

  • Ends the execution of the current function and optionally returns a value to the caller.
  • In main, return 0; signals successful program termination.

Example

int max(int a, int b) {
    if (a > b) return a;
    return b;
}

3.5 Prime‑Number Program Using break

#include <stdio.h>
int main(void) {
    int n, i, isPrime = 1;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    if (n < 2) isPrime = 0;               // 0 and 1 are not prime
    else {
        for (i = 2; i * i <= n; ++i) {
            if (n % i == 0) {
                isPrime = 0;
                break;                    // no need to check further
            }
        }
    }
    if (isPrime) printf("%d is prime\n", n);
    else        printf("%d is not prime\n", n);
    return 0;
}

Trace: For n = 29, loop runs i = 2,3,4,5 (since 5*5 ≤ 29). No divisor found → break never executed → isPrime stays 1 → prints prime.

3.6 Break vs Continue – Quick Comparison

Aspect break continue
Effect on loop Terminates the loop entirely Skips to the next iteration
Typical use Early exit when condition satisfied (search, validation) Skip unwanted iteration (filtering)
Scope Affects the innermost loop or switch only Affects only the innermost loop
Interaction with switch Used to exit a case block Not applicable inside switch

4. Looping (Iteration) Statements

4.1 while Loop

Syntax

while (condition) {
    /* body */
}
  • Condition is evaluated before each iteration.
  • If the condition is false initially, the body may never execute.

Example – Sum of first n natural numbers

int n, i = 1, sum = 0;
printf("Enter n: ");
scanf("%d", &n);
while (i <= n) {
    sum += i;
    ++i;
}
printf("Sum = %d\n", sum);

Trace: For n = 4, iterations add 1,2,3,4 → sum = 10.

4.2 do … while Loop

Syntax

do {
    /* body */
} while (condition);
  • Body executes at least once because condition is checked after the first execution.

Example – Menu driven program (single execution guarantee)

int choice;
do {
    printf("1. Add  2. Sub  3. Exit\n");
    scanf("%d", &choice);
    switch (choice) {
        case 1: printf("Add selected\n"); break;
        case 2: printf("Sub selected\n"); break;
    }
} while (choice != 3);

Trace: If user enters 3 immediately, the menu still appears once before exiting.

4.3 for Loop

Syntax

for (initialization; condition; increment) {
    /* body */
}
  • Compact form that combines initialization, test, and update in one line.
  • Ideal when the number of iterations is known beforehand.

Example – Print a multiplication table (1‑10)

for (int i = 1; i <= 10; ++i) {
    for (int j = 1; j <= 10; ++j)
        printf("%4d", i * j);
    printf("\n");
}

Trace: Outer loop runs 10 times; inner loop prints 10 products per line.

4.4 Choosing the Right Loop

Loop When to use
while Unknown number of iterations, condition may be false initially.
do … while Must execute at least once (e.g., menu, input validation).
for Fixed or easily calculable iteration count; loop variable needed outside body.

4.5 Nested Loops and Flow Control

Nested loops are common for matrix operations, pattern printing, etc. break and continue affect only the innermost loop unless labeled (C does not support labeled break; you must use flags or goto).

Example – Find first pair (i, j) such that i*j = 30

int i, j;
int found = 0;
for (i = 1; i <= 10 && !found; ++i) {
    for (j = 1; j <= 10; ++j) {
        if (i * j == 30) {
            printf("Pair: %d, %d\n", i, j);
            found = 1;
            break;          // exits inner loop only
        }
    }
}

The outer loop condition && !found prevents further iterations once a pair is located.


5. Common Errors and Debugging

5.1 Syntax Errors in the Given Snippet

int main(){
    int a,b,c scanf("%d%d%d, &a, &b, &c

Identified problems

  1. Missing semicolon after variable declaration.
  2. scanf call lacks a closing parenthesis and closing double‑quote.
  3. The format string is malformed: it opens with " but never closes, and the commas are misplaced.
  4. The address‑of operators (&) are placed inside the string literal due to the missing quote.

Corrected version

int main(void) {
    int a, b, c;
    printf("Enter three integers: ");
    scanf("%d %d %d", &a, &b, &c);   // spaces separate inputs; format string closed
    /* optional: use the values */
    printf("You entered: %d %d %d\n", a, b, c);
    return 0;
}

5.2 Logical Mistakes Frequently Seen

Mistake Symptom Fix
Using assignment (=) instead of equality (==) in a condition Condition always true (or false) → unexpected flow Replace = with ==
Forgetting break in a switch case “Fall‑through” causing multiple case bodies to run Add break; or intentional fall‑through comment
Placing continue inside a while loop without updating the loop variable Infinite loop Ensure loop variable is modified before continue or move update after continue
Using scanf without checking return value Undetected input failure → garbage values if (scanf("%d", &x) != 1) { /* handle error */ }

6. Formal Argument vs Actual Argument (Brief Note)

  • Formal argument (parameter): The variable name appearing in a function definition. It acts as a placeholder for the value that will be supplied when the function is called. Example: int max(int a, int b) – a and b are formal arguments.
  • Actual argument (argument): The real value or expression supplied at the call site. Example: max(5, x+2) – 5 and x+2 are actual arguments.

Understanding this distinction helps when tracing function calls that involve control statements (e.g., passing a flag that decides whether a loop should execute).


7. Advantages, Disadvantages, and Typical Applications

Construct Advantages Disadvantages / Caveats Typical Applications
if‑else / else if Flexible conditions, easy to read for few branches Long ladders become hard to maintain Input validation, range checks
switch Fast dispatch via jump table, clear when testing a single variable Limited to integral/enum constants, accidental fall‑through Menu handling, state machines
break Immediate exit, reduces nested ifs Overuse can hide loop termination logic Search termination, early error abort
continue Skips unwanted iteration without extra flags May lead to confusing loop flow if overused Filtering data, ignoring sentinel values
while Simple pre‑test loop, works when iteration count unknown Body may never run Reading until EOF, waiting for a condition
do‑while Guarantees at least one execution May cause unintended first run if condition already false User‑prompt loops, menu display
for Compact, ideal for counted loops, easy to read iteration variable Less natural for condition‑driven loops Array traversal, generating sequences
goto Simple error‑cleanup jump (rare) Makes code spaghetti, hard to debug Deeply nested error handling in legacy code

8. Exam Tip

  • Memorise the exact syntax of each statement, especially the placement of parentheses, braces, and the break keyword inside switch.
  • Practice tracing: Write down the values of loop counters and condition results for at least two iterations of every loop type. Many TU/PU questions ask you to show the output of a given fragment.
  • Common pitfalls: Forgetting break in switch, using = instead of ==, missing semicolons after scanf, and not handling the case where a while condition is false initially. Highlight these in your answer to earn extra marks.
  • Past paper pattern: Questions often combine concepts, e.g., “Write a program that uses a for loop and a break to find the first prime number greater than 100.” Prepare a template that you can adapt quickly.
  • Answer structure: When a question asks to differentiate two statements, use a comparison table (as shown above). For error‑identification tasks, list each error, explain why it is wrong, and provide the corrected line. This systematic approach demonstrates clear understanding and scores full marks.

Based on the TU BSc CSIT syllabus for C Programming (CSC115), unit 5.

Discussion

Loading…