Chapter 6: Decision Making and Branching

📌 Learning Objectives
  • LO 6.1: Understand decision making with if statements
  • LO 6.2: Work with if-else and nested if statements
  • LO 6.3: Use the switch statement for multi-way branching
  • LO 6.4: Apply the conditional operator (?:)
  • LO 6.5: Understand the goto statement and its implications

6.1 Introduction to Decision Making

C language possesses decision-making capabilities that allow the program to change the order of execution of statements based on certain conditions. The decision-making statements in C are:

                    ┌─────────────────┐
                    │    Condition    │
                    └────────┬────────┘
                             │
                 ┌───────────┴───────────┐
                 │                       │
              True/Non-zero           False/Zero
                 │                       │
                 ↓                       ↓
          ┌───────────────┐       ┌───────────────┐
          │  Statement    │       │  Statement    │
          │   Block 1     │       │   Block 2     │
          └───────┬───────┘       └───────┬───────┘
                  └───────────┬───────────┘
                              ↓
                    ┌─────────────────┐
                    │ Statement next  │
                    │   to if-else    │
                    └─────────────────┘

Fig. 6.1: Two-way branching with if-else

6.2 The if Statement

The simplest form of decision control:

if (test expression)
{
    statement-block;
}
statement-x;

📝 Worked-Out Problem 6.1

Simple if statement - Calculating ratio:

#include <stdio.h>

int main() {
    float a, b, c, ratio;
    printf("Enter three numbers: ");
    scanf("%f %f %f", &a, &b, &c);
    
    if ((c - d) != 0) {
        ratio = a / (c - d);
        printf("Ratio = %f\n", ratio);
    }
    
    return 0;
}
Output (if c=10, d=5):
Ratio = 2.000000
Output (if c=5, d=5):
(No output - division skipped)

6.3 The if-else Statement

if (test expression)
{
    true-block;
}
else
{
    false-block;
}
statement-x;

📝 Worked-Out Problem 6.2

Counting boys and girls using if-else:

#include <stdio.h>

int main() {
    int code, boys = 0, girls = 0;
    
    printf("Enter code (1 for boy, 2 for girl): ");
    scanf("%d", &code);
    
    if (code == 1)
        boys++;
    else if (code == 2)
        girls++;
    else
        printf("Invalid code!\n");
    
    printf("Boys: %d, Girls: %d\n", boys, girls);
    return 0;
}
Output:
Enter code (1 for boy, 2 for girl): 1
Boys: 1, Girls: 0

6.4 Nested if-else Statements

if (condition1)
{
    if (condition2)
        statement1;
    else
        statement2;
}
else
{
    statement3;
}
statement-x;

📝 Worked-Out Problem 6.3

Selecting the largest of three numbers:

#include <stdio.h>

int main() {
    int a, b, c, max;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    
    if (a > b) {
        if (a > c)
            max = a;
        else
            max = c;
    }
    else {
        if (b > c)
            max = b;
        else
            max = c;
    }
    
    printf("Largest = %d\n", max);
    return 0;
}
Output:
Enter three numbers: 45 78 23
Largest = 78
⚠️ Dangling Else Problem:

An else is always associated with the most recent unmatched if in the same block. Always use braces to avoid ambiguity.

// Ambiguous
if (x > 0)
    if (y > 0)
        printf("Both positive");
else
    printf("x is not positive");  // This else belongs to inner if!

// Correct
if (x > 0) {
    if (y > 0)
        printf("Both positive");
}
else
    printf("x is not positive");

6.5 The else-if Ladder

if (condition1)
    statement1;
else if (condition2)
    statement2;
else if (condition3)
    statement3;
...
else
    default-statement;
statement-x;

📝 Worked-Out Problem 6.4

Grading students based on marks:

#include <stdio.h>

int main() {
    int marks;
    char grade;
    
    printf("Enter marks (0-100): ");
    scanf("%d", &marks);
    
    if (marks >= 90)
        grade = 'O';  // Outstanding
    else if (marks >= 80)
        grade = 'E';  // Excellent
    else if (marks >= 70)
        grade = 'A';
    else if (marks >= 60)
        grade = 'B';
    else if (marks >= 50)
        grade = 'C';
    else if (marks >= 40)
        grade = 'D';
    else
        grade = 'F';  // Fail
    
    printf("Grade: %c\n", grade);
    return 0;
}
Output:
Enter marks (0-100): 85
Grade: E

