0% found this document useful (0 votes)
2 views48 pages

Major Module 3 + Questions

Uploaded by

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

Major Module 3 + Questions

Uploaded by

hawkeyen720
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Functions

A function is a block of code that performs a specific task.

It is also known as procedure or subroutine or module, in other programming languages.

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

again and again.

2) Code optimization

It makes the code optimized we don't need to write much code.

3) Easily to debug the program

Types of Functions

There are two types of functions in C programming:

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

as many user-defined functions as you want.

Elements of user-defined functins :

In order to write an efficient user defined function, the programmer must familiar with the

following three elements.

1 : Function Declaration. (Function Prototype).

2 : Function Call.

3 : Function Definition

Function Declaration. (Function Prototype).


Praveen Kumar P K, UIT Kollam
A function declaration is the process of tells the compiler about a function name.

Syntax

return_type function_name(parameter/argument);

return_type function-name();

Ex :

int add(int a,int b);

void add();

At the time of function declaration function must be terminated with ;.

Calling a function/function call

When we call any function control goes to function body and execute entire code.

Syntax :

function-name();

function-name(parameter/argument);

return value/ variable = function-name(parameter/argument);

Ex :

add(); // function without parameter/argument

add(a,b); // function with parameter/argument

c=fun(a,b); // function with parameter/argument and return values

Defining a function.

Defining of function is nothing but give body of function that means write logic inside function

body.

Syntax

return_ type function-name(parameter list) // function header.

declaration of variables;

body of function; // Function body

return statement; (expression or value) //optional

Praveen Kumar P K, UIT Kollam


}

Eg: 1

int add( int x, int y)

int z;

z = x + y;

return z

Ex 2

int add( int x, int y)

return ( x + y );

Praveen Kumar P K, UIT Kollam


The execution of a C program begins from the main() function. When the compiler encounters
functionName(); inside the main function, control of the program jumps to void functionName()

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

the function definition are executed.

Example:

#include <stdio.h>

int addNumbers(int a, int b); // function prototype / declaration

int main()

int n1,n2,sum;

printf("Enters two numbers: ");

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function cal

printf("sum = %d",sum);

return 0;

int addNumbers(int a,int b) // function definition

int result;

result = a+b;

return result; // return statement

Praveen Kumar P K, UIT Kollam


Return Statement

Syntax of return statement

return; // does not return any value

or

return(exp); // the specified exp value to calling function.

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.

Praveen Kumar P K, UIT Kollam


Parameters

parameters provides the data communication between the calling function and called function.

They are two types of parametes

1 : Actual parameters.

2 : Formal parameters.

1 : Actual Parameters : These are the parameters transferred from the calling function (main

program) to the called function (function).

2 : Formal Parameters :These are the parameters transferred into the calling function (main

program) from the called function(function).

• The parameters specified in calling function are said to be Actual Parameters.


• The parameters declared in called function are said to be Formal Parameters.
• The value of actual parameters is always copied into formal parameters.

Ex :

main()

fun1( a , b ); //Calling function

fun1( x, y ) //called function

{ }
Praveen Kumar P K, UIT Kollam
Where

a, b are the Actual Parameters

x, y are the Formal Parameters

Difference between Actual Parameters and Formal Parameters


Actual Parameters Formal Parameter Actual Parameters Formal Parameter

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.

2 : Actual parameters can be constants, 2 : Actual parameters can be constants,


variables or expression. variables or expression.

Ex : c=add(a,b) //variable Ex : c=add(a,b) //variable

c = add(a+5,b); //expression. c=add(a+5,b); //expression.

c = add(10,20); //constants. c=add(10,20); //constants.

3 : Actual parameters sends values to the 3 : Formal parametes receive values from the
formal parameters. actual parametes.

Ex : c=add(4,5); Ex : int add(int m,int n);

Here m will have the value 4 and n will have the


value 5

4 : Address of actual parameters can be sent 4 : Address of actual parameters can be sent
to formal parameters to formal parameters

Types of User-defined Functions in C Programming

1 : Functions with no Parameters and no Return Values :

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

Praveen Kumar P K, UIT Kollam


Example

#include<conio.h>

void sum(); //Declaration

