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

if (condition) { // statements }

Example

int age = 20; if (age >= 18) { printf("Eligible to vote"); }

if-else Statement

When the condition is true, one block runs;
when false, the other block runs.

Syntax

if (condition) { // true block } else { // false block }

Example

int marks = 40; if (marks >= 33) { printf("Pass"); } else { printf("Fail"); }

Nested if-else

When an if or else contains another if-else inside it.
It is used for multiple conditions.

Syntax

if (condition1) { if (condition2) { // statements } else { // statements } } else { // statements }

Example

int marks = 85; if (marks >= 60) { if (marks >= 80) { printf("Grade A"); } else { printf("Grade B"); } } else { printf("Grade C"); }

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

switch (expression) { case value1: // statements break; case value2: // statements break; ... default: // statements }

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

switch(choice) { case 1: printf("Add"); break; case 2: printf("Subtract"); break; }

Use of default in Switch

Purpose

Executed when no case matches the expression.

Example

default: printf("Invalid choice");

Comparison: switch vs if-else

Featureif-elseswitch
Suitable forRange-based conditionsExact match conditions
Data typesint, float, char, strings, logical expressionsOnly int, char, enum
ExecutionSlower when too many conditionsFaster in multiple fixed options
ReadabilityHard to read when many conditionsClean and structured
UsageComplex conditions, comparisonsMenu-driven programs, exact values

Example Comparison

Using if-else:

if (choice == 1) printf("Start"); else if (choice == 2) printf("Stop"); else printf("Exit");

Using switch:

switch(choice) { case 1: printf("Start"); break; case 2: printf("Stop"); break; default: printf("Exit"); }

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:

  1. for loop
  2. while loop
  3. do-while loop

for Loop

Used when the number of iterations is known in advance.

Syntax

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

Example

for (int i = 1; i <= 5; i++) { printf("%d ", i); }

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

while (condition) { // statements }

Example

int i = 1; while (i <= 5) { printf("%d ", i); i++; }

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

do { // statements } while (condition);

Example

int i = 1; do { printf("%d ", i); i++; } while (i <= 5);

Multiple Loop Variables

In for loops, you can use more than one variable.

Example

for (int i = 1, j = 10; i <= 5; i++, j--) { printf("i=%d, j=%d\n", i, j); }

  • 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

for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { printf("%d ", j); } printf("\n"); }

Assignment Operators

These operators update the value of variables.

OperatorMeaningExampleEquivalent To
=Simple assignmenta = 5
+=Add and assigna += 5a = a + 5
-=Subtract and assigna -= 3a = a - 3
*=Multiply and assigna *= 2a = a * 2
/=Divide and assigna /= 2a = a / 2
%=Modulus and assigna %= 3a = a % 3

These are used extensively inside loops.

break Statement

Used to exit a loop immediately, even if condition is still true.

Example

for (int i = 1; i <= 10; i++) { if (i == 5) break; printf("%d ", i); }

Output: 1 2 3 4
(stops at 5)

continue Statement

Used to skip the current iteration and continue with the next one.

Example

for (int i = 1; i <= 5; i++) { if (i == 3) continue; printf("%d ", i); }

Output: 1 2 4 5
(3 is skipped)

Key Difference: break vs continue

Featurebreakcontinue
PurposeExit the loop completelySkip current iteration
After executionLoop endsNext iteration starts
Common useSearching, stopping earlySkipping certain values

Summary

ConceptExplanation
forBest when iterations are known
whileCondition checked before loop
do-whileExecutes at least once
Multiple variablesAllows controlling two counters
Nested loopsLoop inside loop
Assignment operatorsShort form to update variables
breakStops loop
continueSkips 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:

int add(int a, int b);

Declaration of a Function

Function declaration tells the compiler:

  • Function name
  • Return type
  • Number and type of parameters

Syntax

return_type function_name(parameter_list);

Example

int sum(int x, int y);

This is also called a function prototype.

Function Definition

Defines the actual body of the function.

Syntax

return_type function_name(parameters) { // statements return value; }

Example

int sum(int a, int b) { return a + b;

}

Function Call

This is where the function is actually executed.

Syntax

function_name(arguments);

Example

int result = sum(5, 10);

Function Prototype

A prototype is written before main() to ensure the compiler knows:

  • Type of arguments
  • Type of return value

Example

int multiply(int, int);

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

void change(int x) { x = 50; } int main() { int a = 10; change(a); printf("%d", a); // Output: 10 }

B. Call by Reference (Not directly supported in C)

We use pointers to simulate it.

Example (using pointers)

void change(int *x) { *x = 50; } int main() { int a = 10; change(&a); printf("%d", a); // Output: 50 }

Return Values from a Function

A function can return:

  • int
  • float
  • char
  • double
  • pointer
  • void (returns nothing)

Example

float area(float r) { return 3.14 * r * r; }

void return type

void greet() { printf("Hello"); }

Writing a Multi-Function Program (Example)

Program: Menu-based Calculator

#include <stdio.h> int add(int a, int b); int sub(int a, int b); int main() { int x = 10, y = 5; printf("Addition = %d\n", add(x, y)); printf("Subtraction = %d\n", sub(x, y)); return 0; } int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; }

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

int factorial(int n) { if (n == 0) return 1; else return n * factorial(n - 1); }

Difference Between Iteration and Recursion

FeatureIteration (loops)Recursion
TechniqueRepeats statements using loopsFunction calls itself
Memory useLessMore (stack memory)
SpeedFasterSlower
CodeLongerCleaner, shorter
Examplefor/while loopsfactorial, Fibonacci

Quick Summary

ConceptExplanation
FunctionBlock of code to perform a task
TypesLibrary & User-defined
PrototypeDeclares function before use
CallExecutes the function
ArgumentsPassed by value (default)
Return valueFunction can return any single value
RecursionFunction calling itself
Multi-function programCombines many user-defined functions