Comprehensive Study Guide on Control Structures in C
Overview of Unit 2: Control Structures
Subject: Computer Programming & C Language
Unit: Unit 2 — Control Structures
Allocated Time: 8 Hours
Core Concepts Covered:
Decision Control Structures:
if,if-else,else-ifladder, conditional operator statement (? :),switch-casestatement.Loop Control Structures:
for,while,do-whileloops.Nested Control Structures: Nested
ifand nested loops.Jump Statements:
break,continue,gotoand their practical uses.Problem Solving: Comprehensive examples and logic-building steps involving basic control structures.
Case Study #3: Performance comparison of
if-elseversusswitch-caseconstructs in scenarios such as grading systems, analyzing scalability, compiler jump-table optimization, and code maintainability.
Decision Control Structures
Fundamentals of Decision Making in C
By default, C program statements execute sequentially from top to bottom.
Decision-making (conditional) statements are utilized to control the execution flow of a program based on specific criteria.
They enable conditional execution, allowing the program to decide whether a particular block of code should execute or be bypassed.
Evaluation Mechanism:
The decision statement evaluates a relational or logical expression (condition).
The condition yields either a true (non-zero) or false (zero) logical result.
Based on the evaluated result, program control is transferred dynamically to a designated branch or statement path.

Classification of Decision Making Statements
One-Way Decision:
ifstatement.Two-Way Decision:
if...elsestatement and Conditional Operator (? :).Multi-Way / n-Way Decision:
if...else if...elseladder andswitch...casestatement.
The if Statement
The
ifstatement is a single-branch decision-making construct.The keyword
ifsignals the start of the construct.Execution Rule: The body within the
ifblock is executed if and only if the specified condition evaluates to true (non-zero). If the condition evaluates to false (zero), the body is skipped entirely, and execution resumes at the subsequent program statement.Syntax:
c if (condition) { // Body of if (executed only when condition is true) } Braces
{}Policy:If the body of the
ifconstruct contains only a single statement, curly braces{}are optional.If the body contains two or more statements, curly braces
{}are strictly mandatory to group them into a compound statement.
if Statement Examples
Example 1: Print Zero if Given Number is 0 ```c
include
void main() { int a; printf("Enter Number:"); scanf("%d", &a); if (a == 0) { printf("Zero"); } } ```
Sample Output 1:
text Enter Number:0 Zero
Example 2: Print Positive or Negative Number using Independent
ifStatements ```cinclude
void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a >= 0) { printf("Positive Number"); } if (a < 0) { printf("Negative Number"); } } ```
Sample Output 1:
text Enter Number:5 Positive Number Sample Output 2:
text Enter Number:-5 Negative Number
Example 3: Print Odd or Even Number using Independent
ifStatements ```cinclude
void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a % 2 == 0) { printf("Even Number"); } if (a % 2 != 0) { printf("Odd Number"); } } ```
Sample Output 1:
text Enter Number:12 Even Number Sample Output 2:
text Enter Number:11 Odd Number
Example 4: Find Largest Number from 2 Given Numbers using Independent
ifStatementsc #include <stdio.h> void main() { int a, b; printf("Enter Two Numbers:"); scanf("%d %d", &a, &b); if (a > b) { printf("%d is largest", a); } if (a < b) { printf("%d is largest", b); } } Sample Output:
text Enter Two Numbers:4 5 5 is largest
The if...else Statement
The
if...elseconstruct provides a two-branch decision-making structure.elseis a reserved C keyword.Execution Rule: If the condition evaluates to true, the
ifbranch body is executed. If the condition evaluates to false, execution bypasses theifbody and executes theelsebranch body instead. Under no circumstance are both bodies executed in a single evaluation.Syntax:
c if (condition) { // True part execution } else { // False part execution }
if...else Statement Examples
Example 1: Positive or Negative Number Determination ```c
include
void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a >= 0) { printf("Positive Number"); } else { printf("Negative Number"); } } ```
Example 2: Odd or Even Number Determination ```c
include
void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a % 2 == 0) { printf("Even Number"); } else { printf("Odd Number"); } } ```
Example 3: Find Largest Number from 2 Numbers
c #include <stdio.h> void main() { int a, b; printf("Enter Two Numbers: "); scanf("%d %d", &a, &b); if (a > b) { printf("%d is largest", a); } else { printf("%d is largest", b); } }
The if...else if...else Ladder
The
else ifladder is a multi-branch decision construct suitable for evaluating multiple sequential conditions.Evaluation Strategy:
Sequential conditions are tested top-down starting from
condition-1.As soon as any condition evaluates to true, its associated statement block executes, and the remainder of the entire ladder is bypassed entirely.
If
condition-1is false,condition-2is evaluated. This process continues down the ladder.If none of the tested conditions evaluate to true, the final trailing
elsestatement block executes as the default fall-through branch.
Syntax:
c if (condition-1) statement-1; else if (condition-2) statement-2; else if (condition-3) statement-3; else default-statement;
if...else if...else Ladder Examples
Example 1: Classify Number as Zero, Positive, or Negative
c #include <stdio.h> void main() { int a; printf("Enter Number: "); scanf("%d", &a); if (a > 0) { printf("Positive Number"); } else if (a == 0) { printf("Zero"); } else { printf("Negative Number"); } }
Nested if Statements
A nested
ifrefers to placing aniforif...elsestructure inside anotheriforelseblock.Execution Logic:
An inner condition (
condition-2) is evaluated if and only if the primary outer condition (condition-1) evaluates to true.If
condition-1is false, execution shifts immediately to the outerelsebranch (statement-3).
Syntax:
c if (condition-1) { if (condition-2) { statement-1; } else { statement-2; } } else { statement-3; }
Nested if Examples
Example 1: Find Maximum Among Three Numbers
c #include <stdio.h> void main() { int a, b, c; printf("Enter Three Numbers: "); scanf("%d %d %d", &a, &b, &c); if (a > b) { if (a > c) printf("%d is max", a); else printf("%d is max", c); } else { if (b > c) printf("%d is max", b); else printf("%d is max", c); } } Sample Output:
text Enter Three Numbers:7 5 9 9 is max
The Conditional Operator (? :)
The conditional operator is C's only ternary operator (requiring three operands).
It offers a compact alternative to simple
if-elseconstructs.Structure:
variable = Expression1 ? Expression2 : Expression3Expression1is the condition to evaluate.If
Expression1evaluates to true (non-zero),Expression2is evaluated, and its value is assigned/returned.If
Expression1evaluates to false (zero),Expression3is evaluated, and its value is assigned/returned.
Conditional Operator Examples
Example 1: Find Largest of Two Numbers
c #include <stdio> void main() { int a, b, max; printf("Enter Two Numbers:"); scanf("%d %d", &a, &b); max = (a > b) ? a : b; printf("%d is largest", max); }
The switch...case Statement
The
switchstatement provides a multi-way selective branching mechanism that allows a variable or expression to be tested against a set of integer/character constant values.Behavioral Rules:
The control expression inside
switch(expression)is evaluated once and compared sequentially against the values in eachcase constant:label.The expression must yield an integral or character evaluation (floating-point expressions are prohibited).
If an exact match is identified, program execution jumps directly to the matching
caseblock.Fall-Through Effect: Without an explicit
break;statement terminating a case block, control continues executing into subsequent case blocks regardless of whether those labels match.The
default:block is optional and executes when no matching constant matches the switch expression.
Syntax:
c switch (expression) { case constant1: // statements break; case constant2: // statements break; default: // default statements executed if no match }
switch...case Examples
Example 1: Map Day Number (1–7) to Day Name
c #include <stdio.h> void main() { int day; printf("Enter day number (1-7):"); scanf("%d", &day); switch (day) { case 1: printf("Sunday"); break; case 2: printf("Monday"); break; case 3: printf("Tuesday"); break; case 4: printf("Wednesday"); break; case 5: printf("Thursday"); break; case 6: printf("Friday"); break; case 7: printf("Saturday"); break; default: printf("Wrong input"); break; } } Sample Output:
text Enter day number (1-7):5 Thursday
Loop Control Structures
Concept and Necessity of Looping
A loop control structure enables repeated execution of a specific block of code for a designated number of times or until a defined loop condition evaluates to false.
Loops eliminate redundant code replication, optimize memory usage, and improve code modularity.
Taxonomy of Loop Control Structures
Entry-Controlled Loops: Condition is checked prior to executing the loop body.
whileloopforloop
Exit-Controlled Loops: Loop body executes once before its termination condition is verified at the bottom.
do-whileloop
Virtual Loop:
gotostatement (unconditional branch used to emulate iteration).
Methodological Logic Building in Loop Programming
Developing efficient algorithms for loop problems involves a structured 4-step framework:
Step 1: Problem Analysis and Conceptualization
Objective: Analyze the requirements completely (e.g., Finding factors of an integer ).
Domain Knowledge: A factor of is any integer that divides completely with zero remainder ().
Variable Allocation:
Input integer stored in variable
n.Loop iterator variable
iinitialized to start checking from .
Control Structure Identification:
A loop iterator variable running sequentially from up to .
An embedded
ifconstruct checking the divisibility conditionn % i == 0during each iteration.
Step 2: Test Case Analysis
Test Case 1 ():
(1 is a factor)
(2 is a factor)
(3 is a factor)
(6 is a factor)
Inference: Iterator starts at , increments by , and terminates when .
Test Case 2 (): Factors are .
Test Case 3 (): Factors are (Prime integer).
General Rule: Every positive integer has at least and as universal factors.
Step 3: Algorithmic Blueprinting and Flowcharting
Step 1: Start execution.
Step 2: Declare integer variables
n,i.Step 3: Initialize iterator variable .
Step 4: Read input integer
nfrom user.Step 5: Evaluate loop condition :
If , evaluate sub-condition
n % i == 0.If
n % i == 0is True, print value of .Increment iterator .
Re-evaluate loop condition.
Step 6: Stop execution when loop condition evaluates to False.
Step 4: Pseudo-Code Design
```text
Initialize i = 1 as integer Declare n as integer Input n while i <= n do if n % i == 0 then print i end if i = i + 1 end while
## Structural Distinction: `if` vs `while` Constructs
* **`if` Statement**: Evaluates condition once. If true, executes the statement block exactly once, then transfers control to subsequent lines.
* **`while` Loop**: Evaluates condition. If true, executes loop body, and automatically loops control back to re-evaluate condition. Execution repeats iteratively until condition evaluates to false.
## The `while` Loop
* An **entry-controlled** looping construct.
* Statements inside the body are repeatedly executed as long as the relational condition evaluates to **true**.
* **Syntax**:
```c
while (condition)
{
// Body of while loop
// Increment / Decrement statement
}
```
### `while` Loop Examples and Execution Traces
* **Example 1: Print Numbers 1 to n**
```c
#include <stdio.h>
void main()
{
int i, n;
i = 1;
printf("Enter n: ");
scanf("%d", &n);
while (i <= n)
{
printf("%d
", i);
i = i + 1;
}
}
```
* **Example 2: Print Odd Numbers Between 1 to n (with Trace Table)**
```c
#include <stdio.h>
void main()
{
int i = 1, n;
printf("Enter the value of n");
scanf("%d", &n);
while (i <= n)
{
if (i % 2 != 0)
{
printf("%d
", i);
}
i = i + 1;
}
}
```
#### Execution Trace Table for Odd Numbers Program ()
| Line # | `i` | `n` | Condition / Statement | Result | Execution Action / Output | Process Notes |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| 1–5 | - | - | Initial declarations | - | Headers, main startup | Setup program memory |
| 6 | 1 | - | Initializing variable | - | `i` set to 1 | Initial iterator value |
| 7 | 1 | 5 | Input scanning | - | Reads `n = 5` | Value scanned into `n` |
| 8 | 1 | 5 | `i <= n` (`1 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 1 | 5 | `i % 2 != 0` (`1 % 2 != 0`) | **True** | Enter `if` statement block | 1 is odd |
| 10 | 1 | 5 | `printf("%d
", i)` | - | **Output: 1** | Print current odd `i` |
| 11 | 2 | 5 | `i = i + 1` | - | `i` updated to 2 | Increment iterator |
| 8 | 2 | 5 | `i <= n` (`2 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 2 | 5 | `i % 2 != 0` (`2 % 2 != 0`) | **False** | Skip `if` body | 2 is even |
| 11 | 3 | 5 | `i = i + 1` | - | `i` updated to 3 | Increment iterator |
| 8 | 3 | 5 | `i <= n` (`3 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 3 | 5 | `i % 2 != 0` (`3 % 2 != 0`) | **True** | Enter `if` statement block | 3 is odd |
| 10 | 3 | 5 | `printf("%d
", i)` | - | **Output: 3** | Print current odd `i` |
| 11 | 4 | 5 | `i = i + 1` | - | `i` updated to 4 | Increment iterator |
| 8 | 4 | 5 | `i <= n` (`4 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 4 | 5 | `i % 2 != 0` (`4 % 2 != 0`) | **False** | Skip `if` body | 4 is even |
| 11 | 5 | 5 | `i = i + 1` | - | `i` updated to 5 | Increment iterator |
| 8 | 5 | 5 | `i <= n` (`5 <= 5`) | **True** | Enter loop body | Loop condition passes |
| 9 | 5 | 5 | `i % 2 != 0` (`5 % 2 != 0`) | **True** | Enter `if` statement block | 5 is odd |
| 10 | 5 | 5 | `printf("%d
", i)` | - | **Output: 5** | Print current odd `i` |
| 11 | 6 | 5 | `i = i + 1` | - | `i` updated to 6 | Increment iterator |
| 8 | 6 | 5 | `i <= n` (`6 <= 5`) | **False** | Terminate loop | Loop exits |
| 13 | 6 | 5 | End of `main()` | - | Returns execution | Program ends successfully |
* **Example 3: Print Multiplication Table**
```c
#include <stdio.h>
void main()
{
int i = 1, n;
printf("Enter n for multiplication table:");
scanf("%d", &n);
while (i <= 10)
{
printf("%d * %d = %d
", n, i, n * i);
i = i + 1;
}
}
```
* **Example 4: Calculate Sum of 5 User-Entered Numbers**
```c
#include <stdio.h>
void main()
{
int sum = 0, i = 1, n;
while (i <= 5)
{
printf("Enter a number=");
scanf("%d", &n);
sum = sum + n;
i = i + 1;
}
printf("Sum is=%d", sum);
}
```
* **Example 5: Find Factors of a Number**
```c
#include <stdio.h>
void main()
{
int i = 1, n;
printf("Enter n to find factors=");
scanf("%d", &n);
while (i <= n)
{
if (n % i == 0)
{
printf("%d,", i);
}
i = i + 1;
}
}
```
* **Example 6: Reverse an Integer Value**
```c
#include <stdio.h>
void main()
{
int n;
printf("Enter a number=");
scanf("%d", &n);
while (n != 0)
{
printf("%d", n % 10);
n = n / 10;
}
}
```
* **Example 7: Check if Number is Perfect Number**
* *Definition*: A perfect number is a positive integer equal to the sum of its proper positive divisors (excluding itself).
```c
#include <stdio.h>
void main()
{
int i = 1, n, sum = 0;
printf("Enter a number:");
scanf("%d", &n);
while (i < n)
{
if (n % i == 0)
{
printf("%d+", i);
sum = sum + i;
}
i = i + 1;
}
printf("=%d", sum);
if (sum == n)
printf("
%d is a perfect number", n);
else
printf("
%d is not a perfect number", n);
}
```
* *Sample Output 1*:
```text
Enter a number:6
1+2+3=6
6 is a perfect number
```
* *Sample Output 2*:
```text
Enter a number:8
1+2+4+=7
8 is not a perfect number
```
* *Sample Output 3*:
```text
Enter a number:496
1+2+4+8+16+31+62+124+248+=496
496 is a perfect number
```
## The `for` Loop
* An **entry-controlled** loop structure that consolidates initialization, condition testing, and parameter update operations into a single header statement.
* **Execution Order**:
1. **Initialization**: Executed exactly once prior to the first loop test.
2. **Condition Evaluation**: Tested before each iteration. If false, loop terminates.
3. **Body Execution**: Executed if the condition tests true.
4. **Update Statement**: Executed at the end of every iteration, immediately prior to re-evaluating the condition.
* **Syntax**:
```c
for (initialization; condition; updateStatement)
{
// Loop body statements
}
```
### `for` Loop Examples
* **Example 1: Print Numbers 1 to n**
```c
#include <stdio.h>
void main()
{
int i, n;
printf("Enter a number:");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("%d
", i);
}
}
```
* **Example 2: Find Factors of a Number**
```c
#include <stdio.h>
void main()
{
int i, n;
printf("Enter n to find factors=");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
printf("%d,", i);
}
}
}
```
* **Example 3: Check Perfect Number**
```c
#include <stdio.h>
void main()
{
int i, n, sum = 0;
printf("Enter a number:");
scanf("%d", &n);
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
printf("%d+", i);
sum = sum + i;
}
}
printf("=%d", sum);
if (sum == n)
printf("
%d is a perfect number", n);
else
printf("
%d is not a perfect number", n);
}
```
## The `do-while` Loop
* An **exit-controlled** looping construct.
* **Key Property**: The loop body is executed **at least once** regardless of whether the loop condition is initially true or false, because condition verification occurs at the bottom of the loop.
* **Syntax**:
```c
do
{
// Body of do-while loop
} while (condition);
```
*(Note: A trailing semicolon `;` after `while(condition)` is mandatory).*
### `do-while` Loop Examples
* **Example 1: Print Odd Numbers Between 1 to n**
```c
#include <stdio.h>
void main()
{
int i = 1, n;
printf("Enter a number: ");
scanf("%d", &n);
do
{
if (i % 2 != 0)
{
printf("%d,", i);
}
i = i + 1;
} while (i <= n);
}
```
* **Example 2: Reverse a Given Number**
```c
#include <stdio.h>
void main()
{
int n;
printf("Enter a number:");
scanf("%d", &n);
do
{
printf("%d", n % 10);
n = n / 10;
} while (n != 0);
}
```
# Jump Statements in C
* Jump statements force unconditional dynamic control transfers to another location within the program, bypassing standard structured sequencing.
## The `break` Statement
* Immediately terminates the execution of the innermost enclosing `for`, `while`, `do-while` loop, or `switch` construct.
* Program control transfers immediately to the first statement following the terminated control structure.
* In nested loops, `break` exits **only** the innermost loop layer currently executing.

### `break` Code Demonstration
c
include
int main() { int i; for (i = 1; i <= 10; i++) { if (i == 6) { break; } printf("%d ", i); } printf("Loop exited. "); return 0; }
* *Output*: `1 2 3 4 5 Loop exited.`
## The `continue` Statement
* Skips all remaining statements in the **current iteration** of a `for`, `while`, or `do-while` loop body.
* Control transfers immediately to the loop update/condition step for the next iteration.

### `continue` Code Demonstration
c
include
int main() { int i; for (i = 0; i < 5; i++) { if (i == 2) { printf("Skipping iteration %d ", i); continue; } printf("Executing iteration %d ", i); } return 0; } ```
Output:
text Executing iteration 0 Executing iteration 1 Skipping iteration 2 Executing iteration 3 Executing iteration 4
The goto Statement
Provides an unconditional jump from the
gotostatement directly to a designated labeled statement within the same function scope.Syntactic Constructs:
Forward Jump:
c goto label_name; // ... label_name: // statement execution resumes here Backward Jump:
c label_name: // statement execution target // ... goto label_name;
Engineering Note: Unrestricted use of
gotogenerates unmaintainable control flow ("spaghetti code"). Its usage is limited to exiting deeply nested loops or handling unified function failure cleanup routines.

goto Code Examples
Example 1: Print Odd Numbers Between 1 to n Using
goto```cinclude
void main() { int i = 1, n; printf("Enter a number:"); scanf("%d", &n); odd: if (i % 2 != 0) { printf("%d,", i); } i = i + 1; if (i <= n) { goto odd; } } ```
Example 2: Find Factors of a Number Using
gotoc #include <stdio.h> void main() { int i = 1, n; printf("Enter a number:"); scanf("%d", &n); odd: if (n % i == 0) { printf("%d,", i); } i = i + 1; if (i <= n) { goto odd; } }
Comparative Analysis & Practical Applications
Case Study #3: Performance & Architecture — if-else vs. switch-case Constructs
Scenario Context: Designing an enterprise automated grading system evaluating student marks across multiple discrete thresholds ().
Computational Complexity and Execution Performance
if-elseLadder: Executes sequentially ( time complexity). Every preceding condition must evaluate to false before testing subsequent conditions. In large decision trees, worst-case execution time grows linearly with branch count.switch-caseConstruct: When compiled with multiple contiguous cases, modern compilers synthesize an optimized Jump Table (array of code pointers) or Binary Search Tree. Jump tables achieve constant time complexity () execution by calculating memory address offsets directly.
Maintainability, Readability, and Scalability Comparison
Assessment Metrics |
|
|
|---|---|---|
Expression Versatility | Handles complex ranges, floating-point math, and compound logical operations ( | Restricted strictly to integer, character constants, and enumerated type equality matching. |
Algorithmic Scalability | Degrades in readability and performance as decision branch paths scale into large numbers. | Highly scalable; structured jump tables keep execution speed uniform (). |
Code Maintainability | Prone to syntax nesting errors; difficult to modify multi-level logical branches safely. | Highly structured modular format; simple to add, remove, or modify isolated case labels. |
Control Fall-Through | Bypasses all subsequent blocks automatically upon finding a true condition. | Requires explicit |
Design Recommendation for Grading Systems
For Continuous Range Grading (e.g., ):
if-elseconstructs are idiomatic because standard Cswitchstatements do not natively support continuous variable range comparisons without dynamic condition mapping.For Discrete Grade Scale Processing (e.g., Mapping letter grades
'A','B','C','D','F'to distinct administrative procedures): Theswitch-casepattern provides optimal runtime performance, clean maintainability, and streamlined architecture.