6.6 The switch Statement

The switch statement is a multi-way decision statement that tests the value of an expression against a list of case values.

switch (expression)
{
    case value-1:
        block-1;
        break;
    case value-2:
        block-2;
        break;
    ...
    default:
        default-block;
}
📌 Rules for switch:
  • The expression must be an integer type (int, char, enum).
  • Case labels must be constants or constant expressions.
  • Case labels must be unique.
  • The break statement is optional but usually needed to exit the switch.
  • The default case is optional.

📝 Worked-Out Problem 6.5

Menu-driven program using switch:

#include <stdio.h>

int main() {
    int choice;
    float a, b, result;
    
    printf("1. Addition\n");
    printf("2. Subtraction\n");
    printf("3. Multiplication\n");
    printf("4. Division\n");
    printf("Enter your choice (1-4): ");
    scanf("%d", &choice);
    
    printf("Enter two numbers: ");
    scanf("%f %f", &a, &b);
    
    switch(choice) {
        case 1:
            result = a + b;
            printf("Sum = %.2f\n", result);
            break;
        case 2:
            result = a - b;
            printf("Difference = %.2f\n", result);
            break;
        case 3:
            result = a * b;
            printf("Product = %.2f\n", result);
            break;
        case 4:
            if (b != 0) {
                result = a / b;
                printf("Quotient = %.2f\n", result);
            }
            else
                printf("Division by zero error!\n");
            break;
        default:
            printf("Invalid choice!\n");
    }
    
    return 0;
}
Output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1-4): 3
Enter two numbers: 12 5
Product = 60.00

6.7 The Conditional Operator (?:)

The conditional operator is a ternary operator that provides a shorthand for if-else statements.

expression1 ? expression2 : expression3

If expression1 is true (non-zero), expression2 is evaluated and becomes the result; otherwise expression3 is evaluated.

📝 Worked-Out Problem 6.6

Finding maximum using conditional operator:

#include <stdio.h>

int main() {
    int a, b, max;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    
    max = (a > b) ? a : b;
    printf("Maximum = %d\n", max);
    
    // Even or odd check
    (a % 2 == 0) ? printf("%d is even\n", a) : printf("%d is odd\n", a);
    
    return 0;
}
Output:
Enter two numbers: 25 18
Maximum = 25
25 is odd

📝 Worked-Out Problem 6.7

Nested conditional operator for salary calculation:

#include <stdio.h>

int main() {
    int items;
    float salary;
    
    printf("Enter number of items sold: ");
    scanf("%d", &items);
    
    salary = (items != 40) ? ((items < 40) ? 4*items + 100 : 4.5*items + 150) : 300;
    
    printf("Salary = %.2f\n", salary);
    return 0;
}
Output:
Enter number of items sold: 45
Salary = 352.50

6.8 The goto Statement

The goto statement is used to branch unconditionally from one point to another in the program. It requires a label to identify the destination.

goto label;
...
label:
    statement;
⚠️ Avoid goto:

Use of goto is generally discouraged as it makes programs difficult to read and maintain. It can lead to "spaghetti code". However, it may be useful in some rare situations like breaking out of deeply nested loops.

📝 Worked-Out Problem 6.8

Using goto to create a simple loop (not recommended):

#include <stdio.h>

int main() {
    int i = 1, sum = 0;
    
    loop:
    sum += i;
    i++;
    if (i <= 10)
        goto loop;
    
    printf("Sum of 1 to 10 = %d\n", sum);
    return 0;
}
Output:
Sum of 1 to 10 = 55

6.9 De Morgan's Rule

De Morgan's rule helps simplify logical expressions with NOT operators:

