DSA Module 1: Data Structures Overview
DSA Module 1: Data Structures Overview
MODULE-1
INTRODUCTION
TOPICS:
Introduction: Data Structures, Classifications (Primitive and Non-Primitive), Data Structures
Operations, Review of Arrays, Structures, Self-Referential Structures and Unions. Pointers and
Dynamic Memory Allocation Functions. Representation of Linear Arrays in Memory, Dynamically
Allocated Arrays.
Array Operations: Traversing, Inserting, Deleting, Searching and Sorting. Multidimensional
Arrays, Polynomials and Sparse Matrices.
1. INTRODUCTION
Data: The term ‘DATA’ simply refers to a value or a set of values. These values may present
anything about something, like it may be roll no of a student, marks, name of an employee,
address of person etc.
Data item: A data item refers to a single unit of value.
For Eg. roll no of a student, marks, name of an employee, address of person etc. are
data items.
Data items that can be divided into sub items are called Group items (Eg. Address,
date, name).
Data items which cannot be divided in to sub items are called Elementary items (Eg.
Roll no, marks, city, pin code etc.).
Entity: With similar attributes (Eg. all employees of an organization) form an entity set.
Information: Data with given attribute or processed data.
Field: Single elementary unit of information representing an attribute of an entity.
Record: It is the collection of field values of a given entity.
File: It 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 and the values K1, K2,
K3… in such a field are called keys or key values.
Here, it is an example of student details where STUDENT is the given entity. Then name,
age, sex, roll number, branch are attributes and their values are properties (A, 17, M, 109cs0132,
CSE). Collection of student details is student entity set and Roll number is the primary key which
uniquely indicates each student details.
DATA STRUCTURE
“Data Structure is a way of collecting and organizing data in such a way that the operations
on these data can be performed in an effective way”.
“Data structure can be defined as logical or mathematical model of a particular organization
of data.”
“Data structure is a representation of logical relationship existing between individual elements
of data”. In other words, a data structure defines a way of organizing all data items that
considers not only the elements stored but also their relationship to each other. The term data
structure is used to describe the way data is stored.
Data Structures is about rendering data elements in terms of some relationship, for better
organization and storage in computer.
To develop a program of an algorithm we should select an appropriate data structure for that
algorithm. Therefore, data structure is represented as:
Algorithm + Data structure = Program
For example, data can be player's name "Virat" and age 26. Here "Virat" is of String data type
and 26 is of integer data type. This data can be recorded as a Player record. Now, it is possible to
collect and store player’s records in a file or database as a data structure. For example: "Dhoni" 30,
"Gambhir" 31, "Sehwag" 33.
In simple language, “Data Structures are structures programmed to store ordered data, so that
various operations can be performed on it easily. It’s an arrangement of data in a computer’s memory.
Algorithms manipulate the data in these structures in order to accomplish some task”.
Definitions:
Primitive Data Structure: “A primitive data structure used to represent the standard data
types of any one of the computer languages”. Variables, pointers, etc. are examples of primitive
data structures. Simple data structure can be constructed with the help of primitive data structure.
Non-Primitive Data structure: “Non-Primitive data structure can be constructed with the
help of any one of the primitive data structures and it is having a specific functionality. It can be
designed by user”. Arrays, Structure, Union, linked list, Stacks, Queue, trees, graphs etc are
example for non-primitive data structures.
Trees: Trees are used to represent data that has some hierarchical relationship among the data
elements. (as shown in figure 2)
Figure 2: Trees
Graph: Graph is used to represent data that has relationship between pair of elements not
necessarily hierarchical in nature. For example electrical and communication networks, airline
routes, flow chart, graphs for planning projects.(as shown in figure 3)
Figure 3: Graph
(1) Traversing: Accessing each record exactly once so that certain items in the record may be
processed.
(2) Searching: Finding the location of a particular record with a given key value, or finding the
Each element can be accessed via its index. For example, we can fetch element at index 6 as
27.
ADT ARRAY
Objects: A set of pairs<index, value > where for each of index there is a value from the set item. Index
is a finite ordered set of one or more dimensions, for example {0,…,n-1} for one dimension,{(0,0
),(0,1),(0.2),(1,0),(1,2),(1,1),(2,1),(2,2),(2,0))} for two dimensions etc.
Functions:
For all A ∈ Array, I ∈ index, x ∈ item, j, size ∈ integer
1. Array create (j, list) = return an array of j dimensions where list is a j-tuple whose ith element is the
size of ith dimension. Items are undefined.
2. Item retrieve (A, i) = if (I ∈ index) return the item associated with index value i in array A else return
error.
3. Array store (A, i, x) = if (i in index) return an array that is identical to array A expect the new pair
<i,x> has been inserted else return error.
end Array
Initialization:
Initialize arrays at the time of declaration.
Syntax: data_type array_name[size] = {value1, value2,…..... valueN};
Where, 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:
1. Address of an data element in the array can be calculated as:
A[K]=BA(A)+W(K-LOWERBOUND);
Where, A is an array, K is the index of the element for which address has to be calculated , BA is
the base address of the array A and W is the size of one element in memory
2. Calculating the length of an array
Length = Upperbound-Lowerbound+1
Where , upperbound is index of the last element and lowerbound is index of the first element in
the array.
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: This program reads and displays 3 elements of integer type.
#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”);
}
}
Example: C Program to Increment every Element of the Array by one & Print Incremented
Array.
#include <stdio.h>
void main()
{
int i;
int array[4] = {10, 20, 30, 40};
for (i = 0; i < 4; i++)
arr[i]++;
OPERATIONS ON ARRAYS
INSERT(LA, N, K, ITEM)
HERE LA is a linear array with N elements and K is a positive integer such that K<=N. this
algorithm inserts an element ITEM into Kth position in LA.
1. [Initalize the counter]. Set J=N.
2. repeat steps 3 and 4 while J>=K
3. [move jth element downward] set LA[J+1]=LA[J].
4. [Decrease the counter] set J=J-1
[end of step 2 loop]
5. [insert element] set LA[K]A=ITEM
6. [reset N] set N=N+1
7. Exit
DELETE(LA, N, K, ITEM)
HERE LA is a linear array with N elements and K is a positive integer such that K<=N. this
algorithm deletes an element ITEM into Kth position in LA.
1. Set ITEM=LA[K]
2. repeat for J=K to N-1
3.[move j+1st element upward] set LA[J]=LA[J+1].
4.[end of step 2 loop]
5.[reset N] set N=N-1
6.Exit
BUBBLE SORT(DATA, N)
Here DATA is an array with N elements . THIS Algorithm sorts the elemts in DATA.
1. repeat steps 2 and 3 for k=1 to N-1
2. [Initalize the pass pointer PTR]. Set PTR=1.
3. Repeat while PTR<=N-K : [Executes pass]
(a) if DATA[PTR]>DATA[PTR+1] then
Interchange DATA[PTR] and DATA[PTR+1] [end of IF structure]
(b) set PTR=PTR+1
[End of inner loop]
[end of step1 outer loop]
4. Exit
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};
Example: int m[][3]={ {1,10}, {2,20,200}, {3}, {4,40,400} };
Suppose we have to find the location of A [3, 2]. The required values are:
Base (A) : 1000
w : 2 (because an integer takes 2 bytes in memory)
M : 3
J : 3
K : 2
Now put these values in the given formula as below:
= 1000 + 2 [3 + 2]
= 1000 + 2 [5]
= 1000 + 10 = 1010
we have to find the location of A [3, 2]. The required values are:
Base (A) : 1000
w : 4 ( integer takes 4 bytes in memory)
M : 3
J : 3
K : 2
= 1000 + 4 [3 + 2]
= 1000 + 4 [5]
= 1000 + 20 = 1020
Suppose we have to find the location of A [3, 2]. The required values are:
K : 2
Now put these values in the given formula as below:
LOC (A [3, 2]) = 1000 + 2 [4 (3-1) + (2-1)]
= 1000 + 2 [4 (2) + 1]
= 1000 + 2 [8 + 1]
= 1000 + 2 [9]
= 1000 + 18
= 1018
Example 1:
Write a C program to find sum of two matrices
#include <stdio.h>
#include<conio.h>
void main()
{
float a[2][2], b[2][2], c[2][2];
int i,j;
clrscr();
printf("Enter the elements of 1st matrix\n");
/* Reading two dimensional Array with the help of two for loop. If there is an array of 'n'
dimension, 'n' numbers of loops are needed for inserting data to array.*/
for(i=0;i<2;I++)
for(j=0;j<2;j++)
{
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
scanf("%f",&b[i][j]);
}
/* accessing corresponding elements of two arrays. */ for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
getch(); exit();
}
row3= row1; col3= col2;
printf(“\n Enter the elements of the first matrix”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
scanf(“%d”,&mat1[i][j]);
}
printf(“\n Enter the elements of the second matrix”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
scanf(“%d”,&mat2[i][j]);
}
for(i=0;i<row3;i++)
{
for(j=0;j<col3;j++)
{
mat3[i][j]=0;
for(k=0;k<col3;k++)
mat3[i][j] +=mat1[i][k]*mat2[k][j];
}
}
printf(“\n The elements of the product matrix are”):
for(i=0;i<row3;i++)
{
printf(“\n”);
for(j=0;j<col3;j++)
printf(“\t %d”, mat3[i][j]);
}
return 0;
}
Output:
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 2
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
1234
Enter the elements of the second matrix
5678
The elements of the product matrix are
19 22
43 50
printf("\n\n");
}
/* Finding transpose of matrix a[][] and storing it in array trans[][]. */
for(i=0; i<r;i++)
for(j=0; j<c; j++)
{
trans[j][i]=a[i][j];
}
/* Displaying the array trans[][]. */ printf("\nTranspose of Matrix:\n");
for(i=0; i<c;i++)
for(j=0; j<r;j++)
{
printf("%d ",trans[i][j]);
if(j==r-1)
printf("\n\n");
}
return 0;
}
STRUCTURE DEFINITION
“Structure is a collection of data items of same or dissimilar data type. Each data item is
identified by its name and type. (Or) A Structure is a user defined data type that can store related
information together. (Or) A structure is a collection of different data items / heterogeneous data items
under a single name.” The variable within a structure are of different data types and each has a name
that is used to select it from the structure.
C arrays allow you to define type of variables that can hold several data items of the same kind
but structure is another user defined data type available in C programming, which allows you to
combine data items of different kinds.
Structures are used to represent a record, Suppose, track of books are kept in a library are
recorded then it is required to track the following attributes about each book:
• Title
• Author
• Subject
• Book ID
STRUCTURE DECLARATION
It is declared using a keyword struct followed by the name of the structure. The members of the
structure are declared within the structure.
Example:
struct struct-name
{
data_type1 member_name1;
data_type2 member_name2;
.. ..
data_typen member_namen;
}structurevariablename;
STRUCTURE INITIALIZATION
Assigning values to the data members of the structure is called initializing of structure.
Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} structure variable={constant1,constant2};
scanf(‘’%s”,stud.name);
To print the values of structure variable stud, can be written as:
printf(“%d”,stud.roll);
printf(“%s”,stud.name);
Program to create a struct person , initializes its data member and print their values
#include<stdio.h>
#include<conio.h>
void main()
{
struct person
{
char name[10];
int age;
float salary;
};
struct person p1;
clrscr();
strcpy(p1.name,"james");
p1.age=10;
p1.salary=35000;
printf("\n name=%s age=%d salary=%f",p1.name,p1.age,p1.salary);
getch();
}
Array of Structures
An array of structure can also be declared. Each element of the array representing a structure
variable.
Example : struct employee emp[5];
The above code define an array emp of size 5 elements. Each element of array emp is of type employee
#include<stdio.h>
#include<conio.h>
struct employee
{
char ename[10];
int sal;
};
struct employee emp[5];
int i,j;
void ask()
{
for(i=0;i<3;i++)
{
printf("\nEnter %dst employee record\n",i+1);
printf("\nEmployee name\t");
scanf("%s",emp[i].ename);
printf("\nEnter employee salary\t");
scanf("%d",&emp[i].sal);
}
if((person1.age!=person2.age)
return FALSE;
if((person1.salary!=person2. salary)
return FALSE;
return TRUE;
}
void main()
{
if(humansEqual(person1,person2))
printf(“the two human beings are the same\n”);
else
printf(“the two human beings are not the same”);
}
else
return TRUE;
}
void main()
{
humanbeing p1,p2;
clrscr();
strcpy(p1.name,"hiiiii");p1.age=12;p1.salary=12000;
strcpy(p2.name,"hi");p2.age=12;p2.salary=12000;
if(humansEqual(p1,p2))
printf("\n persons are same ");
else
printf("\n persons are not same");
getch();
}
Pointers to Structures
Pointer to a structure is a variable that holds the address of a structure. The syntax to declare
pointer to a structure can be given as:
strcut struct_name *ptr;
eg: struct stud *ptr_stud;
To assign address of stud to the pointer using address operator(&) we would write ptr_stud=&stud; To
access the members of the structure (->) operator is used.
for example
ptr_stud->name=Raj;
Nested Structures
It is possible to embed a structure within a structure. “The structure that contains another
structure variable as its members is called a nested structure or a structure within a structure is
called nested structure.”
The structure should be declared separately and then be grouped into high level structure. The data
members of the nested structures can be accessed using (.) Dot operator.
Syntax to follow while accessing the data members of inner structure in nested structure with dot
operator is outer most structure variable. inner most structure variable. inner data member ;
Syntax to followed while accessing the data members of outer structure in nested structure with
dot operator is outer most structure variable .outer data member ;
Type1: declaring structure within a structure
Example :
struct student
{
char name[20];
int marks;
float per;
struct dob
{
int day,month,year;
}date;
}s1;
void main()
{
printf(“\n enter the student details-name marks percentage and date of birth”);
scanf (“%s%d%f%d%d%d”,s1.name,&s1.marks,&s1.per,&s1.date.day,&s1. date.month,
&s1.date.year);
printf(“the given student details is as follows”);
printf(“\n name =%s marks=%d percentage=%d dob=%d/%d/%d”, s1.name, s1.marks,s1.per,
s1.date.day,s1.date.month,s1. date.year);
getch();
}
Type 2: declaring a structure variable of one within another structure
Example :
struct dob
{
int day,month,year;
};
struct student
{
char name[20];
int marks;
float per;
struct dob date;
}s1;
void main()
{
printf(“\n enter the student details-name marks percentage and date of birth”);
scanf (“%s%d%f%d%d%d”,s1.name,&s1.marks,&s1.per,&s1.date.day,&s1. date.month,
&s1.date.year);
printf(“the given student details is as follows”);
printf(“\n name =%s marks=%d percentage=%d dob=%d/%d/%d”, s1.name, s1.marks,s1.per,
s1.date.day,s1.date.month,s1.date.year);
getch();
}
Nested structures with typedef
Example :
typedef struct
{
int month;
int day;
int year;
}date;
typedef struct
{
char name[10];
int age;
salary;
date dob;
}humanbeing;
humanbeing person1,person2;
If humanbeing person1 and person2 declares person1 and person2 variables of type humanbeing.
Then consider a person born on feb 11, 1944, can have the values for the date struct set as:
person1.dob.month=2;
person1.dob.day=11;
person1.dob.year=1944;
Similarly for considering person2, his dob is 3rd December 1956 then
person2.dob.month=12;
person2.dob.day=3;
person2.dob.year=1956;
Example 2:
typedef struct
{
char data;
struct list * link;
}list;
In this example each instance of the structure list have two components data and link.
Data is a single character, while link is a pointer to a list structure.
The value of link is either the address in memory of an instance of list or NULL pointer.
Program to illustrate self-referential structures
#include <stdio.h>
#include <conio.h>
typedef struct
{
char data;
struct list *link;
}list;
void main()
{
Dr. SL, VGK,SNK Dept of ISE, RNSIT Page 30
Data Structures and Applications [21CS32]
list l1,l2,l3;
l1.data='a';
l2.data='b';
l3.data='c';
l1.link=&l1;
l2.link=&l2;
l3.link=&l3;
printf("\n data values of l1=%d,l2=%d,l3=%d",l1.data,l2.data,l3.data);
printf("\n link of l1,l2,l3=%d %d %d",l1.link,l2.link,l3.link);
getch();
}
UNIONS
Union is a collection of variables of different data types. Union information can only be stored in
one field at any one time.
Definition: “A union is a special data type available in C that enables you to store different
data types in the same memory location. “
union can define many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.
Declaring Union:
union union-name
{
data_type1 member_name1;
data_type2 member_name2;
.. ..
data_typen member_namen;
}unionvariablename;
Example:
union data
{
char a;
int x;
float f;
}mydata;
The union tag is optional and each member definition is a normal variable definition, such as int
i; or float f; or any other valid variable definition.
At the end of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional. The memory occupied by a union will be large enough to hold the
largest member of the union. For example, in above example Data type will occupy 4 bytes of memory
space because this is the maximum space which can be occupied by float data.
1.The keyword struct is used to define a 1. The keyword union is used to define a union.
structure
2. When a variable is associated with a 2. When a variable is associated with a union,
structure, the compiler allocates the memory the compiler allocates the memory by
for each member. considering the size of the largest memory.
The size of structure is greater than or equal to So, size of union is equal to the size of largest
the sum of sizes of its members. The smaller member.
members may end with unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in 4. The address is same for all the members of a
ascending order. This indicates that memory union. This indicates that every member begins
for each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize 7. Only the first member of a union can be
at once. initialized.
Ex: struct Book Ex: union Book
{ {
int isbn; int isbn;
float price; float price;
char title[20]; char title[20];
}book; }book;
Total memory reserved will be Total memory reserved will be
Sizeof(int)+sizeof(float)+(20*sizeof(char)) Max(Sizeof(int)+sizeof(float)+(20*sizeof(char))
POINTERS
“Pointers are variables that hold address of another variable of same data type”,
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language.
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.
Concept of Pointer
Whenever a variable is declared, system will allocate a location to that variable in the memory,
to hold value. This location will have its own address number. Let us assume that system has allocated
memory location 80F for a variable a.
Example : int a = 10 ;
The value 10 can be accessed by either using the variable name a or the address 80F.Since the
memory addresses are simply numbers they can be assigned to some other variable. The variable that
holds memory address are called pointer variables. A pointer variable is therefore nothing but a
variable that contains an address, which is a location of another variable. Value of pointer variable will
be stored in another memory location.
Data type of pointer must be same as the variable, which the pointer is pointing. 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. In C language address operator & is
used to determine the address of a variable. The & (immediately preceding a variable name) returns the
address of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
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 *.
void main()
{
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 also print the address of p.
}
Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access
the array. Let’s have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We can also
use the Base address (a in above case) to act as pointer and print all the values.
Replacing the printf(“%d”,*p); statement of above example ,with below mentioned statements. Let’s see
what will be the result
printf(“%d”,a[i]); prints the array, by incrementing index
a++; compile time error, we cannot change base address of the array.
Example: a new area of memory is allocated using malloc().On success, malloc() returns a
pointer to the first byte of allocated memory. The returned pointer is of type void, which can be type cast
to appropriate type of pointer. The memory allocated by malloc() contains garbage value . when the
requested memory is not available, the pointer NULL is returned. when allocated memory is no longer
required , it is freed by using another function free().
void main()
{
int i,*pi;
float f,*pf;
pi=(int*)malloc(sizeof(int));
pf=(float*)malloc(sizeof(float));
*pi=1024;
*pf=3.14;
printf(“an interger=%d,an float number=%f”,*pi,*pf);
free(pi);
free(pf);
getch();
}
it shows allocation and deallocation of memory
if((pi=(int *)malloc(sizeof(int))==NULL) || (pf=(float*)malloc(sizeof(float))==NULL))
{
fprintf(stderr,”insufficient memory”);
exit(EXIT_FAILURE);
}
if(!(pi=malloc(sizeof(int))) || !(pf=malloc(sizeof(float)))
#define MALLOC(p,s)
If(!((p))=malloc(n,s))
{
fprintf(stderr,”insufficient memory”);
exit(EXIT_FAILURE);
}
thus ,MALLOC(pi, sizeof(int));
MALLOC(pf,sizeof(float));
int *x;
x=calloc(n,sizeof(int));
Instead of calloc function a calloc macro can be defined as sown below
#define CALLOC(p,n,s)
if(!((p))=calloc(n,s))
{
fprintf(stderr,”insufficient memory”);
exit(EXIT_FAILURE);
}
The function realloc resizes the memory allocated by either malloc or calloc.
Ex: realloc(p,s)
This realloc(p,s) function changes the size of the memory block pointed at p to s.the contents of
the first allocated s with oldsize bytes of the block are unchanged as a result of this resizing.when
s>oldsize the additional s-oldsize have an unspecified value and s<oldsize the rightmost oldsize-s bytes
of the old block are freed.when realloc is able to do the resizing it returns a pointer to the start of the
new block and when it is unable to do the resizing the old block is unchanged and function returns the
value NULL.
#define REALLOC(p,s)
if(!((p))=realloc(p,s))
{
fprintf(stderr,”insufficient memory”);
exit(EXIT_FAILURE);
}
//Sample program to illustrate macro Definition for malloc()
#include<stdio.h>
#define MALLOC(p,s) \
if(!((p)=malloc(s))) { \
fprintf(stderr, "Insufficient Memory");\
exit(1); \
}
void main()
{
int *p,i,n;
printf("Enter the no. of values\n");
scanf("%d",&n);
MALLOC(p,n*sizeof(int));
printf("Enter n values\n");
for(i=0;i<n;i++)
scanf("%d",(p+i));
printf("Values are\n");
for(i=0;i<n;i++)
printf("%d\t",*(p+i));
}
}
//Sample program to illustrate macro Definition for calloc()
#include<stdio.h>
#define CALLOC(p,n.s) \
if(!((p)=calloc(n,s))) { \
fprintf(stderr, "Insufficient Memory");\
exit(1); \
}
void main()
{
int *p,i,n;
printf("Enter the no. of values\n");
scanf("%d",&n);
CALLOC(p,n,sizeof(int));
printf("Enter n values\n");
for(i=0;i<n;i++)
scanf("%d",(p+i));
printf("Values are\n");
for(i=0;i<n;i++)
printf("%d\t",*(p+i));
}
The following functions are used in dynamic memory allocation and are defined in <stdlib.h>
1. malloc()
Declaration: ptr=(datatpe*) malloc(size)
This function is used to allocate memory dynamically. The argument size specifies the number
of bytes to be allocated. On success, malloc() returns a pointer to the first byte of allocated memory. The
returned pointer is of type void, which can be type cast to appropriate type of pointer. The memory
allocated by malloc() contains garbage value .
2. calloc()
Declaration: ptr=(datatype*)calloc(n,size);
This function is used to allocate multiple blocks of memory. The first argument specifies the
number of blocks and the second one specifies the size of each block. The memory allocated by calloc()
is initialized to zero.
3. realloc()
Declaration: ptr=(datatype*)realloc(ptr,newsize)
The function realloc() is used to change the size of the memory block. It alters the size of the
memory block without losing the old data. This function takes two arguments, first is a pointer to the
block of memory that was previously allocated by malloc() or calloc() and second one is the new size for
that block.
4. free();
Declaration: free(ptr);
This function is used to release the memory space allocated dynamically. The memory released
by free() is made available to the heap again and can be used for some other purpose. We should not try
to free any memory location that was not allocated by malloc(), calloc() or realloc().
C programming allots memory at heap during runtime
C provides two additional Dynamic memory allocation functions calloc and realloc . The calloc function
allocates a user specified amount of memory and initializes the allocated memory to 0 , a pointer to the
start of the allocated memoey is returned. In case ther is insufficient memory to make the allocation , the
returned value is NULL.so, the example statements could be used to define a one dimensional array of
integers with the capacity of this array is n and x ranges from 0 to n-1 with initially 0 value.
malloc() calloc()
The name malloc stands for memory The name calloc stands for contiguous
allocation. allocation.
malloc() takes one argument that calloc() take two arguments those are: number
is, number of bytes. of blocks and size of each block.
malloc is faster than calloc. calloc takes little longer than malloc because
of the extra step of initializing the allocated
memory by zero. However, in practice the
difference in speed is very tiny and not
recognizable.
MALLOC(list,n*sizeof(int));
This above main function fails only when n<1 or when sufficient memory is not allotted.
x[0]
x[1]
x[2]
Figure 9: Two dimensional array
C finds the element x[i][j] by first accessing the point in x[i].this pointer gives the address in memory of
the zeroth element of row I of the array. Then by adding j*sizeof(int) to this pointer , the address of the
[j]th elemnt of row i is determined.
Example program for allocating memory dynamically for 2D array
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int **a;
int p,q;
int ** make2darray();
printf(“\n enter the no of rows”);
scanf(“%d”,&p);
printf(“\n enter the no of cols”);
scanf(“%d”,&q);
a=make2darray(p,q);
printf(“successful memory creation address is”,a);
getch();
}
int **make2darray(int rows,int cols)
{
int **x,i;
x=malloc(rows*sizeof(*x));
for(i=0;i<rows;i++)
x[i]=malloc(cols*sizeof(**x));
return x;
}
Dr. SL, VGK,SNK Dept of ISE, RNSIT Page 47
Data Structures and Applications [21CS32]
APPLICATIONS OF ARRAYS
The two major applications of the arrays are polynomial and sparse matrix
1. POLYNOMIALS
Polynomial is a sum of terms where each term has a form axe, where x is the variable, a is the
coefficient and e is the exponent.
Examples :
A(x) = 3x20+2x5+4
B(x) = x4+10x3+3x2+1
The largest exponent of a polynomial is called its degree.
In the above example, degree of first polynomial is 20 and for the second polynomial it is 4.
Note: Coefficients that are zero are not displayed, the term with exponent zero does not show the
variable i.e. 4x2+5x+1 where 1 is a term having exponent zero so variable is not displayed.
Operations on polynomials
Addition
Subtraction
Multiplication
But division is not allowed.
Conisder a is of type polynomial and n>MAX_DEGREE then polynomial A(x)=∑aixi for i=0 to n
would be represented as
a.degree=n;
a.coef[i]=an-i,0<=i<=n.
Polynomial addition
Function which adds two polynomials A and B giving D, represented as D=A+B. using previous
polynomial representation the following figure 10 shows how two polynomials are represented
Ex: A(x) = 2x1000+1
B(x) = 1x4+10x3+3x2+1
startA++;
startB++;
break;
case 1: /*a.expon>b.expon*/
attach(terms[startA].coef,terms[startA].expon);
startA++;
}
for(;startA<=finishA;startA++)
attach(terms[startA].coef,terms[startA].expon);
for(;startB<=finishB;startB++)
attach(terms[startB].coef,terms[startB].expon);
*finishD=avail-1;
}
Function to add a new term
void attach(float coefficient ,int exponent)
{
if(avail>=MAX_TERMS)
{
printf(stderr,”too many terms in the polynomial\n”);
exit(0);
}
terms[avail].coef=coefficient;
terms[avail++].expon=exponent;
}
2. SPARSE MATRICES
Matrix contains m rows and n columns of elements. it has m rows and n columns. In general
mxn, is used to designate a matrix with m rows and n columns. The total no of elements in such matrix
is m*n. If m equals n then matrix is square.
“Sparse matrix: A matrix containing more number of zero entries, such matrix is called as
sparse matrix.”
In figure8, since this matrix contains many zeros it is called as sparse matrix. Here 8 of 36
elements are only having non-zero values so it is called as sparse matrix. When sparse matrix is
represented as two dimensional array hence space is wasted so need another form of representation to
save memory where only non-zero values are stored.
Transposing a Matrix
Transpose of a given matrix is obtained rows and columns. each element a[i][j].In the original
matrix becomes element b[j][i] in the transpose matrix.
The following algorithm is given by
The algorithm indicates that find all the elements in column 0 and store them in row 0 of the
transpose matrix, find all the elements in column1 and store them in row1 etc. Since the original matrix
ordered the rows, the columns within each row of incorporated in transpose. The first array a is the
original array which the second array b holds the transpose.(As shown in figure13)
b[0].value=n;
if(n>0)
{
currentb=1;
for(i=0;i<a[0].col;i++)
for(j=1;j<=n;j++)
if(a[j].col==i)
{
b[currentb].row=a[j].col;
b[currentb].col=a[j].row;
b[currentb].value=a[j].value;
currentb++;
}
}
}
PROGRAMMING EXAMPLES
1) Write a C program to sort N numbers in ascending order using Bubble sort and print both the
given and the sorted array
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}
2) Write a C program to input N numbers and store them in an array. Do a linear search for a
given key and report success or failure.
#include <stdio.h>
void main()
{
int array[10];
int i, num, keynum, found = 0;
clrscr();
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
3) Write a C program to input N numbers and store them in an array. Do a binary search for a
given key and report success or failure.
#include<stdio.h>
main()
{
int a[20],i,j,d,t,x,l=0,low,mid,high;
printf("\nEnter the number of elements\n");
scanf("%d",&d);
Dr. SL, VGK,SNK Dept of ISE, RNSIT Page 58
Data Structures and Applications [21CS32]
l++;
printf("The item %d is found at location %d\n",x,mid+1);
exit(0);
}
}
}
if(l==0)
printf("Item not found\n");
}
{
printf(“\n enter the roll number:”);
scanf(“%d”,&stud.roll_no);
}
printf(“\n enter the marks:”);
scanf(“%d”,&stud.marks);
if(choice == ‘Y’ || choice == ‘y’)
printf(“\n Name: %s”,stud.name);
else
printf(“\n Roll number: %d”, stud.roll_no);
printf(“\n Marks: %d”, stud.marks);
return 0;
}