0% found this document useful (0 votes)
56 views20 pages

Bca Unit 2 Data Structures

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)
56 views20 pages

Bca Unit 2 Data Structures

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
You are on page 1/ 20

UNIT-II

Arrays, Records and Pointers – Linear Arrays, Representation and Traversing


Linear Arrays, Inserting and Deleting. Passing an array to function, Pointer & Arrays
Multidimensional Arrays, Sparse Matrices.

DEPARTMENT OF COMPUTER SCIENCE


SPACES DEGREE COLLEGE
PAYAKARAOPETA
1
Q) Explain about Linear and Non-Linear Data structures?
Linear Data structures:

 Linear data structure is a Data Structure in which the data items or elements are
organised Linearly or Sequentially.
 It is a list which shows the relationship of adjacency between the elements.
 All the data items(elements) in a linear data structure can be traversed in single
run.
 It’s implementation is easy.
 It includes arrays, linked list, stack and queue data structures.

1. Arrays: Array is a group of consecutive memory locations that stores


homogenous or same type of data.
Each element of an array is referenced by index no or subscript no.

2. Linked list: Linked list is a collection of data elements. It consists of two parts:
data and Link.

Data presents elements and Link is an address of next node.

3. Stack: Stack is a linear list of elements in which the element is inserted or deleted
at one end called Top. It is follows Last-in-First-out (LIFO) organisation.

2
4. Queue: Queue is a linear list of elements in which the elements are added at one
end called rear and deleted from another end called front. It follows first-in-First-
out (FIFO) organisation.

Non-Linear Data Structures:

 It is a data structure where the data items or elements are not organized
sequentially is called non-linear data structure.
 The data elements of the non-linear data structure can be connected to more than
one element.
 In Non-linear data structure the relationship of adjacency is not maintained
between the data elements.
 All the data elements in non-linear data structure cannot be traversed in single
run.
 It’s implementation is complex.
 Examples of non-linear data structures are: Trees, Graphs
Tree:

A tree is collection of nodes where these nodes are arranged hierarchically and form a
parent child relationship.

3
Graph:

A Graph is a collection of a finite number of vertices and edges. Edges represent


relationships among vertices.

Q) Explain about different types of Arrays (******vvvimp******)


 Array is a group of consecutive memory locations which stores homogenous
(same) type of data.
 The elements in array are referred by using index no or subscript no.
 The subscript/index numbers begin from 0 to size-1.
 The lowest index is known as lower bound and the highest index is known as
upper bound.
 The no of subscripts indicates the dimension of the array

4
There are different types of arrays. They are

1. One Dimensional Arrays


2. Two-Dimensional Arrays
3. Multi-Dimensional Arrays

One Dimensional Arrays:

An array with only one subscript is known as one dimensional array


Declaration:
Datatype arrayname[size];

Datatype – specifies the type of array, it can be int, float, double , char etc
Arrayname is the userdefined name and size indicates no of elements in an array.
Example: int a[5];

The length of array is equal to no of elements in array.

Length= Upperbound(UB) – Lowerbound(LB) +1

In above, length= 4-0+1=5

Initialization of one Dimensional Array:

Assigning values to array at time of its declaration is known as Initialization of array.

Datatype arrayname[size]= { value1, value2…….value n};

Eg: int a[5]= { 11,22,33,44,55};

5
Accessing elements of the Array:

The individual elements in an array are accessed by using array name followed by
index no.

Syntax: arrayname [indexno];

Eg: a[3]=44;

Representation of Linear Arrays:

Arrayname itself indicates the starting address or base address. If we know the base
address, we can calculate the address of any element using the following formula.

K – index no base address=starting address of first element in array

W – width/size of each cell lowerbound=lower index no

Eg: a[4]=2000 + 2*[4-0]= 2000+8=2008

6
Operations of One-Dimensional Arrays:

1.creation : creating an empty array

2. insertion : Adding elements into array is known as insertion operation

3. Deletion : Removing elements from array is known as deletion operation

4. Traverse : Visiting or accessing each element of array is known as traverse


operation.

5. sorting : It is arranging the elements either in ascending or descending order.

6. Searching : Finding whether given element is found or not in an array.

7. Merging: combining two or more arrays is known as merging.

8. Reversing array : reversing elements in an array.

Two Dimensional Arrays:

An array with two subscripts is known as two-dimensional array


Declaration:
Datatype arrayname[rowsize] [ colsize];

Datatype – specifies the type of array, it can be int, float, double , char etc
Arrayname is the userdefined name
rowsize indicates no of rows and colsize indicates the no of cols.

Eg: int a[3][3];

7
Accessing elements of the Array:

The individual elements of a two-dimensional array is accessed by using array name


followed by rowno & colno.
Syntax: arrayname [row no] [col no];
Eg: a[2][2]=5;

Initialization of two-dimensional array:


Initialization means assigning values at the time of declaration.
Syntax: array name[row size][Col size]={{row1 values},{row2 values},..........};
Eg: a[2][3]={90,87,78},{68,62,71}};

Representation of two-dimensional arrays in memory

A two dimensional ‘m x n’ Array A is the collection of m X n elements.

8
To determine element address A[i,j]:

Location ( A[ i,j ] ) =Base Address + w*( n * I + j )

Base Address – starting address

W – Width or Size of each cell

N – No of cols

I – row no, j – Col no

Eg:

A[2,1]=2000+2* (3*2+1)=2000+14=2014

Operations of Two-Dimensional Arrays:

1.Addition of Two Matrices

2.Subtraction of Two Matrices

3. Multiplication of Two Matrices

4. Transpose of a matrix

5. Symmetric matrix or not

 A Multi-Dimensional array is an array having n indices and is a collection of m1


* m2 * m3 ......mn elements.
 The Three-dimensional Array is an example of multi-Dimensional array having
3 indices.
 The first index indicates the no of rows, second index indicates no of cols and
third index indicates the no of pages

9
Declaration :

Syntax: Datatype Arrayname[rows][cols][pages];

Eg: int a [2][3][4]

Q) Explain about operations of Single Dimensional Arrays?

 INSERTION:

Insertion operation refers to adding elements into array. We can add the elements from
beginning or last or at middle position.

Algorithm for insertion: INSERT(A,N, POS, ITEM)

1. Let I=N
2. IF I>= POS THEN
a) A[I+1]=A[I]
b) I=I-1
c) Goto step2
End IF
3. A[POS]=ITEM
4. SET N=N+1

10
 DELETION:

Deletion operation refers to removing elements from array. We can delete the
elements at beginning, last or at middle.

Algorithm for deletion: DELETION (A,N, POS)

1. Let ITEM=A[POS]
2. FOR I=POS TO N-1 REPEAT STEP 3
3. A[I]=A[I+1]
4. SET N=N-1
 TRAVERSE:

Visiting each and every element of an array is known as Traverse operation

Algorithm for traverse: Traverse (A,N)

1. FOR I=0 TO N-1


PRINT A[I]
 SEARCHING:Searching is the process of finding whether given element is
found in array or not.

Algorithm for Searching: SEARCH(A,LB,UB,KEY)

1) Let K = LB
2) Repeat , if K<=UB
a. If A[K]=KEY THEN
i. Print “item found at “ K position

End IF

b) K++
c) Goto step 2

End

11
 SORTING:

Sorting is the process of arranging the elements either in ascending order or


descending order.

Algorithm for Bubble sort : SORT(A,N)

start

1. for i=0 to N-1


2. for j=0 to N-i-1
a) if (a[ j ] > a[j+1])
Interchange a[j], a[j+1]
End-of-if Condition
End-of-for Loop
End-of-for Loop

3. for i=0 to N-1


print a[i]

end

Q) Expain about Records in data structure with an example?

 Record is a composite data type that groups together multiple related fields or
elements, each representing a specific attribute of a single entity.
 Each field in a record has a unique name and usually a specific data type, such as
integer, string, or date.

Characteristics of a Record:

1. Grouped Data: A record holds related information as a single unit.

2. Multiple Fields: Each record consists of multiple fields, with each field
representing an attribute of the entity.

12
3. Fixed Structure: Records generally have a fixed number of fields, defined by the
structure.

4. Single Entity Representation: A record represents a real-world entity, such as a


student, employee, or product, with each field representing a property of that entity.

5. Access by Field Name: Each field can be accessed independently using its name.

Example of a Record:

EmployeeID(integer) – a unique identifier.

Name(string) – the employee's name.

Position(string) – the job title.

Salary(float) – the employee’s salary.

Uses of Records in Data Structures:

1. Databases: Records form rows in database tables, with columns as fields.


2. Structs in Programming: In languages like C and C++, structs are used to
define records.
3. File Systems: Records are commonly used in file formats to store structured
data.

Example :

struct Employee {

int EmployeeID;

char Name[50];

char Position[30];

float Salary;

};

13
Q) Explain about Pointers in detail (OR) Overview of pointers

A pointer is a variable that contains the address of some memory location.

Uses:

1. Pointers are used as indirect reference to access memory locations


2. Pointers used to return more than one value from functions
3. Pointers used for accessing array elements.
4. Pointers used in creating complex data structures like linked list, trees, graphs
etc.
5. Pointers are used in dynamic memory allocation.
6. Pointers are used in passing function to another function
7. Pointers are used to improve the efficiency of certain routines.
Declaring of Pointer Variables:
Syntax: <data type> *ptrvar;
Here data type can be int, float, char etc.
Eg: int *p; p is a pointer pointing to integer address

& and * operators:


 The ‘&’ operator is known as address operator which gives the address of a
variable.
Eg: ‘&i’ returns the address of the variable i.
 The ‘*’ operator is called as “value at address operator”.
It returns the value stored at a particular address.

