C Programming - Beginner to Brilliance / Functions in C

What is Function?

A function in C is a self-contained block of code that performs a specific task.

It can take input values (called parameters), perform computations, and optionally return a result.


🧠 Syntax of a Function:

return_type function_name(parameter_list) {
    // function body
    // optional return statement
}

🔍 Example:

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

You can call it from main() like:

int result = add(5, 3);  // result = 8

❓ Why Use Functions? – The Need for Functions

Purpose

Explanation

✅ Modularity

Break large programs into smaller, manageable parts

🔁 Reusability

Write once, use multiple times without rewriting code

🧪 Easier Testing

Each function can be tested separately (unit testing)

📚 Better Readability

Program becomes easier to understand, especially in large projects

🔄 Avoid Repetition

Common logic (like calculations or printing) can be reused with one call

🔄 Divide and Conquer

Complex logic can be broken into logical steps handled by different functions


🏗️ Types of Functions in C:

  1. Library Functions – Built-in (e.g., printf(), scanf(), sqrt())

  2. User-defined Functions – Created by the programmer for specific tasks


🧱 Function Structure in a C Program:

#include <stdio.h>

// Function Declaration
int square(int n);

// Main Function
int main() {
    int result = square(4);
    printf("Square = %d", result);
    return 0;
}

// Function Definition
int square(int n) {
    return n * n;
}

📌 Terminology:

Term

Meaning

Function Call

Invoking a function (e.g., square(4))

Parameters

Input values passed to a function

Arguments

Actual values used during function call

Return Value

Output/result that function sends back (optional)


🧮 Real-Life Analogy:

Think of a function like a coffee machine:

  • You give it inputs: water and coffee beans (parameters)

  • It processes them internally (function body)

  • You get output: coffee (return value)