Programming in C Unit-IV BCA Semester I
1
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Unit-IV: Pointers and User Defined Functions
Pointers in C
Definition:
• A pointer is a special variable that stores the memory address of another variable instead
of storing a direct value.
• Pointers are very powerful in C because they allow:
o Direct access to memory
o Efficient handling of arrays
o Dynamic memory allocation
o Function calls by reference (to modify actual values)
Syntax:
datatype *pointer_name;
• datatype → Specifies the type of value the pointer will point to (e.g., int, float, char).
• The symbol * → Indicates that the variable being declared is a pointer.
Declaring Pointers
To declare a pointer, we must specify the data type it will point to and use the symbol * before
the pointer name.
Examples:
int *p; // pointer to an integer
float *q; // pointer to a float
char *ch; // pointer to a character
Initializing Pointers:
Pointers must be assigned a valid memory address. This is done using the address-of operator
(&).
Programming in C Unit-IV BCA Semester I
2
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example:
int var = 10;
int *ptr1 = &var; // ptr1 now holds the address of variable 'var'
Accessing Address and Value Using Pointers:
1. Getting the Address of a Variable
int var = 10;
printf("Address of var: %pn", &var);
2. Accessing Value via Pointer (Dereferencing)
int var = 10;
int *ptr1 = &var;
printf("Value of var: %dn", *ptr1); // Output: 10
3. Accessing Address via Pointer
printf("Address stored in pointer ptr1: %pn", ptr1);
Programming in C Unit-IV BCA Semester I
3
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Demonstration of Pointers in C: Accessing and Modifying Variable Using Pointer
OUTPUT:
Programming in C Unit-IV BCA Semester I
4
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Pointer Arithmetic in C
Pointer arithmetic refers to performing operations on pointers to move across memory locations.
It is mainly used when working with arrays, dynamic memory, and structures.
Basic Pointer Arithmetic Operations
Operation Name Operation
Symbol
Description Example Code Output /
Result
Pointer
Increment
ptr++ Moves the pointer to
the next element
int arr[3]={10,20,30};
int *ptr=arr;
ptr++;
ptr → arr[1]
(value = 20)
Pointer
Decrement
ptr-- Moves the pointer to
the previous element
int arr[3]={10,20,30};
int *ptr=&arr[1];
ptr--;
ptr → arr[0]
(value = 10)
Addition of
Integer
ptr + n Moves pointer
forward by n
elements
int *ptr=arr;
ptr = ptr + 2;
ptr → arr[2]
(value = 30)
Subtraction of
Integer
ptr - n Moves pointer
backward by n
elements
int *ptr=&arr[2];
ptr = ptr - 1;
ptr → arr[1]
(value = 20)
Pointer
Subtraction
ptr1 - ptr2 Gives number of
elements between two
pointers (same array
only)
int *p1=&arr[2];
int *p2=&arr[0];
int diff = p1 - p2;
diff = 2
Pointer Addition
(Invalid)
ptr1 + ptr2 Adding two pointers is
not allowed
— Compilation
Error
Pointer
Multiplication
(Invalid)
ptr1 * ptr2 Multiplying pointers is
not allowed
— Compilation
Error
Notes:
1. Pointer arithmetic works based on data type size, not bytes.
Example:
int *p; // int = 4 bytes
p++; // moves 4 bytes ahead
Programming in C Unit-IV BCA Semester I
5
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
2. Adding an integer to a pointer is allowed; adding/multiplying two pointers is not
allowed.
Example:
p = p + 2; // valid
p = p + p; // invalid
p = p * p; // invalid
3. Subtracting two pointers gives distance in elements.
Example:
int arr[5];
int *p1 = &arr[3];
int *p2 = &arr[1];
int d = p1 - p2; // d = 2
4. Pointer multiplication is not allowed; multiply the integer before adding.
Example:
p = p + (3); // move 3 positions
Programming in C Unit-IV BCA Semester I
6
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example 1: Increment and Decrement
Example 2: Using ptr + n
• Adding an integer to a pointer
• We cannot add two pointers, but we can add an integer to a pointer.
ptr1 + ptr2; // ❌ Error
• When we do ptr + n, the pointer moves n elements forward, not n bytes.
Programming in C Unit-IV BCA Semester I
7
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example 3: Pointer Difference
Example 4: Pointer Scaling
• Direct multiplication of pointers is not allowed.
We cannot do ptr * n or ptr1 * ptr2 in C. // ❌ Error
• If we want to scale memory movement, we multiply an integer before adding to the
pointer:
ptr = base + (3 * n); // valid: moves 3*n elements ahead
Programming in C Unit-IV BCA Semester I
8
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Advantages of Pointers
1. Pointers save memory and time by passing addresses instead of copying data.
2. They are required for dynamic memory allocation using malloc(), calloc(), etc.
3. Pointers make array and string handling easier and faster.
4. They allow functions to modify values directly using pass-by-reference.
5. Pointers help in creating dynamic data structures like linked lists and trees.
6. They allow direct access to memory and hardware-level operations.
Disadvantages of Pointers
1. Pointer-based programs are harder to understand and debug.
2. Dangling pointers can cause crashes and unpredictable behavior.
3. Forgetting to free memory leads to memory leaks.
4. Incorrect pointer arithmetic may cause errors or segmentation faults.
5. Misuse of pointers can cause security issues like buffer overflows.
Applications of Pointers
1. Pointers are used for dynamic memory allocation using malloc(), calloc(), and free().
2. They are used to access and manipulate arrays and strings efficiently.
3. Pointers help in passing arguments by reference to functions.
4. They are essential for creating linked lists, stacks, queues, trees, and graphs.
5. Pointers are used in system programming to access hardware and memory locations
directly.
6. They are used for buffer management in files, networks, and I/O operations.
7. Function pointers are used to implement callbacks and event-driven programming.
8. Pointers support dynamic structures where size can grow or shrink at runtime.
Programming in C Unit-IV BCA Semester I
9
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Function in C
A function in C is a block of code that performs a specific task and can be called whenever
needed in a program.
• A function may take inputs (called parameters or arguments) and may return a value to
the calling function.
• Functions make a program modular, reusable, and easy to debug.
Types of Functions in C:
1. Predefined (Library) Functions:
o These functions are already provided by C.
o Examples: printf(), scanf(), sqrt(), strlen()
2. User-Defined Functions:
o These functions are created by the programmer to perform specific tasks.
o Example: A function to add two numbers(add(5, 10)), find factorial(fact()), display
a message(greet()), etc.
Syntax of a Function
return_type function_name(parameter_list)
{
// statements
return value; // used only if return_type is not void
}
• return_type → type of value returned
(Example: int, float, char, void — e.g., int add() returns an integer)
• function_name → name of the function
(Example: add(), display(), calculateSum())
• parameter_list → variables passed to the function (optional)
(Example: (int a, int b) in int add(int a, int b))
Programming in C Unit-IV BCA Semester I
10
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
User-Defined Functions
A user-defined function is a function written by the programmer to perform a custom task that is
not available in library functions.
Example: add(5, 10); →A function to calculate the sum of two numbers.
Need for User-Defined Functions
1. They break the program into small, manageable modules (modularity).
2. They allow the same code to be used many times without rewriting (reusability).
3. They make debugging and maintenance easier.
4. They improve the readability and clarity of the program.
5. They reduce repetition by replacing repeated code with function calls.
Structure of a User-Defined Function in C
A user-defined function typically consists of three parts:
Programming in C Unit-IV BCA Semester I
11
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
1.Function Declaration (Prototype)
Tells the compiler about the function name, return type, and parameters before its actual
definition.
Syntax:
return_type function_name(datatype arg1, datatype arg2, ...);
Example:
int add(int a, int b); // Function prototype
2.Function Definition
Contains the actual body of the function where the actual code that performs the task.
Syntax:
return_type function_name(datatype arg1, datatype arg2, ...)
{
// body of the function
return value;
}
Example:
int add(int a, int b)
{
int sum = a + b; // calculate sum
return sum; // return sum to the calling function
}
3. Function Call
It is used to invoke the function from main() or another function.
Syntax:
variable = function_name(value1, value2,…);
Example:
int result;
result = add(num1, num2); // calling the add() function
Programming in C Unit-IV BCA Semester I
12
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Categories of User-Defined Functions
User-defined functions in C can be classified into 4 types based on parameters and return type:
1. Function with Arguments and Return Value
(Takes parameters and returns a value) [int result = add (5, 10);]
2.Function with No Arguments but Return Value
(Takes parameters but does not return a value) [int result = add ();]
3. Function with Arguments but No Return Value (Void Function)
(Does not take parameters but returns a value) [ add (5, 10);]
4. Function with No Arguments and No Return Value (Void Function)
(Does not take parameters and does not return a value) [ add ();]
1. Function with Arguments and Return Value
• This type of user-defined function accepts arguments (inputs) from the calling function
and returns a value (output) back to the caller.
• It is the most commonly used function type in C because it allows data to be passed into
the function and the result to be reused in different parts of the program.
Example Program
Programming in C Unit-IV BCA Semester I
13
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
2. Function with No Arguments but Return Value
This type of function does not take any arguments from the calling function, but it returns a
value to the caller.
• The input values (operands) are usually taken inside the function itself.
• The computed result is then sent back to the main() function using the return statement.
• Useful when you don’t want to pass arguments every time, but still need the result for
further use.
Example Program
3. Function with Arguments but No Return Value (Void Function)
This type of function takes arguments (inputs) from the calling function but does not return
any value.
• Since it does not return a value, its return type is always void.
• Useful when the function only performs an action (like displaying, printing, or updating)
instead of sending results back.
Programming in C Unit-IV BCA Semester I
14
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example Program
4. Function with No Arguments and No Return Value (Void Function)
This type of function does not take any input (arguments) and does not return any value.
• Its return type is void.
• It is generally used when the function performs a task internally, such as reading input,
performing calculations, and displaying the output, without needing to return a result.
Example Program
Programming in C Unit-IV BCA Semester I
15
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Function Call
Function calling is the process of invoking a function by its name, passing required arguments
if any, so that the function executes its defined operations and returns control to the caller.
Example of Function Calling
int main()
{
// Function call
sum = add(num1, num2);
return 0;
}
Function Call Methods
In C programming, functions can be called in two main ways depending on how the arguments
are passed to the function:
1. Call by Value
2. Call by Reference
Both methods determine whether the changes made to function parameters affect the original
variables in the calling function.
Programming in C Unit-IV BCA Semester I
16
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
1. Call by Value/Name
Definition:
Call by Value is a function calling method in which a copy of the actual argument is passed to
the function. Changes made inside the function do not affect the original variable.
• In Call by Value, the function works with a duplicate of the original data.
• Used when you do not want the original value to change.
• Safer because the original data remains unaltered.
• Slower for large data because copies are made.
Example 1: Swapping Two Numbers Using Call by Value
Sample Output:
Programming in C Unit-IV BCA Semester I
17
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example 2: Adding Two Numbers Using Call by Value
Sample Output:
Observation:
• num1 and num2 remain unchanged because only copies were passed.
Advantages of Call by Value:
1. Original data is safe from accidental modification.
2. Easy to implement and understand.
3. Useful for small data types (int, float, char).
Programming in C Unit-IV BCA Semester I
18
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Disadvantages of Call by Value:
1. Slower for large data types (arrays, structures) due to copying.
2. Cannot modify the original variable inside the function.
3. Extra memory may be used for copies of large data.
2. Call by Reference
Definition:
Call by Reference is a function calling method in which the address of the actual argument is
passed. Changes made inside the function directly affect the original variables.
• In Call by Reference, the function works with the original data using its address.
• Efficient for large data because no copying is required.
• Useful when the function needs to modify the original variable.
Example 1: Swapping Two Numbers Using Call by Reference
Programming in C Unit-IV BCA Semester I
19
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Sample Output:
Observation:
• Values of num1 and num2 are swapped because their addresses were passed to the
function.
Example 2: Adding Two Numbers Using Call by Reference
Sample Output:
Programming in C Unit-IV BCA Semester I
20
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Advantages of Call by Reference
1. Modifies original data: Changes made inside the function affect the actual variable.
2. Efficient for large data: No need to copy large data structures, saving memory and time.
3. Useful for multiple outputs: A function can return multiple results using references.
4. Memory efficient: Only addresses are passed, not entire data.
Disadvantages of Call by Reference
1. Changes original data: Accidental changes to the original variable can occur.
2. Harder to debug: Errors may be difficult to trace because the function modifies original
variables.
3. Security risk: Passing sensitive data by reference can be risky if the function alters it
unintentionally.
4. Pointers required: Implementation uses pointers, which may be confusing for beginners.
Comparison of Call by Value and Call by Reference
Call by Value Call by Reference
1. Passes a copy of the variable to the function.
void swap(int num1, int num2)
1. Passes the address of the variable to the function.
void swap(int *num1, int *num2)
2. Changes inside the function do not affect the
original variable.
2. Changes inside the function affect the original
variable.
3. Uses extra memory because a copy of the
variable is created.
3. More memory-efficient, no copying required.
4. Safer; original data cannot be accidentally
changed.
4. Slightly risky; pointers must be used carefully.
5. Simple to implement and understand. 5. Slightly more complex due to pointer usage.
6.Example: Swapping
num1=5, num2=7 → After function:
num1=5, num2=7
6. Example: Swapping
num1=5, num2=7 → After function:
num1=7, num2=5
7. Use when original data should not change. 7. Use when function needs to modify original data.
*** *** ***

