PadhaikoAll subjects

User-defined Functions

Computer Programming (ENCT 101)

Open in the Padhaiko app

7.1 Introduction to function

A function is a self-contained, named block of code designed to perform a specific, well-defined subtask. Every C program begins execution at main() and may call other functions, which fall into two groups:


7.2 Advantages of function

Decomposing a program into user-defined functions provides major engineering benefits:

  1. Modularity (Divide and Conquer): Breaks large problems into smaller, independent subproblems that are easier to design, understand, and reason about.
  2. Code Reusability: Write a logic block once and invoke it from multiple places with different arguments, eliminating duplication.
  3. Easier Debugging and Testing: Individual functions can be unit-tested and fixed in isolation without breaking unrelated code.
  4. Team Collaboration and Maintainability: Different programmers can implement separate functions concurrently using agreed prototypes.
  5. Reduced Program Size and Clear Abstraction: Callers only need to know what a function does (its signature), not how it works internally.

7.3 Elements of user-defined function

A user-defined function involves three distinct elements: function prototype (declaration), function call, and function definition.

7.3.1 Function definition

The function definition provides the actual body (implementation) of the function:

Anatomy of a Function DefinitionC
return_type function_name(parameter_list) {
    /* local declarations and statements */
    return expression;   /* omitted or 'return;' if return_type is void */
}

7.3.2 Function prototype

A function prototype (declaration) informs the compiler of a function's name, return type, and parameter types before it is called (typically placed above main() or in a .h header file). Parameter names are optional in prototypes, and the prototype ends with a semicolon ;:

int add(int a, int b); or int add(int, int);

Prototypes enable compile-time type checking of arguments and implicit argument conversion when a caller passes compatible types (e.g., int to double).

7.3.3 Function parameters

AspectActual Parameters (Arguments)Formal Parameters
Where They AppearInside the function call, e.g., sum(x, y + 2)Inside the function header definition, e.g., int sum(int a, int b)
What They Can BeVariables, constants, or expressionsMust be typed variable declarations
Memory & LifetimeEvaluated before the call and copied into the formal parametersLocal variables created on the call stack when the function starts, destroyed on return

7.4 Storage class

A storage class specifier in C defines four attributes of a variable or function: storage location (RAM vs. CPU register), default initial value, scope (visibility), and lifetime (duration in memory).

Four Storage Classes in C
Storage ClassStorage LocationDefault Initial ValueScopeLifetime
auto (default for locals)Stack (RAM)Garbage (indeterminate)Local to enclosing blockUntil enclosing block finishes
registerCPU register (if available, else stack)Garbage (indeterminate)Local to enclosing blockUntil enclosing block finishes (cannot apply & address-of)
static (local)Data / BSS segment (RAM)0Local to enclosing blockEntire program execution (retains value across calls)
static (global)Data / BSS segment (RAM)0Internal linkage (current .c file only)Entire program execution
externData / BSS segment (RAM)0External linkage (shared across .c files)Entire program execution

7.5 Scope rules

Scope defines the region of program text where an identifier can be legally accessed:

  1. Block (Local) Scope: Variables declared inside { ... } (or function parameters) are visible only from their declaration to the closing } of that block. An inner block variable with the same name shadows (temporarily hides) an outer variable.
  2. File (Global) Scope: Variables declared outside all functions are visible from their declaration point to the end of the source file (and across files unless marked static).
  3. Function Prototype Scope: Parameter names inside a prototype (int f(int x);) are local to that prototype line only.

7.6 Category of functions

Based on whether a function accepts arguments and returns a value, user-defined functions fall into four standard categories:

7.6.1 Functions with no arguments and no return values

The caller passes no data and expects no result back (void greet(void);). The function handles its own input, processing, and output internally.

7.6.2 Functions with arguments and no return values

The caller passes input data into the function, which processes and displays or mutates data without returning a value (void print_line(int len, char ch);).

7.6.3 Functions with arguments and return values

The most versatile and reusable category: the caller supplies inputs, the function computes a result and sends it back via return (double power(double base, int exp);).

7.6.4 Functions with no arguments and return values

The function takes no parameters from the caller (for example, prompting the user for input or reading a sensor) and returns the obtained value (int read_positive(void);).

Four Categories of User-Defined Functions
CategoryPrototype ExampleSample CallPrimary Use
No args, no returnvoid banner(void);banner();Fixed UI banners, greetings
Args, no returnvoid show_sum(int a, int b);show_sum(3, 5);Formatted printing of given inputs
Args and returnint max2(int a, int b);m = max2(3, 5);Reusable pure computations
No args, returnint get_choice(void);c = get_choice();Validated input readers, random/status getters

