4 Control Structures

C Programming ยท Unit 4

Control Structures

Exam-focused notes for Control Structures (C Programming, BIT102): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.

Control Structures in short

Control structures decide which statements run and how many times. They let a program make choices and follow different paths based on data.

Control Structures: notes

If else statement

The if statement runs a block only when a condition is true. The optional else block runs when it is false.

if (marks >= 40)
    printf("Pass\n");
else
    printf("Fail\n");

The condition is any expression. A value of zero means false, and any other value means true. Use braces when a branch has more than one statement.

If else ladder

An if else ladder checks several conditions one after another. The first true condition runs, and the rest are skipped. The final else handles the case where none is true.

if (marks >= 80)
    printf("Distinction\n");
else if (marks >= 60)
    printf("First division\n");
else if (marks >= 40)
    printf("Pass\n");
else
    printf("Fail\n");

Order matters. Put the most specific or highest condition first.

Nested if else

A nested if is an if statement placed inside another if or else block. It is used when a second decision depends on the first.

if (a >= b) {
    if (a >= c)
        printf("%d is largest\n", a);
    else
        printf("%d is largest\n", c);
} else {
    if (b >= c)
        printf("%d is largest\n", b);
    else
        printf("%d is largest\n", c);
}

An else always pairs with the nearest unmatched if. This is called the dangling else rule. Braces make the pairing clear.

What this unit covers

  • If else statement
  • If else ladder
  • Nested if else
  • Switch case statement
  • Comparison of switch and if else ladder
  • Break and continue statements
  • Goto statement and labels
  • Flowchart design

If else ladder

2081 ยท 5 marks

Explain if else ladder with syntax and semantic. Write a program to find largest among 3 different numbers. [2+3]

--- - The conditions are evaluated from top to bottom, one by one. - As soon as a condition evaluates to true, the corresponding block of statements is executed, and the rest of the ladder is skipped. - If none of the conditions is true, the final else block (default block) is executed. - It is u...

Open this answer on its own page โ†’

Switch case statement

2080 ยท 10 marks

Explain different control structures in C. Write a program in C to perform different arithmetic operations on two integers and display the result based on choice made by user using switch statement.[10]

Show solved answer

Control Structures in C and Switch-Based Arithmetic Calculator


Part 1: Control Structures in C

Control structures determine the flow of execution of a program. C provides three main categories:


1. Sequential Structure

Statements are executed one after another in the order they appear. This is the default flow.

Statement 1 โ†’ Statement 2 โ†’ Statement 3

2. Selection (Decision) Structures

Used to choose between alternative paths based on a condition.

a) if Statement

if (condition) {
    // executes if condition is true
}

b) if-else Statement

if (condition) {
    // executes if true
} else {
    // executes if false
}

c) if-else if-else (Ladder)

if (condition1) { ... }
else if (condition2) { ... }
else { ... }

d) switch Statement

Used when a variable is compared against multiple constant values.

switch (expression) {
    case value1: // statements; break;
    case value2: // statements; break;
    default:     // statements;
}

3. Iteration (Loop) Structures

Used to repeat a block of statements.

a) for Loop

for (initialization; condition; update) {
    // body
}

b) while Loop

while (condition) {
    // body
}

c) do-while Loop

do {
    // body
} while (condition);

Executes the body at least once before checking the condition.


4. Jump Structures

Used to transfer control unconditionally.

StatementPurpose
breakExits the nearest loop or switch
continueSkips the current iteration
gotoJumps to a labeled statement
returnExits a function

Part 2: C Program Using Switch for Arithmetic Operations

#include <stdio.h>

int main() {
    int a, b, choice;
    float result;

    // Input two integers
    printf("Enter first integer: ");
    scanf("%d", &a);

    printf("Enter second integer: ");
    scanf("%d", &b);

    // Display menu
    printf("\n--- Arithmetic Operations Menu ---\n");
    printf("1. Addition\n");
    printf("2. Subtraction\n");
    printf("3. Multiplication\n");
    printf("4. Division\n");
    printf("5. Modulus\n");
    printf("Enter your choice (1-5): ");
    scanf("%d", &choice);

    // Switch statement for operation selection
    switch (choice) {
        case 1:
            result = a + b;
            printf("Result: %d + %d = %.2f\n", a, b, result);
            break;

        case 2:
            result = a - b;
            printf("Result: %d - %d = %.2f\n", a, b, result);
            break;

        case 3:
            result = a * b;
            printf("Result: %d * %d = %.2f\n", a, b, result);
            break;

        case 4:
            if (b == 0) {
                printf("Error: Division by zero is not allowed.\n");
            } else {
                result = (float)a / b;
                printf("Result: %d / %d = %.2f\n", a, b, result);
            }
            break;

        case 5:
            if (b == 0) {
                printf("Error: Modulus by zero is not allowed.\n");
            } else {
                printf("Result: %d %% %d = %d\n", a, b, a % b);
            }
            break;

        default:
            printf("Invalid choice! Please enter a number between 1 and 5.\n");
    }

    return 0;
}

Sample Output

Enter first integer: 10
Enter second integer: 3

--- Arithmetic Operations Menu ---
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
Enter your choice (1-5): 4

Result: 10 / 3 = 3.33

Key Points About the Switch Statement Used