C UNIT-IV Pointers and User Defined Functions

  • 1.
    Programming in CUnit-IV BCA Semester I 1 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Unit-IV: Pointers and User Defined Functions Pointers in C Definition: • A pointer is a special variable that stores the memory address of another variable instead of storing a direct value. • Pointers are very powerful in C because they allow: o Direct access to memory o Efficient handling of arrays o Dynamic memory allocation o Function calls by reference (to modify actual values) Syntax: datatype *pointer_name; • datatype → Specifies the type of value the pointer will point to (e.g., int, float, char). • The symbol * → Indicates that the variable being declared is a pointer. Declaring Pointers To declare a pointer, we must specify the data type it will point to and use the symbol * before the pointer name. Examples: int *p; // pointer to an integer float *q; // pointer to a float char *ch; // pointer to a character Initializing Pointers: Pointers must be assigned a valid memory address. This is done using the address-of operator (&).
  • 2.
    Programming in CUnit-IV BCA Semester I 2 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example: int var = 10; int *ptr1 = &var; // ptr1 now holds the address of variable 'var' Accessing Address and Value Using Pointers: 1. Getting the Address of a Variable int var = 10; printf("Address of var: %pn", &var); 2. Accessing Value via Pointer (Dereferencing) int var = 10; int *ptr1 = &var; printf("Value of var: %dn", *ptr1); // Output: 10 3. Accessing Address via Pointer printf("Address stored in pointer ptr1: %pn", ptr1);
  • 3.
    Programming in CUnit-IV BCA Semester I 3 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Demonstration of Pointers in C: Accessing and Modifying Variable Using Pointer OUTPUT:
  • 4.
    Programming in CUnit-IV BCA Semester I 4 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Pointer Arithmetic in C Pointer arithmetic refers to performing operations on pointers to move across memory locations. It is mainly used when working with arrays, dynamic memory, and structures. Basic Pointer Arithmetic Operations Operation Name Operation Symbol Description Example Code Output / Result Pointer Increment ptr++ Moves the pointer to the next element int arr[3]={10,20,30}; int *ptr=arr; ptr++; ptr → arr[1] (value = 20) Pointer Decrement ptr-- Moves the pointer to the previous element int arr[3]={10,20,30}; int *ptr=&arr[1]; ptr--; ptr → arr[0] (value = 10) Addition of Integer ptr + n Moves pointer forward by n elements int *ptr=arr; ptr = ptr + 2; ptr → arr[2] (value = 30) Subtraction of Integer ptr - n Moves pointer backward by n elements int *ptr=&arr[2]; ptr = ptr - 1; ptr → arr[1] (value = 20) Pointer Subtraction ptr1 - ptr2 Gives number of elements between two pointers (same array only) int *p1=&arr[2]; int *p2=&arr[0]; int diff = p1 - p2; diff = 2 Pointer Addition (Invalid) ptr1 + ptr2 Adding two pointers is not allowed — Compilation Error Pointer Multiplication (Invalid) ptr1 * ptr2 Multiplying pointers is not allowed — Compilation Error Notes: 1. Pointer arithmetic works based on data type size, not bytes. Example: int *p; // int = 4 bytes p++; // moves 4 bytes ahead
  • 5.
    Programming in CUnit-IV BCA Semester I 5 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 2. Adding an integer to a pointer is allowed; adding/multiplying two pointers is not allowed. Example: p = p + 2; // valid p = p + p; // invalid p = p * p; // invalid 3. Subtracting two pointers gives distance in elements. Example: int arr[5]; int *p1 = &arr[3]; int *p2 = &arr[1]; int d = p1 - p2; // d = 2 4. Pointer multiplication is not allowed; multiply the integer before adding. Example: p = p + (3); // move 3 positions
  • 6.
    Programming in CUnit-IV BCA Semester I 6 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example 1: Increment and Decrement Example 2: Using ptr + n • Adding an integer to a pointer • We cannot add two pointers, but we can add an integer to a pointer. ptr1 + ptr2; // ❌ Error • When we do ptr + n, the pointer moves n elements forward, not n bytes.
  • 7.
    Programming in CUnit-IV BCA Semester I 7 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example 3: Pointer Difference Example 4: Pointer Scaling • Direct multiplication of pointers is not allowed. We cannot do ptr * n or ptr1 * ptr2 in C. // ❌ Error • If we want to scale memory movement, we multiply an integer before adding to the pointer: ptr = base + (3 * n); // valid: moves 3*n elements ahead
  • 8.
    Programming in CUnit-IV BCA Semester I 8 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Advantages of Pointers 1. Pointers save memory and time by passing addresses instead of copying data. 2. They are required for dynamic memory allocation using malloc(), calloc(), etc. 3. Pointers make array and string handling easier and faster. 4. They allow functions to modify values directly using pass-by-reference. 5. Pointers help in creating dynamic data structures like linked lists and trees. 6. They allow direct access to memory and hardware-level operations. Disadvantages of Pointers 1. Pointer-based programs are harder to understand and debug. 2. Dangling pointers can cause crashes and unpredictable behavior. 3. Forgetting to free memory leads to memory leaks. 4. Incorrect pointer arithmetic may cause errors or segmentation faults. 5. Misuse of pointers can cause security issues like buffer overflows. Applications of Pointers 1. Pointers are used for dynamic memory allocation using malloc(), calloc(), and free(). 2. They are used to access and manipulate arrays and strings efficiently. 3. Pointers help in passing arguments by reference to functions. 4. They are essential for creating linked lists, stacks, queues, trees, and graphs. 5. Pointers are used in system programming to access hardware and memory locations directly. 6. They are used for buffer management in files, networks, and I/O operations. 7. Function pointers are used to implement callbacks and event-driven programming. 8. Pointers support dynamic structures where size can grow or shrink at runtime.
  • 9.
    Programming in CUnit-IV BCA Semester I 9 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Function in C A function in C is a block of code that performs a specific task and can be called whenever needed in a program. • A function may take inputs (called parameters or arguments) and may return a value to the calling function. • Functions make a program modular, reusable, and easy to debug. Types of Functions in C: 1. Predefined (Library) Functions: o These functions are already provided by C. o Examples: printf(), scanf(), sqrt(), strlen() 2. User-Defined Functions: o These functions are created by the programmer to perform specific tasks. o Example: A function to add two numbers(add(5, 10)), find factorial(fact()), display a message(greet()), etc. Syntax of a Function return_type function_name(parameter_list) { // statements return value; // used only if return_type is not void } • return_type → type of value returned (Example: int, float, char, void — e.g., int add() returns an integer) • function_name → name of the function (Example: add(), display(), calculateSum()) • parameter_list → variables passed to the function (optional) (Example: (int a, int b) in int add(int a, int b))
  • 10.
    Programming in CUnit-IV BCA Semester I 10 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca User-Defined Functions A user-defined function is a function written by the programmer to perform a custom task that is not available in library functions. Example: add(5, 10); →A function to calculate the sum of two numbers. Need for User-Defined Functions 1. They break the program into small, manageable modules (modularity). 2. They allow the same code to be used many times without rewriting (reusability). 3. They make debugging and maintenance easier. 4. They improve the readability and clarity of the program. 5. They reduce repetition by replacing repeated code with function calls. Structure of a User-Defined Function in C A user-defined function typically consists of three parts:
  • 11.
    Programming in CUnit-IV BCA Semester I 11 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 1.Function Declaration (Prototype) Tells the compiler about the function name, return type, and parameters before its actual definition. Syntax: return_type function_name(datatype arg1, datatype arg2, ...); Example: int add(int a, int b); // Function prototype 2.Function Definition Contains the actual body of the function where the actual code that performs the task. Syntax: return_type function_name(datatype arg1, datatype arg2, ...) { // body of the function return value; } Example: int add(int a, int b) { int sum = a + b; // calculate sum return sum; // return sum to the calling function } 3. Function Call It is used to invoke the function from main() or another function. Syntax: variable = function_name(value1, value2,…); Example: int result; result = add(num1, num2); // calling the add() function
  • 12.
    Programming in CUnit-IV BCA Semester I 12 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Categories of User-Defined Functions User-defined functions in C can be classified into 4 types based on parameters and return type: 1. Function with Arguments and Return Value (Takes parameters and returns a value) [int result = add (5, 10);] 2.Function with No Arguments but Return Value (Takes parameters but does not return a value) [int result = add ();] 3. Function with Arguments but No Return Value (Void Function) (Does not take parameters but returns a value) [ add (5, 10);] 4. Function with No Arguments and No Return Value (Void Function) (Does not take parameters and does not return a value) [ add ();] 1. Function with Arguments and Return Value • This type of user-defined function accepts arguments (inputs) from the calling function and returns a value (output) back to the caller. • It is the most commonly used function type in C because it allows data to be passed into the function and the result to be reused in different parts of the program. Example Program
  • 13.
    Programming in CUnit-IV BCA Semester I 13 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 2. Function with No Arguments but Return Value This type of function does not take any arguments from the calling function, but it returns a value to the caller. • The input values (operands) are usually taken inside the function itself. • The computed result is then sent back to the main() function using the return statement. • Useful when you don’t want to pass arguments every time, but still need the result for further use. Example Program 3. Function with Arguments but No Return Value (Void Function) This type of function takes arguments (inputs) from the calling function but does not return any value. • Since it does not return a value, its return type is always void. • Useful when the function only performs an action (like displaying, printing, or updating) instead of sending results back.
  • 14.
    Programming in CUnit-IV BCA Semester I 14 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example Program 4. Function with No Arguments and No Return Value (Void Function) This type of function does not take any input (arguments) and does not return any value. • Its return type is void. • It is generally used when the function performs a task internally, such as reading input, performing calculations, and displaying the output, without needing to return a result. Example Program
  • 15.
    Programming in CUnit-IV BCA Semester I 15 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Function Call Function calling is the process of invoking a function by its name, passing required arguments if any, so that the function executes its defined operations and returns control to the caller. Example of Function Calling int main() { // Function call sum = add(num1, num2); return 0; } Function Call Methods In C programming, functions can be called in two main ways depending on how the arguments are passed to the function: 1. Call by Value 2. Call by Reference Both methods determine whether the changes made to function parameters affect the original variables in the calling function.
  • 16.
    Programming in CUnit-IV BCA Semester I 16 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 1. Call by Value/Name Definition: Call by Value is a function calling method in which a copy of the actual argument is passed to the function. Changes made inside the function do not affect the original variable. • In Call by Value, the function works with a duplicate of the original data. • Used when you do not want the original value to change. • Safer because the original data remains unaltered. • Slower for large data because copies are made. Example 1: Swapping Two Numbers Using Call by Value Sample Output:
  • 17.
    Programming in CUnit-IV BCA Semester I 17 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example 2: Adding Two Numbers Using Call by Value Sample Output: Observation: • num1 and num2 remain unchanged because only copies were passed. Advantages of Call by Value: 1. Original data is safe from accidental modification. 2. Easy to implement and understand. 3. Useful for small data types (int, float, char).
  • 18.
    Programming in CUnit-IV BCA Semester I 18 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Disadvantages of Call by Value: 1. Slower for large data types (arrays, structures) due to copying. 2. Cannot modify the original variable inside the function. 3. Extra memory may be used for copies of large data. 2. Call by Reference Definition: Call by Reference is a function calling method in which the address of the actual argument is passed. Changes made inside the function directly affect the original variables. • In Call by Reference, the function works with the original data using its address. • Efficient for large data because no copying is required. • Useful when the function needs to modify the original variable. Example 1: Swapping Two Numbers Using Call by Reference
  • 19.
    Programming in CUnit-IV BCA Semester I 19 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Sample Output: Observation: • Values of num1 and num2 are swapped because their addresses were passed to the function. Example 2: Adding Two Numbers Using Call by Reference Sample Output:
  • 20.
    Programming in CUnit-IV BCA Semester I 20 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Advantages of Call by Reference 1. Modifies original data: Changes made inside the function affect the actual variable. 2. Efficient for large data: No need to copy large data structures, saving memory and time. 3. Useful for multiple outputs: A function can return multiple results using references. 4. Memory efficient: Only addresses are passed, not entire data. Disadvantages of Call by Reference 1. Changes original data: Accidental changes to the original variable can occur. 2. Harder to debug: Errors may be difficult to trace because the function modifies original variables. 3. Security risk: Passing sensitive data by reference can be risky if the function alters it unintentionally. 4. Pointers required: Implementation uses pointers, which may be confusing for beginners. Comparison of Call by Value and Call by Reference Call by Value Call by Reference 1. Passes a copy of the variable to the function. void swap(int num1, int num2) 1. Passes the address of the variable to the function. void swap(int *num1, int *num2) 2. Changes inside the function do not affect the original variable. 2. Changes inside the function affect the original variable. 3. Uses extra memory because a copy of the variable is created. 3. More memory-efficient, no copying required. 4. Safer; original data cannot be accidentally changed. 4. Slightly risky; pointers must be used carefully. 5. Simple to implement and understand. 5. Slightly more complex due to pointer usage. 6.Example: Swapping num1=5, num2=7 → After function: num1=5, num2=7 6. Example: Swapping num1=5, num2=7 → After function: num1=7, num2=5 7. Use when original data should not change. 7. Use when function needs to modify original data. *** *** ***