FOC Unit 3: Function

 

Functions in C Programming

A function in C is a block of code that performs a specific task.
It helps in code reusability, modularity, and makes programs easy to understand.


Why use functions?

To avoid repeating the same code.

To make code cleaner and organized.

To divide large programs into smaller parts.

Types of Functions

There are mainly two types:

  1.  Library Functions:

Already available in C libraries.


Examples:

printf()

scanf()

sqrt()

2. User-Defined Functions

Functions created by the programmer.

Function Syntax

return_type function_name(parameter_list) { // code to be executed }

Function Example (Simple Addition)

#include <stdio.h> int add(int a, int b) { // function definition return a + b; } int main() { int result = add(5, 10); // function call printf("Result = %d", result); return 0; }

Output:

Result = 15


Parts of a Function

  1. Function Declaration (Prototype)
Tells the compiler about the function name, return type, and parameters.
int add(int, int);

    2. Function Definition

Actual body of the function.


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

    3. Function Call

 

Used to use/execute the function.


add(5, 10);


Types Based on Input/Output

1. Without arguments and without return

void greet() { printf("Hello!"); }

2. With arguments but no return

void square(int x) { printf("%d", x * x); }

3. Without arguments but with return

int getNumber() { return 10; }

4. With arguments and return (Most common)

int multiply(int a, int b) { return a * b; }

Example: Function to Find Factorial

#include <stdio.h> int factorial(int n) { int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } int main() { int num = 5; printf("Factorial = %d", factorial(num)); return 0; }

Benefits of Functions

  1. Reduces code duplication
  2. Makes debugging easier
  3. Allows team collaboration
  4. Helps in modular programming

Post a Comment

0 Comments