FeatureDescription
switch(choice)Evaluates the integer variable choice
case n:Matches a specific constant value
breakPrevents fall-through to the next case
defaultHandles any value not matched by a case
Division checkGuards against division/modulus by zero
Open this answer on its own page โ†’

Nested if else

2080 ยท 5 marks

Explain nested if else ladder with suitable example. [5]

A nested if-else ladder (also called if-else-if ladder) is a control structure where multiple conditions are checked in sequence. Each else branch contains another if condition, forming a chain (ladder) of conditions. The program checks each condition from top to bottom and executes the block of ...

Open this answer on its own page โ†’

Flowchart design

2079 ยท 5 marks

What do you mean by flowchart? Draw a Flowchart to find the largest among three numbers entered by user. [5]

Show solved answer

Flowchart

Definition

A flowchart is a diagrammatic or pictorial representation of an algorithm or a step-by-step solution to a given problem. It uses standard geometric symbols connected by arrows (flow lines) to show the sequence of steps, decisions, and operations required to solve a problem.

Common Flowchart Symbols

SymbolShapePurpose
TerminalOval / Rounded RectangleStart / Stop
Input/OutputParallelogramRead / Print data
ProcessRectangleArithmetic / Assignment operations
DecisionDiamondYes/No or True/False condition
Flow LinesArrowsDirection of flow

Flowchart to Find the Largest Among Three Numbers

Problem: Read three numbers A, B, and C from the user and find the largest among them.

        +----------+
        |  START   |
        +----------+
             |
             v
   +------------------+
   |  Read A, B, C    |
   +------------------+
             |
             v
       +------------+
       |   Is A > B? |
       +------------+
       /             \
     YES              NO
      |                |
      v                v
  +--------+       +--------+
  |Is A > C?|      |Is B > C?|
  +--------+       +--------+
  /        \       /        \
YES         NO   YES         NO
 |           |    |           |
 v           v    v           v
+---+      +---+ +---+      +---+
| A |      | C | | B |      | C |
|is |      |is | |is |      |is |
|Lar|      |Lar| |Lar|      |Lar|
|gest      |gest |gest      |gest
+---+      +---+ +---+      +---+
  \           \    /           /
   \           \  /           /
    \           \/           /
     \     +----------+     /
      \    |  Print   |    /
       +-->| Largest  |<--+
           +----------+
                |
                v
           +--------+
           |  STOP  |
           +--------+

Clean Step-by-Step Logic

START
  |
  Read A, B, C
  |
  Is A > B?
  โ”œโ”€โ”€ YES --> Is A > C?
  โ”‚           โ”œโ”€โ”€ YES --> Print "A is Largest"
  โ”‚           โ””โ”€โ”€ NO  --> Print "C is Largest"
  |
  โ””โ”€โ”€ NO  --> Is B > C?
              โ”œโ”€โ”€ YES --> Print "B is Largest"
              โ””โ”€โ”€ NO  --> Print "C is Largest"
  |
STOP

Example Trace

ABCA > B?Next CheckResult
1058YESA > C? (10>8) YESA = 10 is Largest
396NOB > C? (9>6) YESB = 9 is Largest
4611NOB > C? (6>11) NOC = 11 is Largest
Open this answer on its own page โ†’

2081.2 ยท 5 marks

Write an algorithm and flowchart to test whether the given integer is odd or even. [5]

--- Problem: Given an integer N, determine whether it is odd or even. Step 1: START Step 2: Read the integer N Step 3: Check if N MOD 2 = 0 (i.e., divide N by 2 and check the remainder) Step 4: If the remainder is 0, then print "N is Even" Step 5: Else print "N is Odd" Step 6: STOP --- --- Step D...

Open this answer on its own page โ†’

Break and continue statements

2078 ยท 5 marks

How break statement is different from continue statement. Explain with examples? [5]

The break statement is used to immediately terminate the loop (or switch) in which it appears. When break is executed, the program control jumps to the first statement after the loop. Output: The loop stops completely when i == 5. --- The continue statement is used to skip the current iteration o...

Open this answer on its own page โ†’

2077 ยท 5 marks

How break statement is different from continue statement? Explain with suitable example. [5]

Feature break continue --------- Purpose Terminates the entire loop immediately Skips only the current iteration Control flow Exits the loop body completely Goes back to the loop condition check Remaining iterations All remaining iterations are skipped Remaining iterations still execute Used in L...

Open this answer on its own page โ†’

Comparison of switch and if else ladder

2081.2 ยท 5 marks

Differentiate between switch statement and if else if ladder. [5]

A series of if, else if, and else blocks used to test multiple conditions sequentially. Syntax: --- A multi-way branching statement that tests a variable against a list of constant values (cases). Syntax: --- Feature Switch Statement If-Else-If Ladder --------- Condition Type Tests a single varia...

Open this answer on its own page โ†’

0 ยท 5 marks

Differentiate between switch case and else .. if ladder. Why is break statement used inside switch case? Explain briefly. [5]

Feature Switch Case Else-If Ladder --------- Basis of comparison Tests a single variable/expression against multiple constant values Tests multiple different conditions (expressions) Data type Works with integer, character, and enumeration types only Works with any data type including float, stri...

Open this answer on its own page โ†’