Class 9 | Functions | C Programming Notes

Functions in C Programming

A function is a block of code designed to perform a specific task. A function runs only when it is called.

Every C program contains at least one function, called the main() function. A large program can be divided into several smaller functions, making the program easier to understand, develop, test, debug, and maintain.

A function generally involves three important aspects:

  1. Function Declaration
  2. Function Definition
  3. Function Call

Example of a Function

The following program calculates the factorial of a number using a function:

#include <stdio.h>

int factorial(int n);

int main(void)
{
    int num;

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

    printf("Factorial of %d = %d\n", num, factorial(num));

    return 0;
}

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

Function Aspects

The three main aspects of a function are:

  1. Function Declaration
  2. Function Definition
  3. Function Call

1. Function Declaration

A function declaration is also called a function prototype.

It tells the compiler about:

  • Return type of the function
  • Function name
  • Number of parameters
  • Data types of parameters

A function declaration ends with a semicolon ;.

Syntax

return_type function_name(data_type parameter1, data_type parameter2);

It can also be written without parameter names:

return_type function_name(data_type, data_type);

Example

int add(int a, int b);

or:

int add(int, int);

Here:

  • int is the return type.
  • add is the function name.
  • int a and int b are parameters.

2. Function Definition

A function definition contains the actual statements that perform a particular task.

A function definition mainly consists of:

  1. Function Header
  2. Function Body

Function Header

The function header contains:

  • Return type
  • Function name
  • Parameter list

Example

int add(int a, int b)

Unlike a function declaration, the function header in a definition is not followed by a semicolon.


Function Body

The function body contains the statements that perform the required operation.

It is enclosed within curly braces { }.

Syntax

return_type function_name(data_type parameter1, data_type parameter2)
{
    // statements
}

Example

int add(int a, int b)
{
    int sum;

    sum = a + b;

    return sum;
}

3. Function Call

A function call is used to execute a function.

A function is called using its name followed by parentheses containing the required arguments.

Syntax

function_name(arguments);

If the function returns a value:

variable = function_name(arguments);

Example

result = add(10, 20);

Here:

  • add() is the function.
  • 10 and 20 are arguments.
  • The returned value is stored in result.

Example of Function Declaration, Definition and Call

#include <stdio.h>

int add(int a, int b);

int main(void)
{
    int result;

    result = add(10, 20);

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

    return 0;
}

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

Types of Functions

Functions in C can broadly be classified into:

  1. Library Functions
  2. User-Defined Functions

1. Library Function

A library function is a predefined function provided by the C libraries.

Programmers can directly use library functions by including the appropriate header files.

Examples

  • printf()
  • scanf()
  • sqrt()
  • strlen()
  • strcpy()

Example of Library Function

#include <stdio.h>
#include <math.h>

int main(void)
{
    double a = 25;
    double result;

    result = sqrt(a);

    printf("The square root is %.2f\n", result);

    return 0;
}

Output

The square root is 5.00

In this example, sqrt() is a predefined mathematical library function.


2. User-Defined Function

A user-defined function is a function created by the programmer according to the requirements of the program.

Examples

  • sum()
  • product()
  • division()
  • add()
  • subtract()

Example of User-Defined Function

#include <stdio.h>

int product(int a, int b);

int main(void)
{
    int a, b, result;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    result = product(a, b);

    printf("The product is %d\n", result);

    return 0;
}

int product(int a, int b)
{
    int p;

    p = a * b;

    return p;
}

Benefits of Using Functions

The major benefits of using functions are:

  1. Functions reduce code repetition.
  2. They make programs shorter and more organized.
  3. Functions improve code reusability.
  4. Large programs can be divided into smaller manageable parts.
  5. Debugging and error detection become easier.
  6. Programs become easier to understand and maintain.
  7. Individual functions can be tested separately.
  8. Different programmers can work on different parts of a large program.
  9. A function can be called multiple times whenever required.

Categories of User-Defined Functions

User-defined functions can be classified into four categories according to whether arguments are passed and whether a value is returned.

The four categories are:

  1. Function with arguments and return value
  2. Function with arguments and no return value
  3. Function with no arguments and return value
  4. Function with no arguments and no return value

1. Function With Arguments and Return Value

In this type of function:

  • Arguments are passed from the calling function to the called function.
  • The called function returns a value to the calling function.

Example

#include <stdio.h>

int sum(int x, int y);

int main(void)
{
    int a = 2;
    int b = 3;
    int c;

    c = sum(a, b);

    printf("The sum of two numbers is %d\n", c);

    return 0;
}