void main()

sum(); //Calling

getch();

void sum() //Definition

int a,b,c;

printf("enter the values of a and b");

scanf("%d%d",&a,&b);

c=a+b;

printf("sum=%d",c);

2 : Functions with no Parameters and Return Values.

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>

int sum(); //Declaration

void main()

Praveen Kumar P K, UIT Kollam


int c;

clrscr();

c=sum(); //Calling

printf("sum=%d",c);

getch();

int sum() //Definition

int a,b,c;

printf("enter the values of a and b");

scanf("%d%d",&a,&b);

c=a+b;

return c;

3 : Functions with Parameters and no Return Values.

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

the called function.

Example

#include<stdio.h>

#include<conio.h>

void sum(int a,int b);

void main()

Praveen Kumar P K, UIT Kollam


int m,n;

clrscr();

printf("Enter m and n values:");

scanf("%d%d",&m,&n);

sum(m,n);

getch();

void sum(int a,int b)

int c;

c=a+b;

printf("sum=%d",c);

4 : Functions with Parameters and Return Values.

• 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>

int sum(int a,int b);

void main()

int m,n,c;

clrscr();

printf("Enter m and n values");


Praveen Kumar P K, UIT Kollam
scanf("%d%d",&m,&n);

c=sum(m,n);

printf("sum=%d",c);

getch();

int sum(int a,int b)

int c;

c=a+b;

return c;

Praveen Kumar P K, UIT Kollam


Pass arrays to a function in C

In C programming, you can pass an entire array to functions.

Pass One Dimension Arrays to a Function

Example

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>

float calculateSum(float num[]);