7.7 Recursive functions

Definition

Recursion and Its Two Mandatory Parts

A recursive function is a function that calls itself directly or indirectly to solve a smaller instance of the same problem. Every terminating recursion requires:

  1. Base Case: One or more simplest conditions answered directly without making another recursive call (prevents infinite recursion and stack overflow).
  2. Recursive Case: Reduces the problem toward the base case and calls the function on the smaller subproblem.

Each active recursive call pushes a new stack frame (holding its own parameters, local variables, and return address) onto the call stack. Once the base case returns, stack frames unwind in Last-In First-Out (LIFO) order.

AspectRecursionIteration (Loops)
Repetition MechanismRepeated function self-callsfor, while, or do-while loop
TerminationStops when a base case is reachedStops when loop condition becomes false
Memory & SpeedHigher stack memory (O(depth) frames) and call overheadConstant O(1) loop control overhead; faster in C
ReadabilityNatural and concise for trees, factorial, Fibonacci, Tower of HanoiBest for linear counting and array scans

7.8 Function call by values and reference

C natively passes every argument by value. Passing by reference is simulated in C by passing the memory address (pointer) of a variable.

AspectCall by ValueCall by Reference (via Pointers)
What Is PassedA copy of the variable's valueThe memory address (&var) of the variable
Effect on Caller VariableModifying formal parameter does not alter the original caller variableDereferencing *ptr directly modifies the caller's original variable
Multiple OutputsLimited to a single return valueCan update multiple caller variables simultaneously (e.g., swap(&x, &y))

7.9 Passing array and string to function

When an array (or string char[]) is passed to a function, C does not copy all elements onto the stack. Instead, the array name decays into a pointer to its first element (&arr[0]).


Worked Examples

Example 1

1 (6 marks)

Write a recursive C function long fact(int n) to compute the factorial of a non-negative integer n, and trace the call stack and unwinding steps for fact(4).

Recursive Definition of fact(n):

  • Base case: 0! = 1 and 1! = 1 (if (n <= 1) return 1;).
  • Recursive case: n! = n * (n - 1)! (return n * fact(n - 1);).
Recursive Factorial ProgramC
#include <stdio.h>

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

int main(void) {
    printf("4! = %ld\n", fact(4));
    return 0;
}
Answer:

fact(4) returns 24 (and fact(5) returns 120).

Example 2

2 (6 marks)

Trace the output of the following C program demonstrating static local variables, global/local scope shadowing, and call by value vs. call by reference:

Storage Class, Scope, and Parameter Passing TraceC
#include <stdio.h>

int g = 10;

int counter(void) {
    static int c = 0;
    c++;
    return c;
}

void modify(int a, int *b) {
    int g = 99;
    a += g;
    *b += 5;
}

int main(void) {
    int x = 1, y = 2;
    modify(x, &y);
    printf("x=%d y=%d g=%d\n", x, y, g);
    int c1 = counter();
    int c2 = counter();
    int c3 = counter();
    printf("c=%d %d %d\n", c1, c2, c3);
    return 0;
}

Tracing modify(x, &y):

  • Inside modify, int g = 99; is a local variable that shadows global g = 10 without altering global g.
  • a receives a copy of x (1) by value; a += 99 makes local a = 100, leaving caller's x = 1 unchanged.
  • b receives &y (address of y); *b += 5 updates y directly from 2 to 7.
  • When modify returns, global g is still 10. So line 1 prints x=1 y=7 g=10.

Tracing Three Calls to counter(): static int c = 0; is initialized only once and persists across calls:

  • First call: c becomes 1, returns 1.
  • Second call: c retains 1, increments to 2, returns 2.
  • Third call: c retains 2, increments to 3, returns 3.
Answer:

Output:

Program OutputText
x=1 y=7 g=10
c=1 2 3
Example 3

3 (5 marks)

Write a user-defined C function int find_max(const int a[], int n) that takes an integer array and its size, returns the maximum element without modifying the array, and demonstrate calling it from main() on {4, 9, 2, 11, 4}.

Designing find_max(): Initialize int mx = a[0]; and scan indices 1 to n - 1. Using const int a[] ensures the compiler prevents accidental modification of the caller's array.

Passing a 1D Array to a FunctionC
#include <stdio.h>

int find_max(const int a[], int n);

