0% found this document useful (0 votes)
10 views

DS_Notes unit 1

The lecture notes cover fundamental concepts in C programming, focusing on arrays, memory allocation, functions, structures, and pointers. Key topics include static and dynamic memory allocation, function definitions, recursion, and the use of pointers for data manipulation. The notes also explain how to pass data to functions using call by value and call by reference methods, along with examples of memory management functions like malloc(), calloc(), and free().

Uploaded by

b6658087
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

DS_Notes unit 1

The lecture notes cover fundamental concepts in C programming, focusing on arrays, memory allocation, functions, structures, and pointers. Key topics include static and dynamic memory allocation, function definitions, recursion, and the use of pointers for data manipulation. The notes also explain how to pass data to functions using call by value and call by reference methods, along with examples of memory management functions like malloc(), calloc(), and free().

Uploaded by

b6658087
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lecture Notes|| Unit -1

CO1: Implement arrays and memory allocation strategies.

Syllabus: Revision of Function and Structure, Revision of concept of types of pointers and its applications,
Memory Allocation- Static and Dynamic. Introduction: Basic Terminology, Elementary Data Organization,
Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major Order, and
Column Major Order, Application of arrays, Sparse Matrices and their representations.

[T-1] Prerequisites of Subject [Function]

function & 3. Type of value return by the function


Function: - Syntax:
• Definition: A function is a group of statements that return type function name (type1 arg1 , type2 arg2);
together perform a task. Every C program has at least one
function, which is main (), and all the most trivial •Function Definition: It consists of code description
programs can define additional functions.
and code of a function. It consists of two parts 1.
Function header 2. Function coding
• Monolithic Vs Modular Programming-Monolithic
Programming indicates the program which contains a Function definition tells what the I/O functions are and
single function for the large program. Modular what is going to do.
programming helps the programmer to divide the whole Syntax:
program into different Units and each Unit is separately return type function name (type1 arg1 , type2 arg2)
developed and tested. {
local variable;
• Disadvantages of monolithic programming: statements;
1. Difficult to check error on large programs. 2. Difficult return (expression);
to maintain. 3. Code can be specific to a particular }
problem. i.e. it cannot be reused.
Function Categories- There are four main categories
• Advantage of modular programming: 1. Modular of the functions these are as follows:
program are easier to code and debug. 2. Reduces the 1. Function with no arguments and no return values.
programming size. 3. Code can be reused in other 2. Function with no arguments and a return value.
programs. 4. Problem can be isolated to specific Unit so 3. Function with arguments and no return values.
easier to find the error and correct it. 4. Function with arguments and return values.

• A function that is designed for user specific task is Actual Arguments: Arguments which are mentioned
called user defined function. Every user define function in the function call.
has three parts as: Prototype or Declaration, Calling, Formal Arguments: Arguments which are mentioned
Definition in function definition are called dummy or formal
argument. These arguments are used to just hold the
• Function Declaration OR Function Prototype: It is
value that is sent by calling function. Formal arguments
also known as function prototype. It informs the
are like other local variables of the function which are
computer about the three things 1. Name of the function
created when function call starts and destroyed when
2. Number and type of arguments received by the
end function.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 4
Parameter passing methods-
There are two ways to pass value or data to function in C language which is given below;
• call by value
• call by reference

Example of a Call by Value method Example of a Call by Value method


#include<stdio.h> #include<stdio.h>
void increment(int); void increment(int *x);
void main() void main()
{ {
int a = 10; int a = 10;
printf("Before function calling: %d", a); printf("Before function calling: %d", a);
increment(a); increment(&a);
printf("After function calling: %d", a); printf("After function calling: %d", a);
getch(); getch();
} }
void increment(int x) void increment(int *x)
{ {
x = x + 1; *x = *x + 1;
printf ("In function value is: %d", x); printf ("In function value is:", *x);
} }
Output: Output:
Before function calling 10 Before function calling 10
In function value is 11 In function value is 11
After function calling 10 After function calling 11

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 5
Passing Array to a function:

**Passing individual array elements to a function


Passing values of individual array elements to a function (CBV)

Passing addresses of individual array elements to a function (CBR)

**How to pass an entire array to a function as an argument?


Passing entire array to a function (CBV)

