7 Functions And Recursion

C Programming · Unit 7

Functions and Recursion

Exam-focused notes for Functions and Recursion (C Programming, BIT102): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Functions and Recursion in short

A function is a named block of code that does one job. Functions make programs shorter, easier to test and easier to reuse.

Functions and Recursion: notes

Function declaration definition and calling

Three things are involved with a function.

  • Declaration (prototype): tells the compiler the name, return type and parameter types. It ends with a semicolon.
  • Definition: the actual code of the function.
  • Call: the statement that runs the function.
#include <stdio.h>

int add(int a, int b);        /* declaration */

int main(void)
{
    int s = add(4, 6);         /* call */
    printf("%d\n", s);
    return 0;
}

int add(int a, int b)          /* definition */
{
    return a + b;
}

Variables in the definition are formal parameters. Values in the call are actual arguments. If a function returns nothing, its return type is void.

Function advantages

  • Code is reused. Write once and call many times.
  • A large program is divided into small, easy parts.
  • Debugging and testing are easier.
  • Program length is reduced.
  • Different programmers can work on different functions.
  • Functions can be kept in libraries and shared.

Pass by value

In call by value, a copy of the argument is passed. Changes made inside the function do not affect the original variable.

void change(int x) { x = 99; }

int main(void)
{
    int a = 5;
    change(a);
    printf("%d\n", a);   /* still 5 */
    return 0;
}

This is the default way of passing arguments in C. It is safe, but it cannot return more than one value directly.

What this unit covers

  • Function declaration definition and calling
  • Function advantages
  • Pass by value
  • Pass by reference
  • Call by reference for swapping
  • Recursive functions
  • Factorial using recursion
  • External functions
  • Arrays as function arguments
  • Functions returning values

Call by reference for swapping

2081 · 5 marks

Explain call by reference of a function with suitable example. [5]

Call by reference is a method of passing arguments to a function where the address (reference) of the actual argument is passed to the formal parameter of the function. Any changes made to the formal parameter inside the function directly affect the actual argument because both refer to the same ...

Open this answer on its own page →

2081.2 · 10 marks

When do we need external function?Illustrate the process of swapping the value of two variables using the concept of pass by value and pass by reference.[3+7]

Show solved answer

External Functions, Pass by Value and Pass by Reference


When Do We Need External Functions? [3 Marks]

We need external functions in the following situations:

  1. Code Reusability: When the same block of code needs to be used in multiple programs or multiple source files, we define it as an external function so it can be called from anywhere without rewriting.

  2. Large Program Management: When a program becomes too large to manage in a single file, it is split into multiple source files. Functions defined in one file and used in another are external functions. The extern keyword is used to declare such functions.

  3. Modular Programming: When we want to divide a program into independent modules (separate .c files), each module may contain functions that are needed by other modules. These are accessed as external functions.

In short: External functions are needed when a function defined in one source file must be accessed and used in another source file, enabling multi-file, modular program development.


Swapping Two Variables [7 Marks]

Concept Overview

MethodDescription
Pass by ValueA copy of the variable is passed. Changes inside the function do NOT affect the original variables.
Pass by ReferenceThe address (pointer) of the variable is passed. Changes inside the function DO affect the original variables.

1. Swapping Using Pass by Value

#include <stdio.h>

void swap(int a, int b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
    printf("Inside function: a = %d, b = %d\n", a, b);
}

int main() {
    int x = 10, y = 20;
    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(x, y);
    printf("After swap: x = %d, y = %d\n", x, y);
    return 0;
}

Output:

Before swap: x = 10, y = 20
Inside function: a = 20, b = 10
After swap: x = 10, y = 20

Explanation:

main()                  swap(a, b)
-------                 ----------
x = 10  ---copy--->    a = 10
y = 20  ---copy--->    b = 20

Inside swap:
temp = a = 10
a = b = 20
b = temp = 10

But x and y in main() remain UNCHANGED
because only copies were passed.

Conclusion: Pass by value fails to swap the original variables. The swap happens only on local copies.


2. Swapping Using Pass by Reference

#include <stdio.h>