!(x && y || !z)  becomes  !x || !y && z
!(x <= 0 || !condition)  becomes  x > 0 && condition
💡 Programming Tips:
  • Always use braces {} even for single statements in if-else blocks for clarity.
  • Avoid comparing floating-point numbers for equality due to precision errors.
  • In switch statements, don't forget the break unless you intentionally want fall-through.
  • Use the default case in switch to handle unexpected values.
  • The conditional operator is great for simple conditions but avoid nesting it deeply.

Chapter Exercises

Review Questions

  1. State true or false:
    a) A switch expression can be of any type.
    b) Each case label can have only one statement.
    c) The default case is required in the switch statement.
    d) When if statements are nested, the last else gets associated with the nearest if without an else.
    e) The expression !( (x >= 10) || (y == 5) ) is equivalent to (x < 10) && (y != 5).
  2. What is the output of the following code?
    int x = 5;
    if(x = 10)
        printf("TRUE");
    else
        printf("FALSE");
  3. Rewrite the following without using compound relations:
    if (grade <= 59 && grade >= 50)
        second++;

Multiple Choice Questions

  1. What will be the output of the following if-else statement?
    if(x=5)
        printf("Condition is true\n");
    else
        printf("Condition is false\n");

    a) String 'Condition is true' is printed.
    b) x is assigned 5 and 'Condition is true' is printed.
    c) String 'Condition is false' is printed.
    d) None of the above
  2. For the if-else construct:
    if(a>=5 && a<=10)
        printf("True");
    else
        printf("False");
    Which is correct?
    a) True if 5>=a>=10, false otherwise
    b) True if 5<=a<=10, false otherwise
    c) True if 5<=a>=10, false otherwise
    d) None
  3. What will be the output?
    main() {
        x=5;
        if(x==5);
            printf("Hello World");
        else
            printf("I am in else block");
    }

    a) Hello World
    b) I am in else block
    c) Nothing
    d) Compiler error

Debugging Exercises

Find errors, if any, in the following segments:

if (x + y = z && y > 0)
    printf("OK");

if (p < 0) || (q < 0)
    printf("Negative");

if (code > 1);
    a = b + c;
else
    a = 0;

if (x =< 10)
    printf("Welcome");

Programming Exercises

  1. Write a program to determine whether a given number is odd or even using:
    a) if without else
    b) if-else
  2. Write a program to find the number of integers greater than 100 and less than 200 that are divisible by 7.
  3. Write a program to compute the real roots of a quadratic equation. Handle cases where a=0, discriminant negative, etc.
  4. An electricity board charges: 80P per unit for first 200 units, 90P per unit for next 100 units, Rs. 1.00 beyond 300. All users pay minimum Rs. 100 meter charge. If total > Rs. 400, add 15% surcharge. Write a program to print charges.
  5. Write a program using switch to input a month number and display the number of days in that month.
  6. Write a program to input two numbers and display whether they are equal, first is greater, or second is greater.

Interview Questions

  1. What happens if the conditional expression is missing in an if statement?
  2. What could be the if expressions that always return true and false values?
  3. What types of values are permitted to be used with a switch statement?
  4. What will be the output of the following code?
    void main() {
        int a=5;
        if(a<0);
            printf("a is negative");
        else
            printf("a is positive");
    }

Case Study: Range of Numbers

📝 Case Study: Finding Range (Highest - Lowest)

#include <stdio.h>

int main() {
    int count = 0;
    float value, high, low, sum = 0, average, range;
    
    printf("Enter numbers (negative to stop):\n");
    scanf("%f", &value);
    high = low = value;
    
    while (value >= 0) {
        count++;
        sum += value;
        
        if (value > high)
            high = value;
        else if (value < low)
            low = value;
        
        scanf("%f", &value);
    }
    
    if (count > 0) {
        average = sum / count;
        range = high - low;
        printf("\nCount: %d\n", count);
        printf("Average: %.2f\n", average);
        printf("Highest: %.2f\n", high);
        printf("Lowest: %.2f\n", low);
        printf("Range: %.2f\n", range);
    }
    else
        printf("No data entered.\n");
    
    return 0;
}
Output:
Enter numbers (negative to stop):
45 67 23 89 12 -1
Count: 5
Average: 47.20
Highest: 89.00
Lowest: 12.00
Range: 77.00