Passing entire array to a function (CBR)

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 6
• Recursion: When a function calls itself then that int sum(int n)
function is called Recursive function. { if (n != 0)
return n + sum(n-1); // sum()
void recurse() function calls itself
{ recurse();
else
}
int main() return n;
{ recurse(); }
}
Output
Example: Sum of Natural Numbers Using Enter a positive integer:3
Recursion sum = 6
#include <stdio.h>
int sum(int n);
int main() • Advantage of Recursion
{ a) Function calling related information will be
int number, result; maintained by recursion.
printf("Enter a positive integer: "); b) Stack evaluation will be take place by using
recursion.
scanf("%d", &number);
c) In fix prefix, post-fix notation will be
result = sum(number); evaluated by using recursion.
printf("sum = %d", result);
return 0; • Disadvantage of Recursion
} 1. It is a very slow process due to stack
overlapping.
2. Recursive programs can create stack
overflow.
3. Recursive functions can create as loops.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 7
[T-2] Prerequisites of Subject [Structure]

• Structure: A Structure is a user defined data type • Example:


that can store related information together.
Structures are used to represent a record.
// C program to demonstrate structure pointer
• Structure Declaration-It is declared using a #include <stdio.h>
keyword struct followed by the name of the structure. struct point
The variables of the structure are declared within the {
structure. int value;
Example: };
Struct struct-name
{ int main()
data_type var-name; { struct point s;
data_type var-name; struct point* ptr = &s;
}; // Initialization of the structure pointer
return 0;
}
• Structure Initialization-Assigning constants to
the members of the structure is called initializing In the above code s is an instance of struct point
of structure.Syntax: and ptr is the struct pointer because it is storing the
struct struct_name address of struct point.
{data _type member_name1; • Accessing the Structure Member with the Help
data _type member_name2; of Pointers
} struct_var= {constant1, constant2}; There are two ways to access the members
of the structure with the help of a structure
• Accessing the Members of a structure-A structure pointer:
member variable is generally accessed using a ‘.’ 1.With the help of (*) asterisk or indirection
operator.
operator and (.) dot operator.
Syntax: strcut_var. member_name;
The dot operator is used to select a particular member 2.With the help of ( -> ) Arrow operator.
of the structure.
To input values for data members of the structure #include <stdio.h>
variable stud, can be written as, struct person
scanf(“%d”,&stud.roll); {
scanf(‘’%s”,&stud.name); int age;
To print the values of structure variable stud, can be
written as: float weight;
printf(“%s”,stud.roll); };
printf(“%f”, stud.name); int main()
{ struct person *personPtr, person1;
• Structure Pointer in C:A structure pointer is defined personPtr = &person1;
as the pointer which points to the address of the printf("Enter age: ");
memory block that stores a structure known as the scanf("%d", &personPtr->age);
structure pointer. Complex data structures like linked printf("Enter weight: ");
lists, trees, graphs, etc. are created with the help of scanf("%f", &personPtr->weight);
structure pointers. The structure pointer tells the printf("Displaying:\n");
address of a structure in memory by pointing the printf("Age: %d\n", personPtr->age);
variable to the structure variable. printf("weight: %f", personPtr-weight);
return 0;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 8
In this example, the address of person1 is Output
stored in the personPtr pointer Name : Tata
using personPtr = &person1; Now, you Price : 1021
can access the members of person1 using
Example 2: Using Call By Reference
the personPtr pointer. Method
By the way,
personPtr->age is equivalent // C program to pass structure as an argument to
to (*personPtr).age the functions using Call By Reference
personPtr->weight is equivalent Method
#include <stdio.h>
to (*personPtr).weight
struct student {
char name[50];
int roll;
How to Pass or Return a Structure To or From a float marks;
Function in C? };
void display(struct student* student_obj)
Example 1: Using Call By Value Method {
printf("Name: %s\n", student_obj->name);
printf("Roll: %d\n", student_obj->roll);
// C program to pass structure as an printf("Marks: %f\n", student_obj->marks);
argument to the functions using Call By }
Value Method int main()
{ struct student st1 = { "Aman", 19, 8.5 };
#include <stdio.h> display(&st1);
struct car return 0;
{ }
char name[30];
int price; Output
}; Name: Aman
Roll: 19
void print_car_info(struct car c) Marks: 8.500000
{
printf("Name : %s", c.name);
printf("\nPrice : %d\n", c.price);
}

int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 9
[T-3] Pointers and its applications (DMA)

• Every variable in C has a name and a value associated with it. When a variable is declared, a specific block of
memory within the computer is allocated to hold the value of that variable.
Consider the declaration, int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We may represent i’s location in memory by the following memory map.

• We see that the computer has selected memory location 65524 as the place to store the value 3. The location
number 65524 is not a number to be relied upon, because some other time the computer may choose a
different location for storing the value 3. The important point is, i’s address in memory is a number.
• A pointer is a variable that contains the memory location of another variable.
• Pointers applications include:
a) Pointers are used to pass information back and forth between functions.
b) Pointers enable the programmers to return multiple data items from a function via function arguments.
c) Pointers provide an alternate way to access the individual elements of an array.
d) Pointers are used to pass arrays and strings as function arguments.
e) Pointers are used to create complex data structures, such as trees, linked lists, linked stacks, linked
queues, and graphs.
f) Pointers are used for the dynamic memory allocation of a variable
• The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
• Now we can say—pointers are variables that contain addresses, and since addresses are always whole
numbers, pointers would always contain whole numbers.
• Every time a pointer is incremented it points to the immediately next location of its type.
• Thus, the following operations can be performed on a pointer:
(a) Addition of a number to a pointer. For example,
int i = 4, *j, *k ; j = &i ; j = j + 1 ; j = j + 9 ; k = j + 3 ;
(b) Subtraction of a number from a pointer. For example,
j = &i ; j = j - 2 ; j = j - 5 ; k = j - 6 ;
(c) Subtraction of one pointer from another.
One pointer variable can be subtracted from another provided both variables point to elements of the same
array.
(d) Comparison of two pointer variables
Pointer variables can be compared provided both variables point to objects of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array.
• **A word of caution! Do not attempt the following operations on pointers... they would never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 10
Memory Allocation- Static and Dynamic
• Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.
• Although C inherently does not have any technique to allocate memory dynamically, there are 4 library
functions defined under <stdlib.h> for dynamic memory allocation.

