pps module 4 assignment
pps module 4 assignment
Call by Value
In Call by Value, the actual value of the argument is copied into the formal parameter. Any
changes made to the formal parameter do not affect the actual argument.
Example:
int main() {
int a = 5, b = 10;
swap(a, b);
printf("%d %d", a, b); // Output: 5 10
return 0;
}
Call by Reference
In Call by Reference, the memory address of the actual argument is passed to the formal
parameter. Any changes made to the formal parameter affect the actual argument.
Example:
int main() {
int a = 5, b = 10;
swap(&a, &b);
printf("%d %d", a, b); // Output: 10 5
return 0;
}
malloc()
malloc() allocates a block of memory of specified size.
Example:
int *ptr;
ptr = (int *)malloc(sizeof(int));
*ptr = 10;
printf("%d", *ptr); // Output: 10
calloc()
calloc() allocates multiple blocks of memory of specified size.
Example:
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
ptr[0] = 10;
printf("%d", ptr[0]); // Output: 10
realloc()
realloc() changes the size of a memory block previously allocated.
Example:
int *ptr;
ptr = (int *)malloc(sizeof(int));
*ptr = 10;
ptr = (int *)realloc(ptr, 2 * sizeof(int));
ptr[1] = 20;
printf("%d %d", ptr[0], ptr[1]); // Output: 10 20
free()
free() releases a block of memory previously allocated.
Example:
int *ptr;
ptr = (int *)malloc(sizeof(int));
*ptr = 10;
free(ptr);
3. Recursive Function
A recursive function is a function that calls itself repeatedly until it reaches a base case.
#include <stdio.h>
int fibonacci(int n) {
if (n == 0 || n == 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Fibonacci number: %d", fibonacci(n));
return 0;
}
4. Functions in C
A function in C is a block of code that performs a specific task.
Function Declaration
Function declaration is the process of telling the compiler about the function's name, return
type, and parameters.
Example:
Function Definition
Function definition is the actual code that gets executed when the function is called.
Example:
Function Call
Function call is the process of invoking the function to perform its task.
Example:
5. Categorization of Functions in C
Functions in C can be categorized into:
1. Modularity: Functions help break down the code into smaller, manageable modules.
2. Reusability: Functions can be reused throughout the program, reducing code duplication.
3. Readability: Functions improve code readability by providing a clear and concise
description of the code's functionality.
4. Maintainability: Functions make it easier to modify and maintain the code.