C Functions – Full Explanation with example

C Functions – Full Explanation with example

πŸ”Ή What is a Function in C?

A function is a block of code that performs a specific task. In C, functions help to:

  • Break down complex programs into smaller, manageable parts.
  • Reuse code by calling the same function multiple times.
  • Improve readability and maintainability.

πŸ”Ή Types of Functions in C

  1. Library Functions
  • Built-in functions provided by C (e.g., printf(), scanf(), sqrt())
  • Defined in header files like stdio.h, math.h, etc.
  1. User-defined Functions
  • Created by the programmer to perform specific tasks.

πŸ”Ή Syntax of a User-defined Function

return_type function_name(parameter_list) {
    // body of the function
}

Example:

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

πŸ”Ή Components of a Function

ComponentDescription
Return typeType of value returned (e.g., int, void)
Function nameIdentifier name of the function
ParametersInput values (optional)
Function bodyCode block performing specific operations
Return statementSends result back to caller (optional)

πŸ”Ή Function Declaration / Prototype

Before using a function, you must declare it (unless defined before the main function).

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

πŸ”Ή Function Call

To execute a function, you need to call it using its name and pass arguments:

int result = add(5, 3);

πŸ”Ή Complete Example

Let’s see a complete C program using a user-defined function:

#include <stdio.h>

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

// Main function
int main() {
    int x = 10, y = 20, sum;

    sum = add(x, y);  // Function call

    printf("Sum = %d\n", sum);
    return 0;
}

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

πŸ’‘ Output:

Sum = 30

πŸ”Ή Categories of Functions Based on Arguments and Return Value

TypeDescription & Example
1. No arguments, no return valuevoid greet();
2. Arguments, no return valuevoid display(int);
3. No arguments, return valueint getValue();
4. Arguments and return valueint multiply(int, int);

πŸ”Ή Example: No Arguments, No Return Value

#include <stdio.h>

void greet() {
    printf("Hello! Welcome to C programming.\n");
}

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

πŸ”Ή Why Use Functions?

  • Modularity – Breaks large programs into smaller chunks.
  • Reusability – Same function can be used multiple times.
  • Easier testing – Each function can be tested independently.
  • Better organization – Code is cleaner and more readable.

If you want, I can also explain recursive functions, inline functions, or help you write functions for specific tasks like factorial, prime check, file handling, etc.

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *