Major Module 3 + Questions
Major Module 3 + Questions
Advantage of functions
1) Code Reusability
By creating functions in C, you can call it many times. So we don't need to write the
same code
2) Code optimization
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc. You just need to include appropriate
header files to use these functions. These are already declared and defined in C
libraries.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces complexity of a big program and optimizes
the code. Depending upon the complexity and requirement of the program, you can create
In order to write an efficient user defined function, the programmer must familiar with the
2 : Function Call.
3 : Function Definition
Syntax
return_type function_name(parameter/argument);
return_type function-name();
Ex :
void add();
When we call any function control goes to function body and execute entire code.
Syntax :
function-name();
function-name(parameter/argument);
Ex :
Defining a function.
Defining of function is nothing but give body of function that means write logic inside function
body.
Syntax
declaration of variables;
Eg: 1
int z;
z = x + y;
return z
Ex 2
return ( x + y );
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside
Example:
#include <stdio.h>
int main()
int n1,n2,sum;
scanf("%d %d",&n1,&n2);
printf("sum = %d",sum);
return 0;
int result;
result = a+b;
or
Example
return a;
return (a+b);
The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement.
parameters provides the data communication between the calling function and called function.
1 : Actual parameters.
2 : Formal parameters.
1 : Actual Parameters : These are the parameters transferred from the calling function (main
2 : Formal Parameters :These are the parameters transferred into the calling function (main
Ex :
main()
{ }
Praveen Kumar P K, UIT Kollam
Where
1 : Actual parameters are used in calling 1 : Formal parameters are used in the function
function when a function is invoked. header of a called function.
Ex : c=add(a,b); Here a,b are actual Ex : int add(int m,int n); Here m,n are called
parameters. formal parameters.
3 : Actual parameters sends values to the 3 : Formal parametes receive values from the
formal parameters. actual parametes.
4 : Address of actual parameters can be sent 4 : Address of actual parameters can be sent
to formal parameters to formal parameters
In this category, there is no data transfer between the calling function and called function.
But there is flow of control from calling function to the called function.
When no parameters are there , the function cannot receive any value from the calling function.
When the function does not return a value, the calling function cannot receive any value from the
called function
#include<conio.h>
void main()
sum(); //Calling
getch();
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
printf("sum=%d",c);
In this category, there is no data transfer between the calling function and called function.
But there is data transfer from called function to the calling function.
When no parameters are there , the function cannot receive any values from the calling function.
When the function returns a value, the calling function receives one value from the called function
Example
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
c=sum(); //Calling
printf("sum=%d",c);
getch();
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
return c;
In this category, there is data transfer from the calling function to the called function using
parameters.
But there is no data transfer from called function to the calling function.
When parameters are there , the function can receive any values from the calling function.
When the function does not return a value, the calling function cannot receive any value from
Example
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
scanf("%d%d",&m,&n);
sum(m,n);
getch();
int c;
c=a+b;
printf("sum=%d",c);
• In this category, there is data transfer from the calling function to the called function
using parameters.
• But there is no data transfer from called function to the calling function.
• When parameters are there , the function can receive any values from the calling function.
• When the function returns a value, the calling function receive a value from the called
• function.
Example
#include<stdio.h>
#include<conio.h>
void main()
int m,n,c;
clrscr();
c=sum(m,n);
printf("sum=%d",c);
getch();
int c;
c=a+b;
return c;
Example
#include <stdio.h>
int main() {
result = calculateSum(num);
return 0;
sum += num[i];
return sum;
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(num);
... ..
This informs the compiler that you are passing a one-dimensional array to the function.
To pass multidimensional arrays to a function, only the name of the array is passed to the
function (similar to one-dimensional arrays).
Example
#include <stdio.h>
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0;
printf("Displaying:\n");
printf("%d\n", num[i][j]);
}
Praveen Kumar P K, UIT Kollam
}
Output
Enter 4 numbers:
Displaying:
Notice the parameter int num[2][2] in the function prototype and function definition:
// function prototype
This signifies that the function takes a two-dimensional array as an argument. We can also pass
arrays with more than 2 dimensions as a function argument.
When passing two-dimensional arrays, it is not mandatory to specify the number of rows in the
array. However, the number of columns should always be specified.
For example,
// code
Definition:
Pointer is a variable that stores/hold address of another variable of same data type/ t is
also known as locator or indicator that points to an address of a value. A pointer is a derived
data type in C
Declaration of Pointer
Example: int* p;
Note: void type pointer works with all data types, but isn't used often.
int a = 10 ;
or
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch (ptr type is integer and a type is float)
& is called reference operator. It gives you the address of a variable. There is another
operator that gets you the value from the address, it is called a dereference operator (*).
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable,
int a,*p;
a = 10;
p = &a;
• Normal variable stores the value whereas pointer variable stores the address of the
variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these
two pointers.
Example
#include <stdio.h>
int main()
int *p;
p= &var;
Output:
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you can assign
NULL value.
Or
It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
int *p=NULL;
Pointers to Pointers
Pointers can point to other pointers /pointer refers to the address of another pointer.
int **p2;
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
clrscr();
p2=&p;
Output
Value of *p variable is 50
Original value is not modified in call by value but it is modified in call by reference.
The called function receives the information from the calling function through the
parameters.
The variables used while invoking the calling function are called actual parameters and the
variables used in the function header of the called function are called formal parameters.
When a function is called with actual parameters, the values of actual parameters are
copied into formal parameters. If the values of the formal parametes changes in the
function, the values of the actual parameters are not changed. This way of passing
parameters is called pass by value or call by value.
#include <stdio.h>
int main()
int a = 10;
int b = 20;
int temp;
temp = a;
a=b;
b=temp;
Output
#include <stdio.h>
int main()
int a = 10;
int b = 20;
swap(&a,&b);
int temp;
temp = *a;
*a=*b;
*b=temp;
Output
A copy of the value is passed into the An address of value is passed into the
function function
Changes made inside the function is limited Changes made inside the function validate
to the function only. The values of the outside of the function also. The values of
actual parameters do not change by the actual parameters do change by
changing the formal parameters. changing the formal parameters.
Actual and formal arguments are created at Actual and formal arguments are created
the different memory location at the same memory location
When function is called within the same function, it is known as recursion in C. The function
which calls the same function, is known as recursive function.
Features :
Advantages :
• It is easy to use.
• It represents compact programming structures.
Disadvantages :
• It is slower than that of looping statements because each time function is called.
While using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop. Recursive functions are very useful to solve
many mathematical problems, such as calculating the factorial of a number, generating
Fibonacci series, etc
Example of recursion.
recursionfunction()
#include <stdio.h>
int main() {
scanf("%d", &number);
result = sum(number);
return 0;
int sum(int n) {
if (n != 0)
return n + sum(n-1);
else
return n;
Output
sum = 6
Initially, the sum() is called from the main() function with number passed as an argument. Suppose,
the value of n inside sum() is 3 initially. During the next function call, 2 is passed to the sum()
function. This process continues until n is equal to [Link] n is equal to 0, the if condition fails
and the else part is executed returning the sum of integers ultimately to the main() function.
#include<stdio.h>
long factorial(int n)
if (n == 0)
return 1;
else
return(n * factorial(n-1));
void main()
int number;
long fact;
scanf("%d", &number);
fact = factorial(number);
return 0;
Output
Enter a number: 6
#include <stdio.h>
int fact = 1, i;
fact *= i;
return fact;
int main()
int N = 5;
return 0;
Output
Factorial of 5 is 120
As you know, an array is a collection of a fixed number of values. Once the size of an array
is declared, you cannot change it.
Sometimes the size of the array you declared may be insufficient. To solve this issue, you
can allocate memory manually during run-time. This is known as dynamic memory allocation
in C programming.
To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and
free() are used. These functions are defined in the <stdlib.h> header file.
malloc()
The malloc() function reserves a block of memory of the specified number of bytes. And,
it returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
Example
The above statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.
C calloc()
The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
Example:
The above statement allocates contiguous space in memory for 25 elements of type float.
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on
their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
#include <stdio.h>
#include <stdlib.h>
int main() {
scanf("%d", &n);
exit(0);
return 0;
Output
20
36
Sum = 156
#include <stdio.h>
#include <stdlib.h>
int main() {
scanf("%d", &n);
exit(0);
free(ptr);
return 0;
Output
20
36
Sum = 156
realloc()
If the dynamically allocated memory is insufficient or more than required, you can change
the size of previously allocated memory using the realloc() function.
Syntax of realloc()
Example: realloc()
#include <stdio.h>
#include <stdlib.h>
Praveen Kumar P K, UIT Kollam
int main() {
scanf("%d", &n1);
printf("%pc\n",ptr + i);
scanf("%d", &n2);
free(ptr);
return 0;
Output
Enter size: 2
26855472
26855476
26855472
26855480
26855484
malloc() calloc()
malloc() is a function that creates one block calloc() is a function that assigns a
of memory of a fixed size. specified number of blocks of memory to a
single variable.
malloc() does not initialize the memory to calloc() initializes the memory to zero
zero
Answer:
A function in C is a block of code designed to perform a specific task, which can be called and
executed whenever required.
Answer:
A library function is a pre-defined function provided by C libraries such as printf(), scanf(),
sqrt(), etc.
Answer:
Recursion is a process in which a function calls itself directly or indirectly until a base condition
is met.
Answer:
Scope refers to the visibility or lifetime of a variable — i.e., where in the program the variable
can be accessed.
Answer:
return_type function_name(parameter_list);
Answer:
Library Function User-Defined Function
Predefined in C libraries Created by the programmer
Example: printf() Example: sum()
No need for definition Must be defined by user
Answer:
Declaration tells the compiler about the function name, return type, and parameters
(prototype).
Definition provides the actual body or implementation of the function.
3. Write a function to add two numbers and return the result. (Apply – Implement)
Answer:
Answer:
In recursion, a function repeatedly calls itself until a base condition is satisfied.
Example:
int factorial(int n) {
if(n == 0)
return 1;
else
return n * factorial(n - 1);
}
Answer:
Local variables: Declared inside a function and used only within it.
Global variables: Declared outside all functions and can be used anywhere.
Example:
int x = 10; // global
void func() {
int y = 5; // local
}
Answer:
#include <stdio.h>
int factorial(int n) {
if(n == 0)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
Explanation:
This program demonstrates recursion, where factorial() calls itself until n becomes 0.
Answer:
Example (Recursion):
int factorial(int n){
if(n==0) return 1;
return n*factorial(n-1);
}
Example (Iteration):
Answer:
Types of scope:
Example:
4. Apply & Analyse – Develop a program that uses both library and user-defined functions
to compute the square root of a sum of two numbers. (Apply – Design)
Answer:
#include <stdio.h>
#include <math.h> // for sqrt()
int sum(int a, int b) {
return a + b;
}
int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
double result = sqrt(sum(x, y)); // library + user-defined
printf("Square root of sum = %.2lf", result);
return 0;
}
Explanation:
This combines user-defined (sum) and library function (sqrt) effectively.
Pointers
Answer:
A pointer is a variable that stores the memory address of another variable.
Answer:
The & operator gives the address of a variable.
Answer:
The * operator is used to access the value stored at the address pointed to by a pointer
(dereferencing).
Answer:
int *ptr;
Answer:
Pointer arithmetic refers to operations like incrementing, decrementing, adding, or subtracting
integers from pointers.
Answer:
Answer:
int a = 10;
int *p;
p = &a; // pointer p holds address of a
Answer:
In call by value, a copy of the variable is passed to a function.
Changes made inside the function do not affect the original variable.
Example:
Answer:
In call by reference, the address of a variable is passed to a function.
Changes affect the original variable.
Example:
Answer:
1. Apply – Write a C program using pointers to swap two numbers (call by reference).
(Apply – Construct)
Answer:
#include <stdio.h>
int main() {
int a = 5, b = 10;
swap(&a, &b);
printf("After swapping: a = %d, b = %d", a, b);
return 0;
}
Explanation:
The function swap() takes addresses of variables and swaps the original values using
dereferencing.
2. Analyse – Compare call by value and call by reference in terms of data modification and
memory usage. (Analyse – Compare)
Answer:
Conclusion:
Call by reference is more efficient when changes need to persist outside the function.
Then:
Answer:
#include <stdio.h>
int main() {
int marks[5] = {85, 90, 78, 88, 92};
int *ptr[5];
printf("Student Marks:\n");
for(int i=0; i<5; i++)
printf("Student %d: %d\n", i+1, *ptr[i]);
return 0;
}
Explanation:
This program uses an array of pointers to access and display student marks efficiently.
5. Create – Design a program to demonstrate both call by value and call by reference.
(Create – Develop)
Answer:
#include <stdio.h>
void callByValue(int x) {
x = x + 10;
}
int main() {
int a = 5, b = 5;
callByValue(a);
callByReference(&b);
printf("After call by value: a = %d\n", a);
printf("After call by reference: b = %d\n", b);
return 0;
}
Output:
Explanation:
Shows the difference in how function parameters are handled and modified.
Dynamic Memory Allocation
Answer:
Dynamic memory allocation is the process of allocating memory to variables during runtime using
functions such as malloc(), calloc(), realloc(), and free().
2. Name any two functions used for dynamic memory allocation in C. (Remember – Recall)
Answer:
malloc() and calloc() are two commonly used functions.
3. Which header file is required for dynamic memory allocation? (Remember – Recall)
Answer:
#include <stdlib.h>
Answer:
free() is used to release the dynamically allocated memory back to the system to avoid
memory leaks.
5. What does the malloc() function return if memory allocation fails? (Understand –
Recognize)
Answer:
malloc() returns NULL if memory allocation fails.
Answer:
Feature Static Allocation Dynamic Allocation
Time of allocation Compile-time Runtime
Memory size Fixed Flexible
Functions used Not applicable malloc(), calloc(), realloc(), free()
Example int a[5]; int *p = malloc(5 * sizeof(int));
Answer:
3. Write the syntax of realloc() function and explain its use. (Apply – Demonstrate)
Answer:
Syntax:
Use:
realloc() is used to resize an existing memory block dynamically, keeping its contents intact up
to the new size.
Answer:
Without free(), dynamically allocated memory remains occupied even after use, causing memory
leaks.
Hence, free() releases memory back to the system.
Answer:
int *p;
p = (int*) malloc(5 * sizeof(int));
if(p == NULL)
printf("Memory not allocated!");
else
printf("Memory allocated successfully!");
1. Apply – Write a C program to allocate memory dynamically for an array of integers and
find their sum. (Apply – Construct)
Answer:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, *arr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for(int i=0; i<n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
Explanation:
Memory for the array is allocated at runtime using malloc(), and later freed using free().
Answer:
Example Usage:
p = malloc(10 * sizeof(int));
p = realloc(p, 20 * sizeof(int));
Answer:
Advantages:
Disadvantages:
Answer:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
float *marks, sum = 0, avg;
printf("Enter marks:\n");
for(int i = 0; i < n; i++) {
scanf("%f", &marks[i]);
sum += marks[i];
}
avg = sum / n;
printf("Average = %.2f", avg);
free(marks);
return 0;
}
Explanation:
This program dynamically allocates memory using calloc() and computes the average marks.
5. Create – Develop a conceptual algorithm for efficient memory allocation and deallocation
using pointers. (Create – Formulate)
Answer:
Algorithm:
1. Start
2. Input required number of elements (n).
3. Use malloc() or calloc() to allocate memory dynamically.
4. Check if memory allocation was successful.
5. Process data using allocated memory (e.g., store and compute).
6. Output results.
7. Deallocate memory using free() to avoid leaks.
8. Stop
Explanation:
The algorithm ensures safe and efficient use of dynamic memory during program execution.