• malloc()
The name malloc stands for "memory allocation".The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()➔ ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.

• calloc()
The name calloc stands for "contiguous allocation".The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax of calloc()➔ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e,
4 bytes.

• free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its 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.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 11
Example #1: Using C malloc() and free() printf("Enter elements of array: ");
Write a C program to find sum of n elements entered for(i = 0; i < num; ++i)
by user. To perform this program, allocate memory {
dynamically using malloc() function. scanf("%d", ptr + i);
#include <stdio.h> sum += *(ptr + i);
#include <stdlib.h> }
int main() printf("Sum = %d", sum);
{ int num, i, *ptr, sum = 0; free(ptr);
printf("Enter number of elements: "); return 0;
scanf("%d", &num); }
ptr = (int*) malloc(num * sizeof(int)); //memory
allocated using malloc • realloc()
if(ptr == NULL) If the previously allocated memory is
{ printf("Error! memory not allocated."); insufficient or more than required, you can
exit(0); change the previously allocated memory size
} using realloc().
printf("Enter elements of array: "); Syntax of realloc() ➔ptr = realloc(ptr,
for(i = 0; i < num; ++i) newsize);
{ scanf("%d", ptr + i); Here, ptr is reallocated with size of newsize.
sum += *(ptr + i);
} Example #3: Using realloc()
printf("Sum = %d", sum); #include <stdio.h>
free(ptr); #include <stdlib.h>
return 0; int main()
} {
int *ptr, i , n1, n2;
Example #2: Using C calloc() and free() printf("Enter size of array: ");
Write a C program to find sum of n elements entered scanf("%d", &n1);
by user. To perform this program, allocate memory ptr = (int*) malloc(n1 * sizeof(int));
dynamically using calloc() function. printf("Address of previously allocated memory:
#include <stdio.h> ");
#include <stdlib.h> for(i = 0; i < n1; ++i)
int main() printf("%u\t",ptr + i);
{ printf("\nEnter new size of array: ");
int num, i, *ptr, sum = 0; scanf("%d", &n2);
printf("Enter number of elements: "); ptr = realloc(ptr, n2 * sizeof(int));
scanf("%d", &num); for(i = 0; i < n2; ++i)
ptr = (int*) calloc(num, sizeof(int)); printf("%u\t", ptr + i);
if(ptr == NULL) return 0;
{ }
printf("Error! memory not allocated.");
exit(0);
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 12
[T-4] Introduction: Basic Terminology, Elementary Data Organization

• A good program is defined as a program that runs correctly, easy to read and understand, easy to debug and
easy to modify.
• A program is said to be efficient when it executes in minimum time and with minimum memory space.
• In order to write efficient programs, we need to apply certain data management concepts.
• Data structure is a crucial part of data management.
• A data structure is basically a group of data elements that are put together under one name, and which defines
a particular way of storing and organizing data in a computer so that it can be used efficiently.
• Data: Data are simply values or sets of values.
• Data items: Data items refers to a single unit of values. Data items that are divided into sub-items are called
Group items. Ex: An Employee Name may be divided into three subitems- first name, middle name, and last
name.
• Data items that are not able to divide into sub-items are called Elementary items. Ex: SSN
• Entity: An entity is something that has certain attributes or properties which may be assigned values. The
values may be either numeric or non-numeric. Ex: Attributes- Names, Age, Sex, SSN Values- Rohland Gail,
34, F, 134-34-5533 Entities with similar attributes form an entity set. Each attribute of an entity set has a
range of values, the set of all possible values that could be assigned to the particular attribute.
• The term “information” is sometimes used for data with given attributes, of, in other words meaningful or
processed data.
• Field is a single elementary unit of information representing an attribute of an entity.
• Record is the collection of field values of a given entity.
• File is the collection of records of the entities in a given entity set.
• Each record in a file may contain many field items but the value in a certain field may uniquely determine
the record in the file. Such a field K is called a primary key.
• Records may also be classified according to length. A file can have fixed-length records or variable-length
records.
• In fixed-length records, all the records contain the same data items with the same amount of space assigned
to each data item.
• In variable-length records file records may contain different lengths. Example: Student records have
variable lengths, since different students take different numbers of courses. Variable-length records have a
minimum and a maximum length.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 13
What do you mean by the term “Data Structure”?
• Organizing the data in memory.
• A data structure is a way of organizing the data so that it can be used efficiently. Here, we have used the
word efficiently, which in terms of both the space and time.
• It is a set of algorithms that we can use in any programming language to structure the data in the memory.

Classification of Data Structure:

• Linear data structure:


Data structure in which data elements are arranged sequentially or linearly, where each element is attached to its
previous and next adjacent elements, is called a linear data structure. Examples of linear data structures are array,
stack, queue, linked list, etc.

Static data structure: Static data structure has a fixed memory size. It is easier to access the elements in a static
data structure. An example of this data structure is an array.

Dynamic data structure: In dynamic data structure, the size is not fixed. It can be randomly updated during the
runtime which may be considered efficient concerning the memory (space) complexity of the code. Examples of
this data structure are queue, stack, etc.

• Non-linear data structure:


Data structures where data elements are not placed sequentially or linearly are called non-linear data structures. In
a non-linear data structure, we can’t traverse all the elements in a single run only. Examples of non-linear data
structures are trees and graphs.

• The major or the common operations that can be performed on the data structures are:
o Searching: We can search for any element in a data structure.
o Sorting: We can sort the elements of a data structure either in an ascending or descending order.
o Insertion: We can also insert the new element in a data structure.
o Updation: We can also update the element, i.e., we can replace the element with another element.
o Deletion: We can also perform the delete operation to remove the element from the data structure.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 14
• Advantages of Data structures
The following are the advantages of a data structure:
o Efficiency: If the choice of a data structure for implementing a particular ADT is proper, it makes the
program very efficient in terms of time and space.
o Reusability: The data structure provides reusability means that multiple client programs can use the data
structure.
o Abstraction: The data structure specified by an ADT also provides the level of abstraction. The client cannot
see the internal working of the data structure, so it does not have to worry about the implementation part.
The client can only see the interface.

• An abstract data type (ADT) is the way we look at a data structure, focusing on what it does and ignoring how
it does its job. For example, stacks and queues are perfect examples of an ADT. We can implement both these
ADTs using an array or a linked list. This demonstrates the ‘abstract’ nature of stacks and queues.They are not
concerned about how they work.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 15
[T-5] Arrays: Definition, Declaration, Initialization & Processing of Single and Multidimensional Arrays

Array Data Structure


Definition
• An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items
of the same type together.
• They exist in both single dimension and multiple dimensions.
Basic terminologies of the array:
• Array Index: In an array, elements are identified by their indexes. Array index starts from 0.
• Array element: Elements are items stored in an array and can be accessed by their index.
• Array Length: The length of an array is determined by the number of elements it can contain.

Syntax
Creating an array in C language –Arrays are declared using the following syntax:
type name[size];
For example, if we write,
int marks[10];
In the memory, the array will be stored as shown
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
element element element element element element element element element element
marks [0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]

Types of arrays:
There are following types of arrays:
• One-dimensional array (1-D arrays): You can imagine a 1d array as a row, where elements are stored one
after another.

1D array
• Two-dimensional array: 2-D Multidimensional arrays can be considered as an array of arrays or as a matrix
consisting of rows and columns.

2D array
• Three-dimensional array: A 3-D Multidimensional array contains three dimensions, so it can be considered
an array of two-dimensional arrays.

3D array

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 16
Declaration, Initialization & Processing of Single and Multidimensional Arrays
One Dimensional Array

Declaration:
Syntax: ➔data_type array_name[size];
data_type represents the type of elements present in the array. array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.
Example:➔int age[100]; float sal[15]; char grade[20];
Here age is an integer type array, which can store 100 elements of integer type. The array sal is floating type array
of size 15, can hold float values. Grade is a character type array which holds 20 characters.

Initialization:
Syntax: ➔data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements one
after another.
Example: ➔int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23,
marks[4]=4

Note-:
In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then the
compiler assumes the size of array equal to the number of initializers. Example:int marks []={10,2,0,23,4};Here
the size of array marks is initialized to 5.
We can’t copy the elements of one array to another array by simply assigning it. Example:
int a[5]={9,8,7,6,5}; int b[5];
b=a; //not valid
we have to copy all the elements by using for loop.
for(a=i; i<5; i++) b[i]=a[i];

Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements present in the
array and in each pass one element is processed.
Example:
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(“enter the elements”);
scanf(“%d”,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{ printf(“%d”,a[i]);
printf(“\n”);
}
}

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 17
Two Dimensional Arrays-
Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come
naturally in the form of a table, e.g. spreadsheet, which need a two-dimensional array.

Declaration:
Syntax: ➔data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows ,Columnsize specifies the no.of columns.
Example: ➔int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last element of the
array is a[3][4] and total no.of elements is 4*5=20.

Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.
Example: ➔int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};

Note:
In 2-D arrays it is optional to specify the first dimension but the second dimension should always be present.
Example: int m[][3]={
{1,10},
{2,20,200},
{3}, {4,40,400} };
Here the first dimension is taken 4 since there are 4 roes in the initialization list. A 2-D array is known as matrix.

Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the inner loop
indicates the columns.
Example: ➔
int a[4][5];
Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);
This program reads and displays 3 elements of integer type.

Declaration of Three-Dimensional Array:


We can declare a 3D array with x 2D arrays each having y rows and z columns using the syntax shown below.
Syntax:➔
data_type array_name[x][y][z];
• data_type: Type of data to be stored in each element.
• array_name: name of the array
• x: Number of 2D arrays.
• y: Number of rows in each 2D array.
• z: Number of columns in each 2D array.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 18
Representation of Arrays: Row Major Order, and Column Major Order

• When it comes to organizing and accessing elements in a multi-dimensional array, two prevalent methods
are Row Major Order and Column Major Order.

• These approaches define how elements are stored in memory and impact the efficiency of data access in
computing.

Row Major Order


Row major ordering assigns successive elements, moving across the rows and then down the next row, to
successive memory locations. In simple language, the elements of an array are stored in a Row-Wise fashion.

To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.

How to find address using Row Major Order?

Q-Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1 Byte in
memory. Find the address of arr[8][6] with the help of row-major order.
Solution:Given: Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))

Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))


= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 19
Column Major Order
If elements of an array are stored in a column-major fashion means moving across the column and then to the next
column then it’s in column-major order.

To find the address of the element using column-major order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.

How to find address using Column Major Order?


Q-Given an array arr[1………10][1………15] with a base value of 100 and the size of each element is 1 Byte in
memory find the address of arr[8][6] with the help of column-major order.
Solution:Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157

To find the address of any element in 3-Dimensional arrays there are the following two ways:
• Row Major Order
• Column Major Order

Row Major Order:


To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = B + W *(M * N * (i-x) + N *(j-y) + (k-z))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 20
Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each element is 2
Bytes in memory find the address of element arr[5][-1][8] with the help of row-major order?
Solution:
Given:
Block Subset of an element whose address to be found I = 5
Row Subset of an element whose address to be found J = -1
Column Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -4
Lower Limit of column/start column index of matrix z = 5
M(row) = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N(Column)= Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6

Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))

Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]


= 400 + 2 * (6*6*4)+(6*3)+3
= 400 + 2 * (165)
= 730

Column Major Order:


To find the address of the element using column-major order, use the following formula:1
Address of A[i][j][k]= B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of block (first subscipt)
y = Lower Bound of Row
z = Lower Bound of Column

Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each element is 4
Bytes in memory find the address of element arr[3][3][3] with the help of column-major order ?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -5
Lower Limit of column/start column index of matrix z = -10
M (row)= Upper Bound – Lower Bound + 1 = 5 +5 + 1 = 11
N (column)= Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (j-y) + (k – z))

