Computer Fundamentals with C and Unix
(Recursive Functions and Pointers)
Lecture 9: Jan. 11, 2023 Prof. K.R. Chowdhary : Professor of CS

Disclaimer: These notes have not been subjected to the usual scrutiny reserved for formal publications. They may be distributed outside this class only with the permission of the Instructor.

9.1 More about Functions

Functions in C are the basic building blocks of a C program. A function is a set of statements enclosed within curly brackets () that take inputs, do the computation, and provide the resultant output. You can call a function multiple times, thereby allowing reusability and modularity in C programming. It means that instead of writing the same code again and again for different arguments, you can simply enclose the code and make it a function and then call it multiple times by merely passing the various arguments.

We need functions in C programming and even in other programming languages due to the numerous advantages they provide to the developer. Some of the key benefits of using functions are:

There are more important facts about the function sin C language Programming:

9.2 Recursive Functions in C Programming

Functions in C programming are recursive if they can call themselves until the exit condition is satisfied. If a function allows you to call itself within the definition in a C program, it is a recursive function. These functions run by stacking the calls until the exit condition is met and the flow of the program exits the function. Suppose you want to find the factorial of a number in C; you can use a recursive function to get the result. Here’s an example to find the factorial of 8.

#include <stdio.h>
int fact(int num);
int main(){
  int i = 8;
  printf("The factorial of %d is: %d\n", i, fact(i));
  return 0;
}

int fact(int num){
    if (num == 1)
        // Exiting condition
        return (1);
    else
        return (num * fact(num - 1));
}

The Fig. 9.1 shows a recursive function, that computes the factorial of a given number. To take large numbers, the type of that variable as well as the function have been declared as long integers.


PIC

Figure 9.1: A recursion based function called by program


The Fig. 9.2 shows the running of the program mentioned above that calls the recursive function for factorial computation.


PIC

Figure 9.2: Running :A recursive function program



PIC

Figure 9.3: Recursive function call for GCD computation of two numbers