int main(void) {
    int data[] = {4, 9, 2, 11, 4};
    int n = 5;
    printf("Max = %d\n", find_max(data, n));
    return 0;
}

int find_max(const int a[], int n) {
    int mx = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] > mx) {
            mx = a[i];
        }
    }
    return mx;
}
Answer:

find_max(data, 5) prints Max = 11.


Exercises

Exercises — User-defined Functions

Question 1

Differentiate between a function prototype, function definition, and function call. Distinguish formal parameters from actual parameters with an example.

Three Function Elements:

  1. Function Prototype: Declaration ending with ; telling the compiler the return type, name, and parameter types before use (e.g., int square(int);).
  2. Function Definition: Full implementation with body { ... } (e.g., int square(int n) { return n * n; }).
  3. Function Call: Statement/expression invoking execution (e.g., int r = square(5);).

Actual vs. Formal Parameters: In square(5), 5 is the actual parameter (argument) passed by the caller, while n in int square(int n) is the formal parameter receiving the copy inside the function.

Answer:

A prototype declares the signature, a definition provides the body, and a call executes the function. Actual parameters are caller expressions passed in the call, whereas formal parameters are local variables in the function header receiving those values.

Question 2

Compare the four storage classes in C (auto, register, static, extern) with respect to storage location, default initial value, scope, and lifetime.

Storage Class Summary:

  • auto: Stack memory; garbage initial value; block scope; lifetime ends when block exits.
  • register: Requests CPU register storage; garbage initial value; block scope; block lifetime; & cannot be applied.
  • static: Static data segment; default initial value 0; block scope (if local) or file scope (if global); lifetime spans entire program execution.
  • extern: Static data segment; default initial value 0; global/cross-file linkage; lifetime spans entire program execution.
Answer:

auto and register have garbage defaults and block lifetime (stack vs. CPU register request), whereas static and extern initialize to 0 and persist for the entire program run (static restricts visibility to block/file; extern shares across files).

Question 3

Explain call by value vs. call by reference in C. Write a void swap(int *a, int *b) function using pointers and show why void swap(int a, int b) fails to swap variables in main().

Why Call by Value Fails to Swap Caller Variables: In void swap(int a, int b), a and b are independent local copies on the stack. Swapping a and b inside swap leaves the caller's original variables untouched.

Working Pointer-Based swap:

Swapping Two Integers via Call by ReferenceC
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
/* Caller invokes: swap(&x, &y); */

Here *a and *b dereference the caller's addresses directly, exchanging x and y in memory.

Answer:

Call by value passes copies so caller variables remain unchanged; call by reference passes addresses (&x, &y) into pointer parameters (int *a, int *b) so *a and *b swap the original memory contents.

Question 4

What are the two essential components of a recursive function? Write a recursive function int fib(int n) (with fib(0) = 0, fib(1) = 1) and find the value of fib(6).

Two Essential Components:

  1. Base Case: Terminating condition(s) solved directly (if (n <= 1) return n;).
  2. Recursive Case: Self-call on strictly smaller subproblems (return fib(n - 1) + fib(n - 2);).

Evaluating fib(6):

  • fib(0) = 0, fib(1) = 1
  • fib(2) = 1 + 0 = 1
  • fib(3) = 1 + 1 = 2
  • fib(4) = 2 + 1 = 3
  • fib(5) = 3 + 2 = 5
  • fib(6) = 5 + 3 = 8
Answer:

A recursive function requires a base case and a recursive step moving toward it. For fib(0)=0, fib(1)=1, fib(6) evaluates to 8.

Question 5

When an array is passed to a C function, why is it passed by address rather than copied by value? Write a C function int count_vowels(const char str[]) and evaluate its return value on "Computer Programming".

Why Arrays Decay to Pointers: Copying a large array on every function call would waste stack space and CPU time. Instead, C passes only the starting address (&str[0]) as a pointer, allowing O(1) call overhead while letting the function read (or modify, unless const) the caller's array directly.

Function and Trace on "Computer Programming":

Counting Vowels in a Passed StringC
int count_vowels(const char str[]) {
    int count = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        char ch = str[i];
        if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
            ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') {
            count++;
        }
    }
    return count;
}

Vowels in "Computer Programming": 'o', 'u', 'e' in "Computer" (3) and 'o', 'a', 'i' in "Programming" (3), totaling 6 vowels.

Answer:

Arrays decay to a pointer to their first element to avoid expensive stack copies. count_vowels("Computer Programming") counts o, u, e, o, a, i and returns 6.

← Array and PointerStructures →