Address of arr[3][3][3] = 400 + 4 * ((11*16*(3-1)+11*(3-(-5)+(3-(-10)))

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 21
= 400 + 4 * ((176*2 + 11*8 + 13)
= 400 + 4 * (453)
= 400 + 1812
= 2212

Operations supported by an array.


2. Insertion
1. Traverse and display Write a program to insert a number at a given
Write a program to read and display n numbers location in an array.
using an array. #include <stdio.h>
int main()
#include <stdio.h> {
#include <conio.h> int i, n, num, pos, arr[10];
int main() clrscr();
{ printf("\n Enter the no of elements in the array : ");
int i, n, arr[20]; scanf("%d", &n);
clrscr(); for(i=0;i<n;i++)
printf("\n Enter the no of elements in the array : "); {
scanf("%d", &n); printf("\n arr[%d] = ", i);
for(i=0;i<n;i++) scanf("%d", &arr[i]);
{ }
printf("\n arr[%d] = ", i); printf("\n Enter the number to be inserted : ");
scanf("%d",&arr[i]); scanf("%d", &num);
} printf("\n Enter the position at which the number has
printf("\n The array elements are "); to be added : ");
for(i=0;i<n;i++) scanf("%d", &pos);
printf("\t %d", arr[i]); for(i=n–1;i>=pos;i––)
return 0; arr[i+1] = arr[i];
} arr[pos] = num;
Output n = n+1;
Enter the number of elements in the array : 5 printf("\n The array after insertion of %d is : ",
arr[0] = 1 num);
arr[1] = 2 for(i=0;i<n;i++)
arr[2] = 3 printf("\n arr[%d] = %d", i, arr[i]);
arr[3] = 4 return 0;
arr[4] = 5 }
Output
The array elements are 1 2 3 4 5 Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be
added : 3
The array after insertion of 0 is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 4
arr[5] = 5

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 22
4.Search &Update
3.Deletion #include<stdio.h>
Write a program to delete a number from a given int main()
location in an array. { int i,t,a[10],n,m,s,j=0,b[10];
printf("\nEnter the Limit:");
#include <stdio.h> scanf("%d",&n);
int main() printf("\nEnter the Values:");
{ for(i=0i<n;i++)
int i, n, pos, arr[10]; { scanf("%d",&a[i]);
clrscr(); }
printf("\n Enter the no of elements in the array : "); printf("\nGiven values are:");
scanf("%d", &n); for(i=0;i<n;i++)
for(i=0;i<n;i++) { printf("a[%d]=%d",i,a[i]);
{ }
printf("\n arr[%d] = ", i); printf("\nEnter the position to be update:");
scanf("%d", &arr[i]); scanf("%d",&t);
} printf("\nEnter the value to be update:");
printf("\nEnter the position from which the number scanf("%d",&s);
has to be deleted : "); for(i=0;i<n;i++)
scanf("%d", &pos); {
for(i=pos; i<n–1;i++) if(i==t)
arr[i] = arr[i+1]; { a[i]=s;
n– –; }
printf("\n The array after deletion is : "); }
for(i=0;i<n;i++) printf("\nUpdated value is:");
printf("\n arr[%d] = %d", i, arr[i]); for(i=0;i<n;i++)
return 0; { printf("\na[%d]=%d",i,a[i]);
} }
Output return 0;
Enter the number of elements in the array : 5 }
arr[0] = 1 Output
arr[1] = 2 Enter the limit:5
arr[2] = 3 Enter the values:1 2 3 4 5
arr[3] = 4 Given values are:
arr[4] = 5 a[0]=1
Enter the position from which the number has to be a[1]=2
deleted : 3 a[2]=3
The array after deletion is : a[3]=4
arr[0] = 1 a[4]=5
arr[1] = 2 Enter the position to be update:3
arr[2] = 3 Enter the value to be update:5
arr[3] = 5 Inserted value is:
a[0]=1
a[1]=2
a[2]=3
a[3]=5
a[4]=4
a[5]=5

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 23
2. Write a program to input two m x n matrices
Basic Operations on 2D array: and then calculate the sum of their corresponding
elements and store it in a third m x n matrix.
1.Write a program to transpose a 3 x 3 matrix. #include <stdio.h>
int main()
#include <stdio.h> {
int main() int i, j;
{ int rows1, cols1, rows2, cols2, rows_sum, cols_sum;
int i, j, mat[3][3], transposed_mat[3][3]; int mat1[5][5], mat2[5][5], sum[5][5];
clrscr(); clrscr();
printf("\n Enter the elements of the matrix "); printf("\n Enter the number of rows in the first
for(i=0;i<3;i++) matrix : ");
{ scanf("%d",&rows1);
for(j=0;j<3;j++) printf("\n Enter the number of columns in the first
{ matrix : ");
scanf("%d", &mat[i][j]); scanf("%d",&cols1);
} printf("\n Enter the number of rows in the second
} matrix : ");
printf("\n The elements of the matrix are "); scanf("%d",&rows2);
for(i=0;i<3;i++) printf("\n Enter the number of columns in the second
{ matrix : ");
printf("\n"); scanf("%d",&cols2);
for(j=0;j<3;j++) if(rows1 != rows2 || cols1 != cols2)
printf("\t %d", mat[i][j]); {
} printf("\n Number of rows and columns of both
for(i=0;i<3;i++) matrices must be equal");
{ exit(0);
for(j=0;j<3;j++) }
transposed_mat[i][j] = mat[j][i]; rows_sum = rows1;
} cols_sum = cols1;
printf("\n The elements of the transposed matrix are printf("\n Enter the elements of the first matrix ");
"); for(i=0;i<rows1;i++)
for(i=0;i<3;i++) {
{ for(j=0;j<cols1;j++)
printf("\n"); {
for(j=0;j<3;j++) scanf("%d",&mat1[i][j]);
printf("\t %d",transposed_ mat[i][j]);} }
return 0; }
} printf("\n Enter the elements of the second matrix ");
Output for(i=0;i<rows2;i++)
Enter the elements of the matrix {
123456789 for(j=0;j<cols2;j++)
The elements of the matrix are {
123 scanf("%d",&mat2[i][j]);
456 }
789 }
The elements of the transposed matrix are for(i=0;i<rows_sum;i++)
147 {
258 for(j=0;j<cols_sum;j++)
369 sum[i][j] = mat1[i][j] + mat2[i][j];
}
printf("\n The elements of the resultant matrix are ");
for(i=0;i<rows_sum;i++)
{

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 24
printf("\n"); {
for(j=0;j<cols_sum;j++) scanf("%d",&mat1[i][j]);
printf("\t %d", sum[i][j]); }
} }
return 0; printf("\n Enter the elements of the second matrix ");
} for(i=0;i<rows2;i++)
{
Output for(j=0;j<cols2;j++)
Enter the number of rows in the first matrix: 2 {
Enter the number of columns in the first matrix: 2 scanf("%d",&mat2[i][j]);
Enter the number of rows in the second matrix: 2 }
Enter the number of columns in the second matrix: 2 }
Enter the elements of the first matrix for(i=0;i<res_rows;i++)
1234 {
Enter the elements of the second matrix for(j=0;j<res_cols;j++)
5678 Arrays 103
The elements of the resultant matrix are {
68 res[i][j]=0;
10 12 for(k=0; k<res_cols;k++)
res[i][j] += mat1[i][k] * mat2[k][j];
3.Write a program to multiply two m x n }
matrices. }
#include <stdio.h> printf("\n The elements of the product matrix are ");
int main() for(i=0;i<res_rows;i++)
{ {
int i, j, k; printf("\n");
int rows1, cols1, rows2, cols2, res_rows, res_cols; for(j=0;j<res_cols;j++)
int mat1[5][5], mat2[5][5], res[5][5]; printf("\t %d",res[i][j]);
clrscr(); }
printf("\n Enter the number of rows in the first return 0;
matrix : "); }
scanf("%d",&rows1); Output
printf("\n Enter the number of columns in the first Enter the number of rows in the first matrix: 2
matrix : "); Enter the number of columns in the first matrix: 2
scanf("%d",&cols1); Enter the number of rows in the second matrix: 2
printf("\n Enter the number of rows in the second Enter the number of columns in the second matrix: 2
matrix : "); Enter the elements of the first matrix
scanf("%d",&rows2); 1234
printf("\n Enter the number of columns in the second Enter the elements of the second matrix
matrix : "); 5678
scanf("%d",&cols2); The elements of the product matrix are
if(cols1 != rows2) 19 22
{ 43 50
printf("\n The number of columns in the first matrix
must be equal
to the number of rows in the second matrix");
exit();
}
res_rows = rows1;
res_cols = cols2;
printf("\n Enter the elements of the first matrix ");
for(i=0;i<rows1;i++)
{
for(j=0;j<cols1;j++)

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 25
Pointer and 2D Array: Pointer and 3D Array
Write a program to read and display a 3 x 3 Write a program which illustrates the use of a
matrix. pointer to a three-dimensional array.
#include <stdio.h> #include <stdio.h>
#include <conio.h> int main()
void display(int (*)[3]); {
int main() int i,j,k;
{ int arr[2][2][2];
int i, j, mat[3][3]; int (*parr)[2][2]= arr;
clrscr(); clrscr();
printf("\n Enter the elements of the matrix"); printf("\n Enter the elements of a 2 \ 2 \ 2 array: ");
for(i=0;i<3;i++) for(i = 0; i < 2; i++)
{ {
for(j = 0; j < 3; j++) for(j = 0; j < 2; j++)
{ {
scanf("%d", &mat[i][j]); for(k = 0; k < 2; k++)
} scanf("%d", &arr[i][j][k]);
} }
display(mat); }
return 0; printf("\n The elements of the 2 \ 2 \ 2 array are: ");
} for(i = 0; i < 2; i++)
void display(int (*mat)[3]) {
{ for(j = 0; j < 2; j++)
int i, j; {
printf("\n The elements of the matrix are"); for(k = 0; k < 2; k++)
for(i = 0; i < 3; i++) printf("%d", *(*(*(parr+i)+j)+k));
{ }
printf("\n"); }
for(j=0;j<3;j++) return 0;
printf("\t %d",*(*(mat + i)+j)); }
} Output
} Enter the elements of a 2 \ 2 \ 2 array: 1 2 3 4 5 6 7 8
Output The elements of the 2 \ 2 \ 2 array are: 1 2 3 4 5 6 7 8
Enter the elements of the matrix
123456789 Note In the printf statement, you could also have used
The elements of the matrix are * ( * ( * ( a r r + i ) + j + ) + k ) instead of
123 *(*(*(parr+i)+j)+k)).
456
789

Advantages of using Arrays:


• Arrays allow random access to elements. This makes accessing elements by position faster.
• Arrays have better cache locality which makes a pretty big difference in performance.
• Arrays represent multiple data items of the same type using a single name.
• Arrays store multiple data of similar types with the same name.
• Array data structures are used to implement the other data structures like linked lists, stacks, queues, trees,
graphs, etc.

Disadvantages of Array:
• As arrays have a fixed size, once the memory is allocated to them, it cannot be increased or decreased,
making it impossible to store extra data if required. An array of fixed size is referred to as a static array.
• Allocating less memory than required to an array leads to loss of data.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 26
• An array is homogeneous in nature so, a single array cannot store values of different data types.
• Arrays store data in contiguous memory locations, which makes deletion and insertion very difficult to
implement. This problem is overcome by implementing linked lists, which allow elements to be accessed
sequentially.

Application of arrays
• They are used in the implementation of other data structures such as array lists, heaps, hash tables, vectors,
and matrices.
• Database records are usually implemented as arrays.
• It is used for different sorting algorithms such as bubble sort insertion sort, merge sort, and quick sort.
• It is used for implementing matrices.
• Graphs are also implemented as arrays in the form of an adjacency matrix.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 27
[T-6] Sparse Matrices and their representations

• A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n
values.
• If most of the elements of the matrix have 0 value, then it is called a sparse matrix.

Why to use Sparse Matrix instead of simple matrix?


• Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those
elements.
• Computing time: Computing time can be saved by logically designing a data structure traversing only non-
zero elements..
Example:
00304
00570
00000
02600

Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no
use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements.
This means storing non-zero elements with triples- (Row, Column, value).

Sparse Matrix Representations can be done in many ways following are two common representations:
1. Array representation
2. Linked list representation*

Method 1: Using Arrays:


2D array is used to represent a sparse matrix in which there are three rows named as
• Row: Index of row, where non-zero element is located
• Column: Index of column, where non-zero element is located
• Value: Value of the non zero element located at index – (row,column)

Implementation in C

// C program for Sparse Matrix Representation // using Array


#include<stdio.h>
int main()
{ // Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 28
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;

// number of columns in compactMatrix (size) must be equal to number of non - zero elements in sparseMatrix

int compactMatrix[3][size];

// Making of new matrix


int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}

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


{
for (int j=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);

printf("\n");
}
return 0;
}

Output
001133
242312
345726

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 29
Programs/Questions

1. What are arrays and why are they needed?


2. How is an array represented in the memory?
3. How is a two-dimensional array represented in the memory?
4. What is the use of multi-dimensional arrays?
5. Explain sparse matrix.
6. How are pointers used to access two-dimensional arrays?
7. Why does storing of sparse matrices need extra consideration? How are sparse matrices stored efficiently in the
computer’s memory?
8 Consider a two-dimensional array Marks [10][5] having its base address as 2000 and the number of bytes per
element of the array is 2. Now, compute the address of the element, Marks [8][5], assuming that the elements are
stored in row major order.
9. Write a program that reads an array of 100 integers. Display all the pairs of elements whose sum is 50.
10. Write a program to interchange the second element with the second last element.
11. Write a program that calculates the sum of squares of the elements.
12. Write a program to compute the sum and mean of the elements of a two-dimensional array.
13. Write a program to read and display a square (using functions).
14. Write a program that computes the sum of the elements that are stored on the main diagonal of a matrix using
pointers.
15. Write a menu driven program to read and display a 2D matrix. Also, find the sum, transpose, and product of
the two matrices.

Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 30

You might also like