A function in C is a block of code that performs a specific task. Functions help make programs easier to understand, reuse, and maintain. Instead of writing the same code multiple times, you can write it once in a function and call it whenever needed.

Advantages of Functions

  • Reduces code duplication.
  • Makes programs modular.
  • Improves readability and maintainability.
  • Simplifies debugging and testing.
  • Allows code reuse.

Types of Functions in C

  1. Library Functions – Predefined functions provided by C libraries.
    • Examples: printf(), scanf(), sqrt(), strlen()
  2. User-Defined Functions – Functions created by the programmer.

Components of a Function

  1. Function Declaration (Prototype)
    • int add(int, int);
  2. Function Definition
    • int add(int a, int b)
      {
      return a + b;
      }
  3. Function Call
    • sum = add(10, 20);

Syntax of a Function

return_type function_name(parameter_list)
{
    // Statements
    return value;
}

Example Program

#include <stdio.h>

// Function declaration
int add(int, int);

int main()
{
    int a = 10, b = 20, result;

    // Function call
    result = add(a, b);

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

    return 0;
}

// Function definition
int add(int x, int y)
{
    return x + y;
}

Output

Sum = 30

Explanation

  • int add(int, int); is the function declaration.
  • add(a, b) is the function call from main().
  • The function receives a and b as arguments.
  • It adds them and returns the result to main().
  • printf() displays the returned value.

Categories of User-Defined Functions

1. Function with No Arguments and No Return Value

#include <stdio.h>

void message()
{
    printf("Welcome to C Programming");
}

int main()
{
    message();
    return 0;
}

2. Function with Arguments but No Return Value

#include <stdio.h>

void display(int n)
{
    printf("Number = %d", n);
}

int main()
{
    display(100);
    return 0;
}

3. Function with Arguments and Return Value

#include <stdio.h>

int square(int n)
{
    return n * n;
}

int main()
{
    int result = square(5);
    printf("Square = %d", result);
    return 0;
}

Output

Square = 25

4. Function with No Arguments but Return Value

#include <stdio.h>

int getNumber()
{
    return 50;
}

int main()
{
    int n = getNumber();
    printf("Number = %d", n);
    return 0;
}

Output

Number = 50

Summary

  • A function is a reusable block of code that performs a specific task.
  • Functions improve modularity, readability, and code reuse.
  • Every function consists of a declaration, definition, and function call.
  • User-defined functions can be classified into four categories based on the presence or absence of arguments and return values.