Unit 2: Conditional Program Execution
Conditional Program Execution in C
Conditional statements allow a program to make decisions and execute different blocks of code based on certain conditions. They add logic and flexibility to programs.
C supports:
if- if-else
- nested if-else
- switch
if Statement
The if statement executes a block of code only if a given condition is true.
Syntax
Example
if-else Statement
When the condition is true, one block runs;
when false, the other block runs.
Syntax
Example
Nested if-else
When an if or else contains another if-else inside it.
It is used for multiple conditions.
Syntax
Example
Switch Statement
The switch statement is used when you want to select one option from many based on an exact match (like menu selection, options, fixed numeric values).
Syntax
Restrictions on Switch Values
In C:
✔ Allowed data types for case labels:
int- char
- enum
❌ Not allowed:
float- double
- string
- Variables (must be constant expressions)
✔ Case values must be unique
✔ Case values must be constant, not expressions containing variables.
Use of break in Switch
Why break?
- To prevent fall-through (execution of the next case unintentionally).
- It helps exit the switch after a case is matched.
Example
Use of default in Switch
Purpose
Executed when no case matches the expression.
Example
Comparison: switch vs if-else
| Feature | if-else | switch |
|---|---|---|
| Suitable for | Range-based conditions | Exact match conditions |
| Data types | int, float, char, strings, logical expressions | Only int, char, enum |
| Execution | Slower when too many conditions | Faster in multiple fixed options |
| Readability | Hard to read when many conditions | Clean and structured |
| Usage | Complex conditions, comparisons | Menu-driven programs, exact values |
Example Comparison
Using if-else:
Using switch:
Loops and Iteration in C
Loops allow a set of statements to be executed repeatedly until a condition becomes false.
They help avoid writing the same code again and again.
C provides three primary loops:
forloopwhileloopdo-whileloop
for Loop
Used when the number of iterations is known in advance.
Syntax
Example
Output: 1 2 3 4 5
while Loop
Used when the number of iterations is not known beforehand.
It checks the condition before executing the loop body.
Syntax
Example
do–while Loop
This loop executes the body at least once, even if the condition is false.
The condition is tested after running the loop.
Syntax
Example
Multiple Loop Variables
In for loops, you can use more than one variable.
Example
- Both variables change every iteration
- Very useful in algorithms like searching from both ends
Nested Loops
A loop inside another loop is called a nested loop.
Commonly used for:
- Patterns
- 2D arrays
- Multiplication tables
Example: 3x3 Matrix Print
Assignment Operators
These operators update the value of variables.
| Operator | Meaning | Example | Equivalent To |
|---|---|---|---|
= | Simple assignment | a = 5 | — |
+= | Add and assign | a += 5 | a = a + 5 |
-= | Subtract and assign | a -= 3 | a = a - 3 |
*= | Multiply and assign | a *= 2 | a = a * 2 |
/= | Divide and assign | a /= 2 | a = a / 2 |
%= | Modulus and assign | a %= 3 | a = a % 3 |
These are used extensively inside loops.
break Statement
Used to exit a loop immediately, even if condition is still true.
Example
Output: 1 2 3 4
(stops at 5)
continue Statement
Used to skip the current iteration and continue with the next one.
Example
Output: 1 2 4 5
(3 is skipped)
Key Difference: break vs continue
| Feature | break | continue |
|---|---|---|
| Purpose | Exit the loop completely | Skip current iteration |
| After execution | Loop ends | Next iteration starts |
| Common use | Searching, stopping early | Skipping certain values |
Summary
| Concept | Explanation |
|---|---|
for | Best when iterations are known |
while | Condition checked before loop |
do-while | Executes at least once |
| Multiple variables | Allows controlling two counters |
| Nested loops | Loop inside loop |
| Assignment operators | Short form to update variables |
break | Stops loop |
continue | Skips iteration |
Functions in C
A function is a block of code that performs a specific task.
It allows programmers to break a large program into smaller, manageable, reusable parts.
Benefits of using functions
- Reusability
- Easy debugging
- Cleaner code
- Reduces repetition
- Makes program modular
Types of Functions
A. Library Functions
Predefined functions provided by C.
Examples:
printf(), scanf(), sqrt(), strlen()
B. User-Defined Functions
Functions created by the programmer.
Example:
Declaration of a Function
Function declaration tells the compiler:
- Function name
- Return type
- Number and type of parameters
Syntax
Example
This is also called a function prototype.
Function Definition
Defines the actual body of the function.
Syntax
Example
Function Call
This is where the function is actually executed.
Syntax
Example
Function Prototype
A prototype is written before main() to ensure the compiler knows:
- Type of arguments
- Type of return value
Example
This prevents errors and ensures type checking.
Passing Arguments to a Function
There are two ways in C:
A. Call by Value (C uses this method ONLY)
- Copies the value of the variable into the function
- Changes inside the function do not affect the original variable
Example
B. Call by Reference (Not directly supported in C)
We use pointers to simulate it.
Example (using pointers)
Return Values from a Function
A function can return:
int- float
- char
- double
- pointer
void(returns nothing)
Example
void return type
Writing a Multi-Function Program (Example)
Program: Menu-based Calculator
Recursive Functions
A recursive function is a function that calls itself.
Used for:
- Factorial
- Fibonacci
- Tree structures
- Searching and sorting (quick sort, merge sort)
Example: Factorial using recursion
Difference Between Iteration and Recursion
| Feature | Iteration (loops) | Recursion |
|---|---|---|
| Technique | Repeats statements using loops | Function calls itself |
| Memory use | Less | More (stack memory) |
| Speed | Faster | Slower |
| Code | Longer | Cleaner, shorter |
| Example | for/while loops | factorial, Fibonacci |
Quick Summary
| Concept | Explanation |
|---|---|
| Function | Block of code to perform a task |
| Types | Library & User-defined |
| Prototype | Declares function before use |
| Call | Executes the function |
| Arguments | Passed by value (default) |
| Return value | Function can return any single value |
| Recursion | Function calling itself |
| Multi-function program | Combines many user-defined functions |