int main() {

float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()

result = calculateSum(num);

printf("Result = %.2f", result);

return 0;

float calculateSum(float num[]) {

float sum = 0.0;

for (int i = 0; i < 6; ++i) {

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);

However, notice the use of [] in the function definition.

Praveen Kumar P K, UIT Kollam


float calculateSum(float num[]) {

... ..

This informs the compiler that you are passing a one-dimensional array to the function.

Pass Multidimensional Arrays to a 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>

void displayNumbers(int num[2][2]);

int main() {

int num[2][2];

printf("Enter 4 numbers:\n");

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 2; ++j) {

scanf("%d", &num[i][j]);

// pass multi-dimensional array to a function

displayNumbers(num);

return 0;

void displayNumbers(int num[2][2]) {

printf("Displaying:\n");

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 2; ++j) {

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

void displayNumbers(int num[2][2]);

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,

void displayNumbers(int num[][2]) {

// code

Praveen Kumar P K, UIT Kollam


POINTERS

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

Benefit of using pointers

• Pointers are more efficient in handling Array and Structure.


• Pointer allows references to function and thereby helps in passing of function as arguments
to other function.
• It reduces length and the program execution time.
• It allows C to support dynamic memory management.

Declaration of Pointer

Syntax: data_type* pointer_variable_name;

Example: int* p;

Note: void type pointer works with all data types, but isn't used often.

Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable to pointer variable.

Pointer variable contains address of variable of same data type

int a = 10 ;

int *ptr ; //pointer declaration

ptr = &a ; //pointer initialization

or

int *ptr = &a ; //initialization and declaration together

Note: Pointer variable always points to same type of data.

float a;

int *ptr;

ptr = &a; //ERROR, type mismatch (ptr type is integer and a type is float)

Praveen Kumar P K, UIT Kollam


Reference operator (&) and Dereference operator (*)

& 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 (*).

Symbol Name Description

& (ampersand sign) Reference operator / determines the address of a variable.


Address of operator

* (asterisk sign) Dereference operator / accesses the value at the address.


Indirection operator

Dereferencing of Pointer

Once a pointer has been assigned the address of a variable. To access the value of variable,

pointer is dereferenced, using the indirection operator *.

int a,*p;

a = 10;

p = &a;

printf("%d",*p); //this will print the value of a.

printf("%d",*&a); //this will also print the value of a.

printf("%u",&a); //this will print the address of a.

printf("%u",p); //this will also print the address of a.

printf("%u",&p); //this will print the address of p.

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:

• 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.

Praveen Kumar P K, UIT Kollam


• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler)

Example

#include <stdio.h>

int main()

int var =10;

int *p;

p= &var;

printf ( "\n Address of var is: %u", &var);

printf ( "\n Address of var is: %u", p);

printf ( "\n Address of pointer p is: %u", &p);

/* %u for p's value as it should be an address*/

printf( "\n Value of pointer p is: %u", p);

printf ( "\n Value of var is: %d", var);

printf ( "\n Value of var is: %d", *p);

printf ( "\n Value of var is: %d", *( &var));

Output:

Address of var is: 00XBBA77

Address of var is: 00XBBA77

Address of pointer p is: 77221111

Value of pointer p is: 00XBBA77

Value of var is: 10

Value of var is: 10

Value of var is: 10

Praveen Kumar P K, UIT Kollam


NULL Pointer

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.

syntax of pointer to pointer

int **p2;

Example:

#include <stdio.h>

#include <conio.h>

void main(){

int number=50;

int *p;//pointer to int

int **p2;//pointer to pointer

clrscr();

p=&number;//stores the address of number variable

p2=&p;

printf("Address of number variable is %x \n",&number);

printf("Address of p variable is %x \n",p);

printf("Value of *p variable is %d \n",*p);

printf("Address of p2 variable is %x \n",p2);

printf("Value of **p2 variable is %d \n",**p);

Praveen Kumar P K, UIT Kollam


getch();

Output

Address of number variable is fff4

Address of p variable is fff4

Value of *p variable is 50

Address of p2 variable is fff2

Value of **p variable is 50

Praveen Kumar P K, UIT Kollam


PASSING PARAMETERS TO FUNCTIONS

There are two ways to pass value or data to function in C language:

Call by value and Call by reference.

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.

C provides two mechanisms to pass parameters to a function.

1. Pass by value (OR) Call by value.


2. Pass by reference (OR) Call by Reference

Pass by value (OR) Call by value :

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.

Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int , int); //prototype of the function

int main()

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b);

// printing the value of a and b in main

swap(a,b); //Function Call

printf("After swapping values in main a = %d, b = %d\n",a,b);

/* The value of actual parameters do not change by changing the formal


parameters in call by value, a = 10, b = 20 */

Praveen Kumar P K, UIT Kollam


}

void swap (int a, int b) //Function Definition

int temp;

temp = a;

a=b;

b=temp;

printf("After swapping values in function a = %d, b = %d\n",a,b);

// Formal parameters, a = 20, b = 10

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20

Pass by reference (OR) Call by Reference :

In pass by reference, a function is called with addresses of actual parameters. In the


function header, the formal parameters receive the addresses of actual parameters. Now
the formal parameters do not contain values, instead they contain addresses. Any variable
if it contains an address, it is called a pointer variable. Using pointer variables, the values
of the actual parameters can be changed. This way of passing parameters is called call by
reference or pass by reference.

Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int *, int *); //prototype of the function

int main()

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b);


Praveen Kumar P K, UIT Kollam
// printing the value of a and b in main

swap(&a,&b);

printf("After swapping values in main a = %d, b = %d\n",a,b);

// The values of actual parameters do change in call by reference, a = 10, b = 20

void swap (int *a, int *b)

int temp;

temp = *a;

*a=*b;

*b=temp;

printf("After swapping values in function a = %d, b = %d\n",*a,*b);

// Formal parameters, a = 20, b = 10

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c

Call by value Call by reference

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

Praveen Kumar P K, UIT Kollam


Recursion

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 :

• There should be at least one if statement used to terminate recursion.


• It does not contain any looping statements.

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()

recursionfunction(); //calling self function

Praveen Kumar P K, UIT Kollam


Example 1: Sum of Natural Numbers Using Recursion

#include <stdio.h>

int sum(int n);

int main() {

int number, result;

printf("Enter a positive integer: ");

scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);

return 0;

int sum(int n) {

if (n != 0)

// sum() function calls itself

return n + sum(n-1);

else

return n;

Output

Enter a positive integer:3

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.

Praveen Kumar P K, UIT Kollam


Praveen Kumar P K, UIT Kollam
Example 2: Factorial Program using recursion in C

#include<stdio.h>

long factorial(int n)

if (n == 0)

return 1;

else

return(n * factorial(n-1));

void main()

int number;

long fact;

printf("Enter a number: ");

scanf("%d", &number);

fact = factorial(number);

printf("Factorial of %d is %ld\n", number, fact);

return 0;

Output

Enter a number: 6

Factorial of 5 is: 720

Example 3: C program to Find the Factorial Using for Loop

#include <stdio.h>

unsigned int factorial(unsigned int N)

int fact = 1, i;

Praveen Kumar P K, UIT Kollam


// Loop from 1 to N to get the factorial

for (i = 1; i <= N; i++)

fact *= i;

return fact;

int main()

int N = 5;

int fact = factorial(N);

printf("Factorial of %d is %d", N, fact);

return 0;

Output

Factorial of 5 is 120

Praveen Kumar P K, UIT Kollam


C Dynamic Memory Allocation

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 name "malloc" stands for memory allocation.

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()

ptr = (castType*) malloc(size);

Example

ptr = (float*) malloc(100 * sizeof(float));

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.

The expression results in a NULL pointer if the memory cannot be allocated.

C calloc()

The name "calloc" stands for contiguous allocation.

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()

Praveen Kumar P K, UIT Kollam


ptr = (castType*)calloc(n, size);

Example:

ptr = (float*) calloc(25, sizeof(float));

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.

Example: malloc() and free()

// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");

scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));

