Knowlet

Unit IV: Decision Making and Looping


1. Decision Making and Branching

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program. Branching allows the program to skip or execute certain blocks of code based on the result of these tests.


2. The IF Family

The if statement is the most powerful tool for controlling the flow of execution.

  • Simple IF Statement: Used to execute a single block of code if a condition is true.
  • IF-ELSE Statement: Executes one block if the condition is true and another block if it is false.
  • Nested IF-ELSE: An if-else statement inside another if or else block, used for complex multi-level decisions.
  • ELSE IF Ladder: A chain of if statements where multiple conditions are checked sequentially.

3. Switch Statement

The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of an expression.

Utility: It is often used as a cleaner alternative to a long else if ladder when comparing a single variable against multiple constant values.

4. Looping: Introduction and Types

Looping involves repeating a set of instructions until a specific condition is met. This is essential for tasks like processing array elements or generating series.


5. While, Do-While, and For Statements

There are three primary looping constructs in C:

  • while Statement: An entry-controlled loop that checks the condition before executing the loop body.
  • do-while Statement: An exit-controlled loop that executes the body at least once before checking the condition.
  • for Statement: A compact loop structure that includes initialization, condition, and increment/decrement in a single line.

Exam Tips

  • Semicolon Warning: Never put a semicolon after the if(condition) or for(...) header, as it terminates the statement immediately without executing the block.
  • Switch Break: Always remember to use the break keyword in switch cases; otherwise, execution will "fall through" to subsequent cases.
  • Loop Selection: Use a for loop when you know the number of iterations in advance and a while loop when the termination depends on a condition.

Frequently Asked Questions

Q1: What is the main difference between while and do-while?
The while loop may never execute if the condition is false initially, whereas do-while guarantees at least one execution.

Q2: When should I use an ELSE IF ladder over a Switch?
Use an else if ladder for range-based conditions (e.g., marks > 90) and a switch for specific discrete values (e.g., choice == 1).

Did this resource help you study?

Share feedback or report issues to help improve this resource.