void swap(int *a, int *b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After swap: x = %d, y = %d\n", x, y);
    return 0;
}

Output:

Before swap: x = 10, y = 20
After swap: x = 20, y = 10

Explanation (Step by Step):

main() memory:
x = 10  (address: 1000)
y = 20  (address: 1004)

Call: swap(&x, &y)
  --> a = 1000 (pointer to x)
  --> b = 1004 (pointer to y)

Inside swap():
Step 1: temp = *a  --> temp = 10
Step 2: *a   = *b  --> value at 1000 = 20  (x becomes 20)
Step 3: *b   = temp --> value at 1004 = 10  (y becomes 10)

Back in main():
x = 20, y = 10  (ACTUALLY SWAPPED)

Conclusion: Pass by reference successfully swaps the original variables because the function works directly on the memory addresses of x and y.


Key Difference Summary

FeaturePass by ValuePass by Reference
What is passedCopy of valueAddress of variable
Original variable changed?NoYes
Swap successful?NoYes
Syntaxswap(x, y)swap(&x, &y)
Parameter typeint a, int bint *a, int *b
Open this answer on its own page →

Factorial using recursion

2080 · 5 marks

What is recursion? Write a program to find the factorial of a given integer using recursion. [5]

Show solved answer

Recursion and Factorial Program

What is Recursion?

Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. A recursive function solves a problem by breaking it down into smaller subproblems of the same type until it reaches a base case (a condition where the function stops calling itself).

Every recursive function must have:

  1. Base Case - the condition that terminates the recursion
  2. Recursive Case - the part where the function calls itself

Factorial Using Recursion

Mathematical Definition

$$n! = \begin{cases} 1 & \text{if } n = 0 \text{ or } n = 1 \ n \times (n-1)! & \text{if } n > 1 \end{cases}$$

Example: 5! = 5 × 4 × 3 × 2 × 1 = 120


C Program

#include <stdio.h>

// Recursive function to calculate factorial
int factorial(int n) {
    // Base case
    if (n == 0 || n == 1) {
        return 1;
    }
    // Recursive case
    else {
        return n * factorial(n - 1);
    }
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        printf("Factorial of %d = %d\n", num, factorial(num));
    }
    return 0;
}

Trace of Execution (for n = 5)

factorial(5)
  = 5 * factorial(4)
        = 4 * factorial(3)
              = 3 * factorial(2)
                    = 2 * factorial(1)
                              = 1       <-- Base case
                    = 2 * 1 = 2
              = 3 * 2 = 6
        = 4 * 6 = 24
  = 5 * 24 = 120

Output:

Enter a positive integer: 5
Factorial of 5 = 120

Key Points

AspectDescription
Base Casen == 0 or n == 1, returns 1
Recursive Casen * factorial(n-1)
Stack UsageEach call is pushed onto the call stack
TerminationRecursion stops when base case is reached
Open this answer on its own page →

Arrays as function arguments

2079 · 5 marks

Write a program with a function that takes an array as an argument and returns its sum to the main function. [5]

--- --- Concept Description ------ Function argument arr[] passes the array by reference (address); size passes the count by value Return value return sum; sends the computed sum back to main() Function declaration Prototype int arraySum(int arr[], int size); declared before main() Accumulator Va...

Open this answer on its own page →

Recursive functions

2077 · 10 marks

Explain the role of function in programming. How function is declared, defined and called in C?Write a grogram to find factorial of 'n' using recursive function.[5+5]

--- (a) Role of Functions in Programming A function is a self-contained, named block of code that performs a specific task and can be called (invoked) from anywhere in the program. Role Description ------------------- Modularity Breaks a large, complex program into smaller, manageable sub-program...

Open this answer on its own page →

Function advantages

0 · 10 marks

Discuss the advantages of using functions in programming. Differentiate between recursive function and normal function.Write a program using call by reference to swap the values of two variables.[6+4]

--- A function is a self-contained block of code that performs a specific task and can be called multiple times from different parts of a program. 1. Modularity - Functions break a large, complex program into smaller, manageable modules. - Each function handles one specific task, making the progr...

Open this answer on its own page →