0% found this document useful (0 votes)
1 views43 pages

SL7 Chapter 9 Subprograms

Paradigm

Uploaded by

Saurabh Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views43 pages

SL7 Chapter 9 Subprograms

Paradigm

Uploaded by

Saurabh Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subprograms

Introduction to Subprograms:

A subprogram is a reusable block of code that


performs a specific task.
Types in C:
•Functions
•Procedures (void functions)
Example
int add(int a, int b) {
return a + b;
}
Explanation
add() is a function that takes two inputs and
returns their sum.
Advantages of Subprograms

Benefits:
•Code reuse
•Modularity
•Easier debugging
•Improved readability
Example
int square(int x) {
return x * x;
}
Explanation
The function can be reused anywhere in the program.
Function Structure in C

General structure:
return_type function_name(parameters)
{
statements
}
Example:
int multiply(int a, int b) {
return a * b;
}
Explanation
Function multiplies two numbers and returns result.
Function Declaration

Function declaration informs compiler about


function.

int add(int, int);

Explanation
This tells compiler that a function named add
exists.
Function Definition

int add(int a, int b) {


return a + b;
}

Explanation
This provides the actual implementation of the
function.
Function Call

int result = add(3,4);

Explanation

The function add() is called with arguments 3 and 4.


Parameter Passing

Parameters allow data to be passed to functions.


Types:
•Actual parameters
•Formal parameters

Example:
int add(int a, int b)
a and b are formal parameters.
Actual vs Formal Parameters

Example:
int result = add(3,4);

Explanation:
•3 and 4 → actual parameters
•a and b → formal parameters
Pass by Value

In C, parameters are passed by value.

void change(int x){


x = 100;
}

Explanation
Changes affect only local copy.
Pass by Value Example

int x = 10;
change(x);

Explanation
Value of x remains unchanged.
Pass by Reference Using Pointers

void change(int *x){


*x = 100;
}

Explanation
Pointer allows modification of original variable.
Pass by Reference Example

int x = 10;
change(&x);

Explanation
Original variable x becomes 100.
Function Returning Value

int square(int x){


return x*x;
}

Explanation
Function calculates square and returns result.
Void Functions

Functions may not return a value.


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

Explanation
Used for tasks without return values.
Recursion

A function calling itself.


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

Explanation
Calculates factorial recursively.
Recursion Example

fact(4)
Execution:
4 * fact(3)
3 * fact(2)
2 * fact(1)
1

Result = 24.
Stack Frame

Each function call creates a stack frame.

Stores:
•parameters
•local variables
•return address
C example of a stack frame.
#include <stdio.h>

int add(int a, int b) {


int sum = a + b;
return sum;
}

int main() {
int x = 10;
int y = 20;
int result = add(x, y);
printf("%d\n", result);
return 0;
}
What happens

When main() starts, a stack frame is created for main.


Stack frame of main
It stores:
•local variables: x, y, result
•return address for where main should go back when it
finishes
Then this line runs:
int result = add(x, y);
Now add() is called, so a new stack frame is pushed
onto the stack.
Stack frame of add
It stores:
•parameters: a = 10, b = 20
•local variable: sum
•return address back to main
Inside add():
int sum = a + b;

So:
•sum = 30
Then:
return sum;

The value 30 is returned to main, and the stack


frame of add() is removed.
Control goes back to main, and:
result = 30;
Stack view:

While add() is running, stack looks like this:


Top of Stack
-------------------
add() frame
a = 10
b = 20
sum = 30
return address -> main
-------------------
main() frame
x = 10
y = 20
result
-------------------
Bottom of Stack
After add() returns, the add() frame is popped.
Top of Stack
-------------------
main() frame
x = 10
y = 20
result = 30
-------------------
Bottom of Stack
Why this matters:

A stack frame is important because it keeps each function


call separate:
•its own parameters
•its own local variables
•where to return after finishing
That’s why functions do not usually disturb each other’s
local data.

Main idea
A stack frame is like a temporary workspace created for each
function call.
Nested Function Calls

int result = square(add(3,4));

Explanation
First add() runs, then square().
Scope of Variables

Variables inside function are local.


void test(){
int x = 10;
}

Explanation
x cannot be accessed outside function.
Global Variables

int g = 10;

Explanation

Accessible throughout the program.


Static Local Variables

void counter(){
static int count = 0;
count++;
printf("%d",count);
}

Explanation
Value persists between function calls.
Parameter Modes

Parameter passing types:


•Pass by value
•Pass by reference
•Pass by result
•Pass by value-result

C mainly uses value and pointer reference.


Pass by Result Concept

Parameter used only for output.

Example conceptually:
function returns value through
parameter
C uses pointers instead.
#include <stdio.h>

void calculateSumAndProduct(int a, int b, int *sum, int *product) {


*sum = a + b;
*product = a * b;
}

int main() {
int x = 4, y = 5;
int s, p;

calculateSumAndProduct(x, y, &s, &p);

printf("Sum = %d\n", s);


printf("Product = %d\n", p);

return 0;
}
Explanation

Function:
void calculateSumAndProduct(int a, int
b, int *sum, int *product)

•a and b are input parameters


•sum and product are output parameters
Inside function:
*sum = a + b;
*product = a * b;
This writes results back into variables from main.
In main:
calculateSumAndProduct(x, y, &s,
&p);
•&s passes address of s
•&p passes address of p
So the function fills those variables.

Output
Sum = 9
Product = 20
Pass by Value-Result

Value copied in and copied out.

Not directly supported in C.


For pass-by-value-result, the idea is:

[Link] is copied in to the formal parameter at function


start
[Link] works on that local copy
[Link] value is copied out back to actual parameter when
function ends

C does not have true pass-by-value-result, but here is a


conceptual example so you understand it.
Example of pass-by-value- What happens in pass-by-value-result
result: Step 1: Copy in
Actual parameter x is copied into formal
Suppose we have: parameter a
x = 10 a = 10
And call: x = 10
increment(x) Step 2: Modify local copy
Function: Inside function:
procedure increment(a) a = a + 1
begin Now:
a = a + 1 a = 11
end x = 10
Step 3: Copy out
When function ends, a is copied back to x
x = 11

Final result
Before call: x = 10
After call: x = 11
C does not support it directly, but pointer-based code can produce a similar
final effect:

#include <stdio.h>

void increment(int *x) {


int temp = *x; // copy in
temp = temp + 1; // modify local copy
*x = temp; // copy out
}

int main() {
int x = 10;
increment(&x);
printf("%d\n", x);
return 0;
}
Output
11
Default Parameters

Some languages allow default values.

Example (concept):
function f(int x = 5)
C does not support default parameters.
Named Parameters

Some languages allow arguments by name.

Example:
f(x=5,y=10)
Not supported in C.
Function Overloading

Multiple functions with same name but different


parameters.
Supported in C++ but not in C.
Inline Functions

Example in C:
inline int square(int x){
return x*x;
}

Explanation
Reduces function call overhead.
Advantages of Subprograms

•Reusability
•Modularity
•Reduced code duplication
•Easier maintenance
Chapter Summary:

Subprograms help in:


•organizing large programs
•code reuse
•modular design

Important concepts:
•functions
•parameter passing
•recursion
•scope
•stack frames
Thank You

You might also like