int sum(int x, int y)
{
    return x + y;
}

Output

The sum of two numbers is 5

2. Function With Arguments and No Return Value

In this type of function:

  • Arguments are passed to the function.
  • The function does not return any value.

Therefore, the return type is void.

Example

#include <stdio.h>

void add(int a, int b);

int main(void)
{
    int a = 50;
    int b = 90;

    add(a, b);

    return 0;
}

void add(int a, int b)
{
    int sum;

    sum = a + b;

    printf("The sum is %d\n", sum);
}

Output

The sum is 140

3. Function With No Arguments and Return Value

In this type:

  • No argument is passed to the function.
  • The function returns a value to the calling function.

Example

#include <stdio.h>

int add(void);

int main(void)
{
    int result;

    result = add();

    printf("The sum is %d\n", result);

    return 0;
}

int add(void)
{
    int a = 50;
    int b = 90;
    int sum;

    sum = a + b;

    return sum;
}

Output

The sum is 140

4. Function With No Arguments and No Return Value

In this type:

  • No argument is passed.
  • No value is returned.

Therefore, the function uses the void return type.

Example

#include <stdio.h>

void add(void);

int main(void)
{
    add();

    return 0;
}

void add(void)
{
    int a = 50;
    int b = 90;
    int sum;

    sum = a + b;

    printf("The sum is %d\n", sum);
}

Output

The sum is 140

Summary of Function Categories

Function TypeArgumentsReturn Value
With arguments and return valueYesYes
With arguments and no return valueYesNo
Without arguments and with return valueNoYes
Without arguments and without return valueNoNo

Difference Between Library Function and User-Defined Function

Library FunctionUser-Defined Function
It is predefined in C libraries.It is created by the programmer.
Its implementation is already available.Its implementation must be written by the programmer.
Appropriate header files are generally required.A function prototype may be declared before the function is called.
It saves programming time.It is created for a particular programming requirement.
Its standard name and behavior are predefined.The programmer chooses its name and operation.
Examples: printf(), scanf(), sqrt(), strlen().Examples: sum(), product(), reverse(), add().

void Return Type

The keyword void is used when a function does not return a value to the calling function.

Syntax

void function_name(void)
{
    // statements
}

Example

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

Program to Display the Series 2, 4, 6, 8, … up to 10 Terms

#include <stdio.h>

void series(int a);

int main(void)
{
    int a = 2;

    series(a);

    return 0;
}

void series(int a)
{
    int i;

    for (i = 1; i <= 10; i++)
    {
        printf("%d\t", a);

        a = a + 2;
    }
}

Output

2    4    6    8    10    12    14    16    18    20

Actual and Formal Parameters

When data is passed between functions, two important terms are used:

  1. Actual Parameters
  2. Formal Parameters

Actual Parameters

The values or variables supplied when calling a function are called actual parameters or arguments.

Example

sum(a, b);

Here, a and b are actual parameters.


Formal Parameters

The variables declared in the function definition to receive values from the calling function are called formal parameters.

Example

int sum(int x, int y)

Here, x and y are formal parameters.


Types of Function Calls

The chapter commonly describes two methods of passing data to functions:

  1. Call by Value
  2. Call by Reference

1. Call by Value

In call by value, copies of the values of actual parameters are passed to the formal parameters.

The actual and formal parameters use separate memory locations.

Therefore, changes made to the formal parameters inside the function do not affect the original variables.


Example of Call by Value

#include <stdio.h>

void swap(int x, int y);

int main(void)
{
    int a = 10;
    int b = 20;

    printf("Before swapping: a = %d, b = %d\n", a, b);

    swap(a, b);

    printf("After swapping: a = %d, b = %d\n", a, b);

    return 0;
}

void swap(int x, int y)
{
    int temp;

    temp = x;
    x = y;
    y = temp;

    printf("Inside swap function: x = %d, y = %d\n", x, y);
}

Output

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

The original values of a and b remain unchanged.


2. Call by Reference Using Pointers

In C, what is commonly taught as call by reference is achieved by passing the addresses of variables to a function using pointers.

The function can then access and modify the original variables.


Syntax

void function_name(int *a, int *b);

Function call:

function_name(&x, &y);

Example of Call by Reference

#include <stdio.h>

void swap(int *a, int *b);

int main(void)
{
    int num1, num2;

    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    printf(
        "Before swapping: num1 = %d, num2 = %d\n",
        num1,
        num2
    );

    swap(&num1, &num2);

    printf(
        "After swapping: num1 = %d, num2 = %d\n",
        num1,
        num2
    );

    return 0;
}

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

    temp = *a;
    *a = *b;
    *b = temp;
}