if(ptr == NULL) { // if memory cannot be allocated

printf("Error! memory not allocated.");

exit(0);

Praveen Kumar P K, UIT Kollam


}

printf("Enter elements: ");

for(i = 0; i < n; ++i) {

scanf("%d", ptr + i);

sum += *(ptr + i);

printf("Sum = %d", sum);

free(ptr); // deallocating the memory

return 0;

Output

Enter number of elements: 3

Enter elements: 100

20

36

Sum = 156

Here, we have dynamically allocated the memory for n number of int.

Example: calloc() and free()

// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");

scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));

Praveen Kumar P K, UIT Kollam


if(ptr == NULL) {

printf("Error! memory not allocated.");

exit(0);

printf("Enter elements: ");

for(i = 0; i < n; ++i) {

scanf("%d", ptr + i);

sum += *(ptr + i);

printf("Sum = %d", sum);

free(ptr);

return 0;

Output

Enter number of elements: 3

Enter elements: 100

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()

ptr = realloc(ptr, x);

Here, ptr is reallocated with a new size x.

Example: realloc()

#include <stdio.h>

#include <stdlib.h>
Praveen Kumar P K, UIT Kollam
int main() {

int *ptr, i , n1, n2;

printf("Enter size: ");

scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Addresses of previously allocated memory:\n");

for(i = 0; i < n1; ++i)

printf("%pc\n",ptr + i);

printf("\nEnter the new size: ");

scanf("%d", &n2);

// rellocating the memory

ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");

for(i = 0; i < n2; ++i)

printf("%pc\n", ptr + i);

free(ptr);

return 0;

Output

Enter size: 2

Addresses of previously allocated memory:

26855472

26855476

Enter the new size: 4

Addresses of newly allocated memory:

26855472

Praveen Kumar P K, UIT Kollam


26855476

26855480

26855484

Difference between malloc() and calloc() in C

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() only takes one argument calloc() takes two arguments.

malloc() is faster than calloc. calloc() is slower than malloc()

calloc() is slower than malloc() calloc() has low time efficiency

malloc() is used to indicate memory calloc() is used to indicate contiguous


allocation memory allocation

Syntax : void* malloc(size_t size); Syntax : void* calloc(size_t num, size_t


size);

malloc() does not initialize the memory to calloc() initializes the memory to zero
zero

Praveen Kumar P K, UIT Kollam


Functions

1 Mark Questions (Remember & Understand Level)

1. Define a function in C. (Remember – Define)

Answer:
A function in C is a block of code designed to perform a specific task, which can be called and
executed whenever required.

2. What is a library function? (Remember – Recall)

Answer:
A library function is a pre-defined function provided by C libraries such as printf(), scanf(),
sqrt(), etc.

3. What is recursion? (Understand – Explain)

Answer:
Recursion is a process in which a function calls itself directly or indirectly until a base condition
is met.

4. What is the scope of a variable? (Understand – Describe)

Answer:
Scope refers to the visibility or lifetime of a variable — i.e., where in the program the variable
can be accessed.

5. Write the syntax for declaring a function in C. (Remember – Recall)

Answer:

return_type function_name(parameter_list);

2 Mark Questions (Understand & Apply Level)

1. Differentiate between library and user-defined functions. (Understand – Differentiate)

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

2. Explain the difference between function declaration and function definition.


(Understand – Distinguish)

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:

int add(int a, int b) {


return a + b;
}

4. Describe how recursion works with an example. (Understand – Illustrate)

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);
}

5. Explain local and global variables with an example. (Apply – Illustrate)

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
}

