C Programming: Functions from Basics to Advanced
1. Introduction to Functions
Definition: A function is a block of code that performs a specific task.
Purpose: Helps in modular programming, code reuse, and better organization.
Types of Functions:
Built-in Functions: Provided by the C standard library (e.g., printf, scanf).
User-Defined Functions: Created by the programmer to perform specific tasks.
2. Structure of a Function
General Syntax:
return_type function_name(parameter_list)
{
// Function body
return value; // Optional
}
Example:
int add(int a, int b)
{
return a + b;
}
3. Declaring and Calling Functions
Function Declaration (Prototype):
return_type function_name(parameter_list);
Function Call:
result = function_name(arguments);
Example:
#include <stdio.h>
int add(int a, int b); // Function declaration
int main()
{
int sum = add(5, 3); // Function call
printf("Sum: %d", sum);
return 0;
}
int add(int a, int b) { // Function definition
return a + b;
}
4. Passing Parameters to Functions
a. Pass by Value
Definition: Copies the actual value of arguments into function parameters.
Example:
void display(int num)
{
printf("Number: %d", num);
}
b. Pass by Reference
Definition: Passes the address of arguments to the function, allowing modification
of original variables.
Example:
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
5. Types of User-Defined Functions
Functions with No Return Type and No Parameters
void greet()
{
printf("Hello, World!\n");
}
Functions with No Return Type but with Parameters
void printNumber(int num)
{
printf("Number: %d\n", num);
}
Functions with Return Type but No Parameters
int getFive() {
return 5;
}
Functions with Return Type and Parameters
int multiply(int a, int b) {
return a * b;
}
6. Recursion
Definition: A function that calls itself to solve a problem.
Types:
Direct Recursion
Indirect Recursion
Example (Factorial):
int factorial(int n)
{
if (n == 0) return 1;
return n * factorial(n - 1);
}
7. Inline Functions (Using Macros)
Inline functions are not supported directly in C but can be simulated using macros.
Example:
#define SQUARE(x) ((x) * (x))
printf("Square: %d", SQUARE(5));
8. Advanced Concepts in Functions
a. Function Pointers
Definition: A pointer that stores the address of a function.
Example:
void greet()
{
printf("Hello!\n");
}
int main()
{
void (*func_ptr)() = greet;
func_ptr();
return 0;
}
b. Callback Functions
Definition: A function that is passed as an argument to another function.
Example:
void executeCallback(void (*callback)())
{
callback();
}
c. Variadic Functions
Definition: Functions that accept a variable number of arguments.
Example:
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
9. Real-Time Examples and Logic Building
a. Prime Number Check
int isPrime(int num)
{
if (num < 2) return 0;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) return 0;
}
return 1;
}
b. Sorting Using Bubble Sort
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
c. Fibonacci Sequence
void fibonacci(int n)
{
int t1 = 0, t2 = 1, nextTerm;
for (int i = 1; i <= n; i++) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
}
10. Best Practices
Use meaningful names for functions to represent their purpose.
Keep functions short and focused on a single task.
Avoid global variables; prefer passing parameters.
Document functions with comments to improve readability.
11. Summary
Functions are essential for modular programming and code reusability.
Mastering recursion, function pointers, and advanced topics like callbacks is vital
for efficient programming.
Real-time examples and logic building enhance problem-solving skills in C
programming.
C Programming: Pointers from Basics to Advanced
1. Introduction to Pointers
Definition: A pointer is a variable that stores the address of another variable.
Purpose:
Provides dynamic memory management.
Enables efficient handling of arrays, strings, and structures.
Facilitates function parameter passing by reference.
2. Basics of Pointers
a. Declaration and Initialization
Syntax:
data_type *pointer_name;
Example:
int a = 10;
int *p = &a; // Pointer p stores the address of variable a
b. Pointer Operators
Address-of Operator (&): Fetches the address of a variable.
int a = 5;
int *p = &a; // p stores the address of a
Dereference Operator (*): Accesses the value at the address stored in the pointer.
printf("Value: %d", *p); // Prints 5
3. Pointer Arithmetic
Supported Operations:
Increment (p++) and Decrement (p--) move to the next and previous memory location
respectively.
Addition (p + n) and Subtraction (p - n) jump by n memory blocks.
Example:
int arr[3] = {10, 20, 30};
int *p = arr;
printf("%d", *(p + 1)); // Outputs 20
4. Pointers and Arrays
Relationship: The name of an array is a pointer to its first element.
int arr[3] = {10, 20, 30};
int *p = arr;
printf("%d", *p); // Outputs 10
Accessing Array Elements:
for (int i = 0; i < 3; i++) {
printf("%d ", *(p + i));
}
5. Pointers and Strings
Accessing Characters:
char str[] = "Hello";
char *p = str;
while (*p != '\0') {
printf("%c", *p);
p++;
}
String Manipulation:
void reverseString(char *str)
{
char *start = str, *end = str + strlen(str) - 1, temp;
while (start < end)
{
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
6. Dynamic Memory Allocation
Functions: malloc, calloc, realloc, and free (from <stdlib.h>).
Examples:
Allocating Memory:
int *p = (int *)malloc(5 * sizeof(int));
if (p == NULL) {
printf("Memory allocation failed");
}
Releasing Memory:
free(p);
7. Pointers and Functions
a. Passing Pointers to Functions
Enables modification of actual arguments.
Example:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
b. Returning Pointers from Functions
Be cautious about returning pointers to local variables.
Example:
int* createArray(int size) {
return (int *)malloc(size * sizeof(int));
}
8. Advanced Concepts
a. Pointer to Pointer
Definition: A pointer that stores the address of another pointer.
Example:
int a = 10;
int *p = &a;
int **pp = &p;
printf("Value: %d", **pp); // Outputs 10
b. Function Pointers
Definition: A pointer that points to a function.
Example:
void greet() {
printf("Hello, World!\n");
}
void (*func_ptr)() = greet;
func_ptr();
c. Array of Function Pointers
Example:
void add() { printf("Add\n"); }
void subtract() { printf("Subtract\n"); }
void (*operations[2])() = {add, subtract};
operations[0](); // Calls add
operations[1](); // Calls subtract
9. Real-Time Examples and Logic Building
a. Matrix Multiplication Using Pointers
void multiplyMatrices(int *a, int *b, int *result, int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
*(result + i * n + j) = 0;
for (int k = 0; k < n; k++) {
*(result + i * n + j) += *(a + i * n + k) * *(b + k * n + j);
}
}
}
}
b. Implementing Linked List
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert(Node **head, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
c. Memory Copy Function
void myMemCopy(void *dest, void *src, size_t size) {
char *d = dest;
char *s = src;
while (size--) {
*d++ = *s++;
}
}
10. Best Practices
Always initialize pointers to avoid undefined behavior.
Use NULL to check if a pointer is valid.
Free dynamically allocated memory to prevent memory leaks.
Avoid dangling pointers (pointers pointing to freed memory).
11. Summary
Pointers are a powerful feature in C programming that enable efficient memory and
data manipulation.
Mastering pointers is essential for advanced programming concepts like dynamic
memory, data structures, and system programming.
Logic building with pointers is crucial for solving real-world problems
efficiently.