0% found this document useful (0 votes)
13 views16 pages

Functions: What Is A Function? Block of Code Divide Code Reusability Readability Maintenance

Uploaded by

rockyyyy884
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views16 pages

Functions: What Is A Function? Block of Code Divide Code Reusability Readability Maintenance

Uploaded by

rockyyyy884
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Functions

What is a Function?
 A function is a block of code designed to perform a particular task.
 It helps to divide a large program into smaller, manageable parts.
 Functions improve code reusability, readability, and maintenance.

Advantages of Using Functions


 Code reusability — Write once, use multiple times.
 Makes program modular and organized.
 Easier to debug and test small code blocks.
 Avoids repetitive code.

Types of Functions

Type Description Example

Predefined functions provided by C printf(), scanf(),


Library Functions
standard library. strlen()

User-defined Functions written by the programmer to int add(int a, int


Functions perform specific tasks. b)

Function Syntax
return_type function_name(parameters) {
// Code to execute
return value; // (if return_type is not void)
}
 Return Type: Data type of the value returned (void if nothing is
returned).
 Function Name: Identifier for the function (follow C naming rules).
 Parameters: Input variables (optional)

Function Components

Componen
Description Example
t

Tells the compiler about the function's


Declaration int add(int a, int b);
existence (before main()).

int add(int a, int b)


Definition Implements the function's logic.
{ return a+b; }

Call Executes the function. sum = add(5, 3);

Parameters vs. Arguments


 Parameters: Variables in the function declaration.
void food(int param1, char param2); // param1, param2 are parameters
 Arguments: Actual values passed during a function call.
food(10, 'A'); // 10 and 'A' are arguments
return Statement
 Exits the function and sends a value back to the caller.
 Mandatory for non-void functions
int isEven(int num) {
if (num % 2 == 0)
return 1; // True
else
return 0; // False
}
Types of Functions

Type Description Example

No Return, No Takes no input, returns


void greet()
Args nothing.

Returns a value but takes no


Return, No Args int getRandom()
input.

No Return, With Takes input but returns void printSum(int a, int


Args nothing. b)

Takes input and returns a


Return with Args int multiply(int x, int y)
value.
#include <stdio.h>
// Function declaration (no arguments, no return)
void greet();
int main() {
// Calling the function without arguments
greet();
return 0;
}
// Function definition
void greet() {
printf("Hello! Welcome to C programming.\n");
printf("This function has no arguments and returns nothing.\n");
}
W A P Sum of two numbers with help of Function
#include <stdio.h>
void swap(int a, int b);
void swap(int a, int b) { // a, b are FORMAL ARGUMENTS
int temp = a;
a = b;
b = temp;
printf("Inside swap: a=%d, b=%d\n", a, b);
}
int main() {
int x = 10, y = 20;
swap(x, y); // x, y are ACTUAL ARGUMENTS
printf("In main: x=%d, y=%d\n", x, y);
return 0;
}

Feature Actual Arguments Formal Arguments

Variables in function Variables in function


Definition
CALL DEFINITION

Caller's function Local to called function


Scope
(e.g., main()) (e.g., swap())

Memory Original memory New memory locations


Location addresses (copies)

Exist until caller Destroyed when called


Lifetime
function ends function ends

Changes persist in Changes lost after


Modification
caller function exit
Write a C program using a function to reverse a given integer number.
#include <stdio.h>
// Function to reverse a number
int reverseNumber(int num);
int reverseNumber(int num) {
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num = num / 10;
}
return reversed;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
int reversed = reverseNumber(number);
printf("Reversed number: %d\n", reversed);
return 0;
}