7 Mark Questions (Apply & Analyse Level)

1. Apply – Write a C program using user-defined functions to find the factorial of a


number using recursion. (Apply – Construct)

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.

2. Analyse – Compare recursion and iteration with examples. (Analyse – Compare)

Answer:

Aspect Recursion Iteration


Definition Function calling itself Looping constructs used repeatedly
Memory usage Uses stack for each call Uses less memory
Termination Controlled by base condition Controlled by loop condition
Example factorial(n) calls itself for(i=1;i<=n;i++)

Example (Recursion):
int factorial(int n){
if(n==0) return 1;
return n*factorial(n-1);
}

Example (Iteration):

int factorial(int n){


int f=1;
for(int i=1;i<=n;i++) f=f*i;
return f;
}

3. Analyse – Explain different types of function scope in C with examples. (Analyse –


Examine)

Answer:
Types of scope:

1. Local scope: Variable inside a function.


2. Global scope: Variable outside all functions.
3. Function scope: Labels defined within functions.
4. Block scope: Variable declared within {}.

Example:

int x = 10; // global


void main() {
int y = 5; // local
{
int z = 3; // block
printf("%d", z);
}
}

Each variable’s visibility is limited by its scope.

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

1-Mark Questions (Remember / Understand Level)

1. Define a pointer in C. (Remember – Define)

Answer:
A pointer is a variable that stores the memory address of another variable.

2. What does the & operator do in C? (Remember – Recall)

Answer:
The & operator gives the address of a variable.

3. What does the * operator do in C? (Understand – Explain)

Answer:
The * operator is used to access the value stored at the address pointed to by a pointer
(dereferencing).

4. Write the syntax to declare a pointer to an integer. (Remember – Recall)

Answer:

int *ptr;

5. What is pointer arithmetic? (Understand – Describe)

Answer:
Pointer arithmetic refers to operations like incrementing, decrementing, adding, or subtracting
integers from pointers.

2-Mark Questions (Understand / Apply Level)

1. Differentiate between & and * operators in pointers. (Understand – Differentiate)

Answer:

Operator Function Example Meaning


& Address-of &a Gives address of variable a
Operator Function Example Meaning
* Value-at *p Accesses value stored at address p

2. Declare a pointer and assign it to a variable. (Apply – Implement)

Answer:

int a = 10;
int *p;
p = &a; // pointer p holds address of a

3. Explain the concept of call by value with an example. (Understand – Explain)

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:

void display(int x){ x = x + 10; }

4. Explain call by reference with an example. (Understand – Illustrate)

Answer:
In call by reference, the address of a variable is passed to a function.
Changes affect the original variable.
Example:

void update(int *x){ *x = *x + 10; }

5. Demonstrate pointer arithmetic using an example. (Apply – Demonstrate)

Answer:

int arr[3] = {10, 20, 30};


int *p = arr;
p++; // moves to next memory location

Now p points to arr[1].


7-Mark Questions (Apply / Analyse / Create Level)

1. Apply – Write a C program using pointers to swap two numbers (call by reference).
(Apply – Construct)

Answer:

#include <stdio.h>

void swap(int *x, int *y) {


int temp;
temp = *x;
*x = *y;
*y = temp;
}

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:

Aspect Call by Value Call by Reference