14
This operator also called as “indirection operator” and is used as a prefix to
pointer variable.
Eg: int *p; float *b;
Working with pointers:
 A pointer variable which stores the address of another pointer variable is known
as pointer to pointer.
int a=2;
int *b;
int **c;
b=&a;
c=&b;
 Various arithmetic operations can be performed on pointers like addition,
subtraction, preincrement, postincrement, predecrement, postdecrement.

Eg:
b=b+1=1000 + 1 * sizeof(int)=1000+2=1002
b=b-3 = 1000 – 3 *sizeof(int)=1000-3*2=1000 – 6=994

 Pointers are used in functions to return more than one value.


In call by reference mechanism the address of actual parameters are copied to
formal parameters (function parameters) and the function is executed with
formal and if any changes in formal will also
affect the actual parameters.
Eg: void main( )
{
swap(int*,int*);
int a=2,b=3;

15
swap(&a,&b);
printf(“%d%d”,a,b);
}

Q)Write shortnotes on pointers & arrays-5m(******imp***)


Pointer and Arrays:
An array is a group of consecutive memory locations which stores
homogenous type
of data.
int a[] = {1,2,3,4,5};
1 2 3 4 5
a [0] a [1] a[2] a[3] a[4]
1000 1002 1004 1006 1008
 The array name itself indicates the pointer to first element of that array. It is
known as the base address. In other words, base address is the address of the
first element in the array or the address of a [0].
 The first element of array can be expressed as a , second array element as (a+1)
and so on the ith element is expressed as (a+i)
 To obtain the contents we use
*(a+0) gives the first element of the array.
*(a+1) gives the second element of the array.
*(a+2) gives the third element of the array.
*(a+i) gives the ith element of the array.
Example:
main()
{
int a[20];
16
for(i=0;i<10;i++)
scanf(“%d”,(a+i));
for(i=0;i<10;i++)
printf(“%d”, *(a+i));
}
Pointer and 2D Arrays:
A two-dimensional array is a collection of one-dimensional arrays so we define two-
dimensional array as pointer to group of contiguous one-dimensional array.
Declaration:
datatype (*ptr)[colsize]
Eg: int (*a)[3];
Here a is a pointer to array of 3 elements.
In two dimensional array,
a+0 (or) a - pointer to first row
a+1 - pointer to second row
*(a+0) - pointer to first element of oth row
*(a+i) - pointer to first element of ith row
*(a+i)+j - pointer to jth element of ith row
*(*(a+i)+j) – gives the contents of jth element of ith row

Eg: main()
{
int (*a)[2], i,j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
scanf(“%d”,*(a+i)+j);
}
}

17
Q) Difference between Array and Pointer: (*********5m**********)

ARRAY POINTER
1)Array is a group of consecutive 1) pointer is a variable that contains
memory locations that stores address of another variable
homogenous type of data
2)Array names cannot be used as lvalue 2)Pointers can be used as values
Eg: int a[]={1,2,3} Eg: int a=5;
int b; int b;
b=a; //error p1=&a;
b=p1;
3)Array can’t be assigned to another 3)Pointers can be assigned to another
array pointer
Eg: if a,b are arrays a =b produces error Eg: p2=p1
4)Array name gives the address of array 4)Pointer name doesn’t specify any
address
5)sizeof operator with array gives the 5)sizeof operator with pointer returns
size of array the no of bytes used for pointer
variable

Q) Explain about sparse matrix with an example?


• A sparse matrix is a matrix in which most of the elements are zero.
• This means that only a small percentage of the matrix's elements are non-zero.
• Sparse matrices are common in many fields, such as scientific computing, data
mining, machine learning, and graph theory, where systems or datasets naturally
contain mostly zero values.

18
Representing a sparse matrix

 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 two common representations:

1. Array representation
2. Linked list representation

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)

Using Linked Lists:

In linked list, each node has four fields. These four fields are defined as:

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

Next node: Address of the next node

Implementation of array representation of the sparse matrix:

#include <stdio.h> for(int i=0; i<4; i++)


void main {
{ for(int j=0; j<5; j++)
int sparse_matrix[4][5] = {
{ if(sparse_matrix[i][j]!=0)
{0 , 0 , 6 , 0 , 9 }, {
{0 , 0 , 4 , 6 , 0 }, matrix[0][k] = i;
{0 , 0 , 0 , 0 , 0 }, matrix[1][k] = j;
{0 , 1 , 2 , 0 , 0 } matrix[2][k] =
}; sparse_matrix[i][j];
int size = 0; k++;
for(int i=0; i<4; i++) }
{ }
for(int j=0; j<5; j++) }
{ for(int i=0 ;i<3; i++)
if(sparse_matrix[i][j]!=0) {
{ for(int j=0; j<size; j++)
size++; {
} printf("%d ", matrix[i][j]);
} printf("\t");
} }
printf("\n");
int matrix[3][size]; }
int k=0; }

20

You might also like