Recursion
Recursion in C is a programming technique where a function calls itself within
its own definition. This allows for solving problems by breaking them down into
smaller, self-similar subproblems.
Base Case:
A recursive function must have a base case, which is a condition that stops the
recursion. Without it, the function would call itself indefinitely, leading to a
stack overflow error
Recursive Case:
The recursive step is where the function calls itself with a modified input,
moving closer to the base case.
Write a C program using a function to print factorial of a number.
#include <stdio.h>
int factorial(int n);
int factorial(int n) {
// Base case: when n is 0, return 1
if (n == 0) {
return 1;
} else {
// Recursive case:
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
printf("Factorial of %d = %d\n", num, factorial(num)); return 0;

}
Write a C program to find the greatest of three numbers by passing them as
an array to a function.
#include <stdio.h>
// Function to find the greatest number
int findGreatest(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max; }
int main() {
int numbers[3];
// Taking input from user
printf("Enter three numbers:\n");
for (int i = 0; i < 3; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Calling function
int greatest = findGreatest(numbers, 3);
// Output
printf("Greatest number is: %d\n", greatest); return 0;
}
C Program using Recursion to return nth Fibonacci number
#include <stdio.h>
// Function to return nth Fibonacci number
int fibonacci(int n);
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
Pointer
A pointer is a variable that stores the memory address of another variable. It
enables dynamic memory management and efficient data handling.

Syntax
datatype *pointer_name; // Declaration
pointer_name = &variable; // Initialization
Example
int a = 5;
int *ptr = &a; // ptr stores address of a

1. Null Pointer
 A pointer that is initialized to NULL.
 It does not point to any valid memory location.
int *ptr = NULL;
2. Dangling Pointer
 A pointer pointing to a memory location that has been freed/deleted.
int *ptr = (int *)malloc(sizeof(int));
free(ptr);
// Now ptr is dangling
3. Void Pointer (Generic Pointer)
 A pointer that can store the address of any data type.
 Cannot be dereferenced directly.
void *ptr;
int a = 10;
ptr = &a;
5. Wild Pointer
 A pointer that is declared but not initialized.
 It points to a random memory location.
6. Pointer to Pointer(Double pointer)
 Stores the address of another pointer.
int a = 5;
int *p = &a;
int **pp = &p;

Pointer Arithmetic
Pointer Arithmetic = Doing math operations on pointers (like +, -, ++, --) to
move through memory addresses.
But only limited operations are allowed on pointers in C:
 + (Addition)
 - (Subtraction)
 ++ (Increment)
 -- (Decrement)
 ptr2 - ptr1 (difference between two pointers)

Operation Meaning

ptr + n Move forward n elements

ptr - n Move backward n elements

ptr1 - ptr2 Distance (in elements) between them

ptr++ / ptr-- Move to next/prev element


W A P Sum of two numbers with help of Function
#include <stdio.h>
void swap(int a, int b);
void swap(int a, int b) { // a, b are FORMAL ARGUMENTS
int temp = a;
a = b;
b = temp;
printf("Inside swap: a=%d, b=%d\n", a, b);
}
int main() {
int x = 10, y = 20;
swap(x, y); // x, y are ACTUAL ARGUMENTS
printf("In main: x=%d, y=%d\n", x, y);
return 0;
}

Write a program to swap the two variable with the help of pointers.
#include <stdio.h>
void swap(int *x,int*y);
void swap(int *x,int*y){
int temp=*x;
*x=*y;
*y=temp;
}
int main() {
int a = 5;
int *x=&a;
int b=10;
int *y=&b;
printf("value of a before a = %d\n",a);
printf("value of a before b =%d\n",b);
swap(x,y);
printf("After swaping value of a= %d\n",a);
printf("After swaping value of b=%d",b);
return 0;
}
Feature Call by Value Call by Reference

Address (reference) of the


📤 What is passed? A copy of the actual value
variable

🔁 Changes affect ❌ No, changes don’t affect ✅ Yes, changes affect the
original? original value original value

📍 Parameters Separate memory is used Same memory (shared) is used

💽 Memory use More (due to copies) Less (uses same variable)

Safer – original data remains Risky – original data can be


🔐 Safe or risky?
unchanged modified

📌 Function
void func(int a) void func(int *a)
Declaration

When you want to modify the


🧠 Use case When you only need the value
original

Dynamic Memory Allocation (DMA)


Dynamic Memory Allocation means:
Allocating memory at runtime (during program execution) instead of compile
time.
It is useful when:
 You don’t know how much memory you need in advance
 You want to allocate memory based on user input

Function Purpose

malloc() Allocates memory block (uninitialized)

calloc() Allocates memory block (initialized to 0)

realloc() Re-allocates memory (resize)

free() Frees the dynamically allocated memory

Feature malloc() calloc()

Initialization ❌ Does not initialize ✅ Initializes to zero

Parameters One (total size in bytes) Two (no. of blocks, size per block)

Speed Slightly faster Slightly slower

When you don’t need zero When you need zero-initialized


Use
in it memory

Function Purpose Initialization Syntax Used in?

Allocates Initial
malloc() ❌ No malloc(size_in_bytes)
memory allocation

calloc() Allocates ✅ Yes (zero) calloc(num_elements, Initial


memory for
Function Purpose Initialization Syntax Used in?

array of
size_of_each) allocation
elements

Re-allocates
previously ❌ Preserves realloc(old_ptr, Resize
realloc()
allocated old data new_size) memory
memory

Frees
previously
free() — free(ptr) Deallocation
allocated
memory

You might also like