Passing method Passes copy of value Passes address
Changes to variable Do not affect original Affect original
Memory usage More memory Less memory
Speed Slower due to copying Faster
Example fun(a); fun(&a);

Conclusion:
Call by reference is more efficient when changes need to persist outside the function.

3. Analyse – Explain pointer arithmetic operations with examples. (Analyse – Examine)


Answer:
Pointer arithmetic allows moving through memory locations.
Let:

int a[3] = {1, 2, 3};


int *p = a;

Then:

1. p + 1 → points to next element (a[1])


2. p - 1 → moves to previous element
3. *(p + 2) → accesses third element

Each increment adds sizeof(int) bytes.

4. Create – Develop a C program that uses an array of pointers to display marks of 5


students. (Create – Design)

Answer:

#include <stdio.h>

int main() {
int marks[5] = {85, 90, 78, 88, 92};
int *ptr[5];

for(int i=0; i<5; i++)


ptr[i] = &marks[i]; // assigning addresses

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;
}

void callByReference(int *y) {


*y = *y + 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:

After call by value: a = 5


After call by reference: b = 15

Explanation:
Shows the difference in how function parameters are handled and modified.
Dynamic Memory Allocation

1-Mark Questions (Remember / Understand Level)

1. What is dynamic memory allocation? (Remember – Define)

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>

4. What is the use of the free() function? (Understand – Explain)

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.

-Mark Questions (Understand / Apply Level)

1. Differentiate between static and dynamic memory allocation. (Understand –


Differentiate)

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));

2. Explain the use of malloc() and calloc() functions. (Understand – Explain)

Answer:

 malloc(size) allocates a single block of memory of the specified size (uninitialized).


 calloc(n, size) allocates multiple blocks (n elements), each of given size, and initializes all
bytes to zero.

3. Write the syntax of realloc() function and explain its use. (Apply – Demonstrate)

Answer:
Syntax:

ptr = realloc(ptr, new_size);

Use:
realloc() is used to resize an existing memory block dynamically, keeping its contents intact up
to the new size.

4. Why is free() important in dynamic memory management? (Understand – Explain)

Answer:
Without free(), dynamically allocated memory remains occupied even after use, causing memory
leaks.
Hence, free() releases memory back to the system.

5. Illustrate an example showing allocation using malloc(). (Apply – Illustrate)

Answer:

int *p;
p = (int*) malloc(5 * sizeof(int));
if(p == NULL)
printf("Memory not allocated!");
else
printf("Memory allocated successfully!");

7-Mark Questions (Apply / Analyse / Create Level)

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);

arr = (int*) malloc(n * sizeof(int));


if(arr == NULL) {
printf("Memory allocation failed!");
return 1;
}

printf("Enter elements:\n");
for(int i=0; i<n; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}

printf("Sum = %d", sum);


free(arr);
return 0;
}

Explanation:
Memory for the array is allocated at runtime using malloc(), and later freed using free().

2. Analyse – Compare malloc(), calloc(), and realloc() functions. (Analyse – Compare)

Answer:

Function Purpose Initialization Parameters Return Type


malloc() Allocates single block Garbage value size void*
Function Purpose Initialization Parameters Return Type
calloc() Allocates multiple blocks Zeros n, size void*
realloc() Resizes existing block Keeps old data ptr, new_size void*

Example Usage:

p = malloc(10 * sizeof(int));
p = realloc(p, 20 * sizeof(int));

3. Analyse – Explain the advantages and disadvantages of dynamic memory allocation.


(Analyse – Examine)

Answer:

Advantages:

 Memory is allocated as per need.


 Efficient use of memory.
 Enables creation of data structures like linked lists, trees, etc.

Disadvantages:

 Risk of memory leaks if free() not used.


 Slower than static allocation.
 Requires careful pointer handling.

4. Create – Design a C program using dynamic memory allocation to store marks of


students and find the average. (Create – Design)

Answer:

#include <stdio.h>
#include <stdlib.h>

int main() {
int n;
float *marks, sum = 0, avg;

printf("Enter number of students: ");


scanf("%d", &n);

marks = (float*) calloc(n, sizeof(float));


if(marks == NULL) {
printf("Memory allocation failed!");
return 1;
}

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.

You might also like