Unit 5: Control Structures

Table of Contents

1. Decision-Making Statements (if, if-else)

Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program.

The if Statement

It is the simplest decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not.

if (condition) {
    // block of code to be executed if the condition is true
}
    

The if-else Statement

The if statement alone tells us that if a condition is true it will execute a block of statements. If the condition is false, we can use else to execute a different block.

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

2. Nested if-else and if-else-if Ladder

Nested if

An if or else statement inside another if or else statement is called nested if.

[Image of nested if-else flowchart]

if-else-if Ladder

Used when we have multiple conditions to check. The compiler checks conditions from top to bottom. As soon as a true condition is found, the statement associated with it is executed.

if (condition1) {
    // code
} else if (condition2) {
    // code
} else {
    // code if no conditions are true
}
    

3. Switch-Case Statement

The switch statement 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.

Rule: The expression used in a switch statement must have an integral or enumerated type (int or char).
switch (expression) {
    case value1:
        // statement
        break;
    case value2:
        // statement
        break;
    default:
        // default statement
}
    

4. Looping Statements (for, while, do-while)

Loops are used to repeat a block of code a specific number of times or until a certain condition is met.

The while Loop

This is an entry-controlled loop. The condition is checked before entering the loop body.

while (condition) {
    // statements
}
    

The do-while Loop

This is an exit-controlled loop. The body of the loop is executed at least once before the condition is checked.

do {
    // statements
} while (condition);
    

The for Loop

Used when the number of iterations is known in advance. It includes initialization, condition, and increment/decrement in one line.

for (initialization; condition; increment/decrement) {
    // statements
}
    

5. Jump Statements: break and continue

These statements are used to alter the flow of a loop or switch statement.

6. Exam Focus Enhancements

Exam Tips

Common Mistakes

Frequently Asked Questions

Q: Can we use float in switch case?
A: No, switch expressions must result in an integer or character constant.

Q: When is a for loop better than a while loop?
A: Use a for loop when you know the exact number of iterations. Use a while loop when you need to repeat something until a specific event/condition occurs.