4.2 Control Statements
4.2 Control Statements
Introduction to Program Control Flow
Control statements are fundamental constructs that determine the order in which instructions in a program are executed. They allow a program to make decisions, repeat tasks, and branch to different sections of code based on conditions, moving beyond simple sequential execution. This ability to control the flow of execution is what transforms a static list of instructions into a dynamic and intelligent program capable of solving complex problems. This unit covers the primary tools for implementing logic: conditional statements for decision-making and looping constructs for repetition.
1. Conditional Statements
Conditional statements allow a program to choose different paths of execution based on whether a specified condition evaluates to true or false.
1.1 The if Statement
if StatementPurpose: To execute a block of code only if a given condition is true.
Syntax:
if (condition) { // Block of statements to execute if condition is TRUE }Flow:
The
conditionis evaluated. It must be a relational or logical expression resulting intrue(non-zero) orfalse(zero).If
true, the statements inside the block{ }are executed.If
false, the block is skipped, and control jumps to the statement after theifblock.
Example:
int age = 18; if (age >= 18) { printf("You are eligible to vote.\n"); }
1.2 The if-else Statement
if-else StatementPurpose: To execute one block of code if a condition is true, and an alternative block if it is false. It provides a two-way branch.
Syntax:
Flow: One and only one of the two blocks will be executed.
Example:
1.3 Nested if-else and The else-if Ladder
if-else and The else-if LadderNested
if-else: Aniforif-elsestatement inside anotheriforelseblock. Used for multi-level decision making.The
else-ifLadder: A clean way to check multiple conditions in sequence.Syntax:
Flow: Conditions are checked from top to bottom. The block corresponding to the first true condition is executed. The rest are skipped. If none are true, the final
elseblock executes.Example (Grading System):
1.4 The switch Statement
switch StatementPurpose: A multi-way branch statement that selects one of many code blocks to execute based on the value of an integer or character expression. It's often cleaner than a long
else-ifladder when comparing the same variable against constant values.Syntax:
Key Rules:
The
expressionmust evaluate to an integer (int,char,enum).Each
caselabel must be a constant (e.g.,1,'A'), not a variable or range.The
breakstatement is crucial. It terminates theswitchblock. Without it, execution will "fall through" to the nextcasestatements.The
defaultcase is optional and executes if none of thecaseconstants match the expression.
Example:
2. Looping Constructs (Iteration Statements)
Loops are used to execute a block of code repeatedly as long as (or until) a specified condition remains true. They are essential for automating repetitive tasks.
2.1 The for Loop
for LoopPurpose: Used when the number of iterations is known beforehand (counter-controlled loop). It combines initialization, condition checking, and update in one line.
Syntax:
Execution Flow:
Initialization: Executed once at the start. Typically used to initialize a loop counter.
Condition Check: Evaluated before each iteration. If
true, the loop body executes. Iffalse, the loop terminates.Body Execution: The statements inside the loop are executed.
Update: Executed after each iteration of the body. Typically increments/decrements the loop counter.
Go back to Step 2 (Condition Check).
Example (Print numbers 1 to 5):
2.2 The while Loop
while LoopPurpose: Used when the number of iterations is not known beforehand, but the continuation condition is known (condition-controlled loop). It checks the condition before entering the loop body (pre-test loop).
Syntax:
Execution Flow:
Condition is evaluated.
If
true, the loop body executes.After the body, control goes back to step 1.
If
false, the loop is skipped.
Crucial: The body must contain statements that eventually make the condition
false; otherwise, an infinite loop occurs.Example (Sum of digits of a number):
2.3 The do-while Loop
do-while LoopPurpose: Similar to
while, but it guarantees that the loop body executes at least once because it checks the condition after the body (post-test loop).Syntax:
Note the semicolon (
;) afterwhile(condition).Execution Flow:
The body executes.
Condition is evaluated.
If
true, go back to step 1.If
false, exit the loop.
Typical Use Case: Menu-driven programs where you want to show the menu at least once.
Example:
2.4 Comparison of Loops
Feature
for Loop
while Loop
do-while Loop
When to Use
Known number of iterations
Unknown iterations, condition pre-check
Unknown iterations, body must run at least once
Initialization
Inside for( ) statement
Before the loop
Before the loop
Condition Check
At the beginning of each iteration
At the beginning of each iteration
At the end of each iteration
Update
Inside for( ) statement
Inside the loop body
Inside the loop body
Body Execution
Only if condition is true
Only if condition is true
At least once, then while condition is true
3. Loop Control Statements
These statements alter the normal sequential flow of execution within loops (and switch).
3.1 The break Statement
break StatementPurpose: To terminate the execution of the innermost
switch,for,while, ordo-whileloop immediately. Control passes to the statement immediately following the terminated block.Usage:
In Loops: Used to exit a loop prematurely based on some condition inside the body.
In
switch: Used to exit theswitchblock after acaseis executed, preventing fall-through.
Example (Exit loop when a negative number is entered):
3.2 Introduction to The continue Statement
continue StatementPurpose: To skip the rest of the current iteration of the innermost loop and proceed immediately to the next iteration.
In
forloop: It jumps to the update expression.In
while/do-whileloop: It jumps to the condition check.
Effect: It does not terminate the loop; it only skips the statements following
continuefor that particular iteration.Example (Print only odd numbers from 1 to 10):
3.3 Key Difference: break vs continue
break vs continuebreak: Exits the loop entirely. No more iterations occur.continue: Skips the current iteration and moves to the next iteration of the same loop.
Conclusion: Control statements are the decision-making and automation engines of a program. Mastering if-else and switch allows you to build intelligent, branching logic. Proficiency with for, while, and do-while loops enables you to handle repetitive tasks efficiently. Understanding break and continue gives you fine-grained control over these repetitive processes. Combining these constructs allows programmers to model complex real-world logic and solve a vast array of computational problems.
Last updated