Example Output

Enter two numbers: 10 20
Before swapping: num1 = 10, num2 = 20
After swapping: num1 = 20, num2 = 10

Difference Between Call by Value and Call by Reference

Call by ValueCall by Reference Using Pointers
A copy of the value is passed.The address of the variable is passed.
Separate values are used inside the function.The original variables can be accessed through pointers.
Changes inside the function do not affect original variables.Changes through pointers affect the original variables.
Normal variables are passed.Addresses are passed using the & operator.
Suitable when original values should remain unchanged.Suitable when the function needs to modify original values.

Recursive Function

A recursive function is a function that calls itself repeatedly until a specified stopping condition is satisfied.

The process in which a function calls itself is called recursion.

For recursion to work correctly:

  1. The function must call itself.
  2. It must contain a stopping or base condition.

Without a base condition, recursive calls may continue indefinitely.


Syntax of Recursive Function

return_type function_name(parameters)
{
    if (stopping_condition)
    {
        return value;
    }

    return function_name(modified_parameters);
}

Example: Factorial Using Recursion

The factorial of a positive integer is:

n! = n × (n - 1) × (n - 2) × ... × 1

For example:

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

Program

#include <stdio.h>

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

    return n * factorial(n - 1);
}

int main(void)
{
    int num;
    int fact;

    printf("Enter a number to find its factorial: ");
    scanf("%d", &num);

    fact = factorial(num);

    printf("Factorial of %d = %d\n", num, fact);

    return 0;
}

Example Output

Enter a number to find its factorial: 5
Factorial of 5 = 120

Working of Recursive Factorial

For:

factorial(5)

the recursive calls are:

factorial(5)
= 5 × factorial(4)

= 5 × 4 × factorial(3)

= 5 × 4 × 3 × factorial(2)

= 5 × 4 × 3 × 2 × factorial(1)

= 5 × 4 × 3 × 2 × 1 × factorial(0)

= 5 × 4 × 3 × 2 × 1 × 1

= 120

The following condition stops the recursion:

if (n == 0)
{
    return 1;
}

This is called the base condition.


Advantages of Functions

The major advantages of functions are:

  1. Code Reusability
    The same function can be called multiple times without rewriting the same code.
  2. Reduced Program Size
    Repeated operations can be placed inside a function, reducing unnecessary code.
  3. Easy Debugging
    Errors can be identified and corrected in individual functions.
  4. Easy Testing
    Individual functions can be tested separately.
  5. Better Readability
    A program divided into functions is easier to read and understand.
  6. Modularity
    A large program can be divided into smaller logical modules.
  7. Easy Maintenance
    Changes can be made to a particular function without rewriting the entire program.
  8. Teamwork
    Different programmers can work on different functions during program development.
  9. Faster Program Development
    Reusing existing functions can reduce development time.

Quick Revision

What is a Function?

A function is a block of code that performs a specific task and executes when it is called.

Main Aspects of a Function

  • Function Declaration
  • Function Definition
  • Function Call

Types of Functions

  • Library Function
  • User-Defined Function

Categories of User-Defined Functions

  • Arguments + Return Value
  • Arguments + No Return Value
  • No Arguments + Return Value
  • No Arguments + No Return Value

Function Declaration

int add(int, int);

Function Definition

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

Function Call

result = add(10, 20);

Call by Value

A copy of the value is passed to the function. Changes inside the function do not affect the original variable.

Call by Reference

The address of the variable is passed using pointers, allowing the function to modify the original value.

Recursion

Recursion occurs when a function calls itself. A recursive function must contain a base condition.


Important Exam Points

  • A function is a reusable block of code.
  • Every C program contains the main() function.
  • A function prototype tells the compiler about the function before it is used.
  • A function declaration ends with a semicolon.
  • A function definition contains the actual body of the function.
  • A function call executes the function.
  • Library functions are predefined.
  • User-defined functions are created by programmers.
  • User-defined functions can be divided into four categories based on arguments and return values.
  • void indicates that a function does not return a value.
  • Actual parameters are supplied during a function call.
  • Formal parameters receive those values in the function definition.
  • Call by value does not change the original variables.
  • Pointer-based parameter passing can modify original variables.
  • A recursive function calls itself.
  • Every recursive function should have a base condition.
  • Functions improve code reuse, readability, debugging, testing, and program organization.

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play