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

Legendary Arrays

The document discusses linear data structures and arrays. It defines arrays as collections of homogeneous elements that use contiguous memory allocation. Elements in an array can be accessed using their position index. Arrays provide advantages like code optimization, easy traversal and sorting of data, and random element access. However, arrays have a fixed size set at declaration. The document describes array declaration, initialization, passing arrays to functions, and common operations on arrays like traversal, insertion, deletion, searching, and updating elements.

Uploaded by

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

Legendary Arrays

The document discusses linear data structures and arrays. It defines arrays as collections of homogeneous elements that use contiguous memory allocation. Elements in an array can be accessed using their position index. Arrays provide advantages like code optimization, easy traversal and sorting of data, and random element access. However, arrays have a fixed size set at declaration. The document describes array declaration, initialization, passing arrays to functions, and common operations on arrays like traversal, insertion, deletion, searching, and updating elements.

Uploaded by

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

Dr.

Jyoti Srivastava

Linear Data Structure:


Arrays
Arrays

Array is a collection or group of elements (data).

All the elements are homogeneous (similar).

It has contiguous memory allocation.

Each array element can be accessed by its position in the sequence


of the array.

Static entity – same size throughout program


Arrays
C array is beneficial if you have to store similar elements. Suppose
you have to store marks of 50 students:
 One way to do this is allotting 50 variables.
 So it will be typical and hard to manage. For example we can not access
the value of these variables with only 1 or 2 lines of code.
 Another way to do this is array.
 By using array, we can access the elements easily. Only few lines of code
is required to access the elements of array.

To refer to an element, specify


 Array name and Position number
 Format: array_name[ position number ]
Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve


the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a


few lines of code only.

4) Random Access: We can access any element randomly using


the array index.
Disadvantage of C Array
Fixed Size:
Whatever size, we define at the time of declaration of
array, we can't exceed the limit.

So, it doesn't grow the size dynamically like Linked List


which we will learn later.
Declaration
When declaring arrays, specify
 Name
 Type of array
 Number of elements

data_type array_name[array_size];
 Examples:
oint a[20], b[3],c[7];
ofloat f[5], c[2];
ochar m[4], n[20];
oint marks[5];
Initialization
Initialization of an array is the process of assigning initial values.

 Examples (Declaration with Initialization):


oint a[4]={1,3,5,2};
ofloat b[3]={2.0, 5.5, 3.14};
ochar name[4]= {‘E’,’m’,’r’,’e’};
oint c[10]={0}; //All elements 0

If size omitted, initializers determine it


int n[ ] = { 1, 2, 3, 4, 5 };
 5 initializers, therefore 5 element array
Initialization

A simple way to initialize array is by index.

Notice that array index starts from 0 and ends with


[SIZE - 1].

 marks[0]=80;//initialization of array
 marks[1]=60;
 marks[2]=70;
 marks[3]=85;
 marks[4]=75;
Example
Write a program to calculate and print the average of the following
array of integers.
( 4, 3, 7, -1, 7, 2, 0, 4, 2, 13)

#include<stdio.h>
#define size 10
int main()
{
int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0;
float av;
for(i=0,i<=size-1;i++)
sum = sum + x[i];
av = (float)sum/size;
printf(“The average of the numbers=%.2f\n”, av);
return 0;
}
Passing Arrays to Functions
To pass an array argument to a function, specify the name of the array
without any brackets
functionname(arrayname);//passing array
Example:
int myArray[ 24 ];
myFunction( myArray);
Arrays passed call-by-reference
Name of array is address of first element
Function knows where the array is stored
 Modifies original memory locations
Passing Arrays to Functions

There are 3 ways to declare function that receives


array as argument.

1. return_type function(type arrayname[])

2. return_type function(type arrayname[SIZE])

3. return_type function(type *arrayname)


Passing Arrays to Functions

• Function prototype
void modifyArray(int b[], int arraySize);

• Parameter names optional in prototype


• int b[] could be written int []
• int arraySize could be simply int
Passing array to function example
#include <stdio.h> void main()
#include <conio.h> { minimum number is 3
int i=0,min=0;
int minarray(int arr[],int size){ int numbers[]={4,5,7,3,8,9};//declaration of array
clrscr();
int min=arr[0];
int i=0;
for(i=1;i<size;i++){ min=minarray(numbers,6);//passing array with size
if(min>arr[i]){
min=arr[i]; printf("minimum number is %d \n",min);
} getch();
}//end of for }
return min;
}//end of function
Operations on Arrays

1. Traversal
2. Insertion
3. Deletion
4. Searching
5. Update
6. Merging
Traversal

• Accessing each and every element of array for specific purpose.

• Traversing can include


•printing of elements,
•counting number of elements, or
•performing any processing on these
elements.
Algorithm for array traversal

STEP1: [Initialization] Set I = lower_bound

STEP2: Repeat steps 2 to 4 while I <= upper_bound

STEP3: Apply Process to A[I]

STEP4: Set I = I + 1
[End of Loop]
STEP5: Exit
Example

Assume that there is an array Marks[] such that the


index of the array specifies roll number and value
represents marks obtained. Ex. Marks[4] = 78.

1. Find the total number of students who have


secured 80 or more marks.

2. Print the roll number and marks of all students


who have got distinction.
Solution of 1
1. Find the total number of students who have secured 80 or
more marks.

STEP1: [Initialization] Set Count = 0


STEP2: Repeat for I = lower_bound to upper_bound
IF Marks[I] >= 80,
then : Set Count = Count + 1
[End of Loop]
STEP3: Exit
Solution of 2
2. Print the roll number and marks of all students who have got
distinction.

STEP1: Repeat for I = lower_bound to upper_bound


IF Marks[I] >= 75,
then : Write: I, Marks[I]
[End of Loop]
STEP2: Exit
Insertion

• Inserting an element in the array means adding a new data element in


an already existing array.

• If the element has to be inserted at the end, then task is simple.


Simply, increment upper_bound by 1 and assign the values.

• If an array is declared to contain 10 elements, but currently it has only


8 elements, then we can add two more elements. But if it already has
10 elements, then not possible.
Insertion

• Algorithm to append a new element to an existing array

STEP1: Set upper_bound= upper_bound + 1


STEP2: Set A[upper_bound] = VAL
STEP3: Exit
Insert an Element in Middle

• The algorithm will be declared as INSERT(A, N, POS, VAL).


1. A, the array in which element has to be inserted
2. N, the last offset in the array (last filled index)
3. POS, the position at which element has to be inserted
4. VAL, the value that has to be inserted
Insert an Element in Middle INSERT(A, N, POS, VAL)

Calling INSERT(DATA, 5, 3, 100)


45 23 34 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 23 34 12 56 20 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]

45 23 34 12 56 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]

45 23 34 12 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]

45 23 34 100 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]


Insert an Element in Middle
INSERT(A, N, POS, VAL)
INSERT(DATA, 5, 3, 100)
STEP1: [Initialization] Set I = N
STEP2: SET N = N + 1
STEP3: Repeat Steps 3 to 5 while I >= POS
STEP4: SET A[I+1] = A[I]
STEP5: SET I = I - 1
[End of Loop]
STEP6: SET A[POS] = VAL
STEP7: Exit

45 23 34 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]


Deletion

• Deleting an element from an array means removing a data element


from an already existing array.

• If the element has to be deleted from the end of the array, then quite
simple. Subtract 1 from upper_bound.

STEP1: Set upper_bound= upper_bound - 1


STEP2: Exit
Delete an Element in Middle

• The algorithm will be declared as DELETE(A, N, POS).


1. A, the array in which element has to be deleted
2. N, last offset in the array
3. POS, the position from which element has to be deleted
Delete an Element in Middle
DELETE(A, N, POS)
DELETE(Data, 5, 2)
45 23 34 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 23 12 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 23 12 56 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 23 12 56 20 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 23 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4]


Delete an Element in Middle
DELETE(A, N, POS)

DELETE(Data, 5, 2)

STEP1: [Initialization] Set I = POS


STEP2: Repeat Steps 3 and 4 while I <= N – 1
STEP3: SET A[I] = A[I + 1]
STEP4: SET I = I + 1
[End of Loop]
STEP5: SET N = N – 1
STEP6: Exit

45 23 34 12 56 20

Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]


Searching

• Searching means to find whether a particular value is present in the


array or not.

• Two popular methods:


1. Linear Search
2. Binary Search

Which one should I use? – Depends on the values.

• If values are sorted, then binary search is efficient.


Linear Search
• This is known as sequential search.

• Compares every element of the array one by one.


int A[] = {10, 8, 9 ,5, 1, 2};

• If we are searching for 9(VAL) then answer is 2(POS)

• Within this linear search, efficiency = O(n), where n is the number


of elements.

• Best Case: first element is the VAL.


efficiency = O(1)
Algorithm for Linear Search
LINEAR SEARCH(A, N, VAL, POS)
STEP1: [INITIALIZE] SET POS = -1
STEP2: [INITIALIZE] SET I = 0
STEP3: Repeat Step 4 while I<N
STEP4: IF A[I] = VAL, then
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
[END OF LOOP]
STEP5: PRINT “Value not present in array”
STEP6: EXIT
Binary Search

• Works efficiently with sorted data.


• Algorithm finds the position of a particular element in the array.
• Take an example: Dictionary

int A[] = {0, 1, 2,……,10}


VAL = 9 then BEG = 0, END = 10,
MID = (0+10)/2 = 5
Algorithm for
BINARY SEARCH(A, lower_bound, upper_bound, VAL, POS)

STEP1: [INITIALIZE] SET BEG= lower_bound, END = upper_bound, POS = -1


STEP2: Repeat Step 3 and Step 4 while BEG<=END
STEP3: SET MID = (BEG+END)/2
STEP4: IF A[MID] = VAL, then
POS = MID
PRINT POS
Go to Step 6
IF A[MID] > VAL then ;
SET END = MID - 1
ELSE
SET BEG = MID + 1
[END OF IF]
[END OF LOOP]
STEP5: PRINT “Value not present in array”
STEP6: EXIT
Update
Update operation refers to updating an existing element in the
array at a given index.

Example Algorithm:

Consider LA is a linear array with N elements


and K is a positive integer such that K<N.
Following is the algorithm to update an element available at the
Kth index of LA.

1. Start
2. Set LA[K] = ITEM
3. Stop
Merging
• Merging two arrays in a third array means first copying
contents of first array into the third array and then copying the
contents of the second array into third array.

Array -1 90 56 89 77 69

Array -2 45 88 99 58 81

Array -3 90 56 89 77 69 45 88 99 58 81

• The above example is only for unsorted arrays.


Merging

• If we have two sorted arrays, then resultant array should be


sorted.

Array -1 20 30 40 50 60

Array -2 15 22 31 45 56

Array -3 15 20 22 30 31 40 45 50 56 60
Pointer of Array

int arr[5] = {1, 2, 3, 4, 5};


int *ptr = &arr[0];
ptr++;
Array of Pointers

int *ptr[10];
int p = 1, q = 2, r = 3;
ptr[0] = &p;
ptr[1] = &q;
ptr[2] = &r;
Two Dimensional Array
• The two dimensional array is represented in the form of rows and
columns, also known as matrix.

• It is also known as array of arrays or list of arrays.

• The two dimensional, three dimensional or other dimensional arrays


are also known as multidimensional arrays.

• Used to store information that we normally represent in table form.

• Two-dimensional arrays, like one-dimensional arrays, are


homogeneous.
Two-Dimensional Arrays
• Examples:
• a seating plan for a room (organized
by rows and columns),

• a monthly budget (organized by


category and month),

• a grade book where rows might


correspond to individual students
and columns to student scores.
Declaration of two dimensional Array in C

• data_type array_name[row_size][column_size];

 Example: int twodimen[4][3];

• Initialization

1. At the time of declaration:


int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

2. Using loop
Two-Dimensional Array Initialization

int A[3][4] = {{8, 2, 6, 5}, //row 0


{6, 3, 1 ,0}, //row 1
{8, 7, 9, 6}}; //row 2
Two dimensional array example in C
#include <stdio.h>
#include <conio.h> arr[0][0] = 1
arr[0][1] = 2
void main(){
arr[0][2] = 3
int i=0,j=0; arr[1][0] = 2
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][1] = 3
clrscr(); arr[1][2] = 4
//traversing 2D array arr[2][0] = 3
arr[2][1] = 4
for(i=0;i<4;i++){ arr[2][2] = 5
for(j=0;j<3;j++){ arr[3][0] = 4
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); arr[3][1] = 5
}//end of j arr[3][2] = 6
}//end of i
getch();
}
Mapping 2D array to 1D array
We do need to map two dimensional array to the one dimensional
array in order to store them in the memory.

1. Row Major ordering


2. Column Major ordering
Row Major ordering
Column Major ordering
Calculating the Address of the
random element of a 2D array
• By Row Major Order
If array is declared by a[m][n] where m is the number of
rows while n is the number of columns, then address of an
element a[i][j] of the array stored in row major order is
calculated as,

Address(a[i][j]) = B. A. + (i * n + j) * size

where, B. A. is the base address or the address of the first


element of the array a[0][0] .
Calculating the Address of the
random element of a 2D array
• By Column major order

If array is declared by a[m][n] where m is the number of


rows while n is the number of columns, then address of an
element a[i][j] of the array stored in row major order is
calculated as,

Address(a[i][j]) = ((j*m)+i)*Size + BA

where BA is the base address of the array.


Operations on 2D Array
• Transpose

• Sum

• Difference

• Product
Sparse matrix
• Sparse matrix is a matrix which has many elements
with a value zero.

•Example:
00304
00570
00000
02600
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.
Lower-triangular Sparse matrix

• All elements above the main diagonal have a value zero.

1
53
271
3142
92817

• To store this, we can use 1D array which stores only non-zero


elements
Lower-triangular Sparse matrix

The mapping between 1D array and 2D matrix can be


done in two ways:

1. Row-wise mapping: the content of the array A[]


will be {1, 5, 3, 2, 7, 1, 3, 1, 4, 2, 9, 2, 8, 1, 7}

2. Column-wise mapping: the content of the array A[]


will be {1, 5, 2, 3, 9, 3, 7, 1, 2, 1, 4, 8, 2, 1, 7}
Upper-triangular Sparse matrix
• All elements below the main diagonal have a value
zero.

12345
6789
127
23
1
Sparse Matrix Representations
• 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

• Sparse Matrix Representations can be done in many ways. Following


are two common representations:

•Array representation
•Linked list representation
Array representation
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)
Linked list representation

• In linked list, each node has four fields. These four fields are
defined 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)
• Next node: Address of the next node
Linked list representation
Structures in C
• One of the unique features of the C language.

• Provide a method for packing together data of different types.

• A structure is a convenient tool for handling a group of logically


related data items.

• It is a user-defined data type with a template that serves to


define its data properties.

• Once the structure type has been defined, we can create


variables of that type using declarations that are similar to
the built-in type declarations.
Structures in C
• For example, consider the following declaration:
struct student
{
char name[20] ;
int roll_number;
float total_marks;
};
• The keyword struct declares student as a new data type that can
hold three fields of different data types.

• These fields are known as structure members or elements.

• The identifier student, which is referred to as structure name or


structure tag, can be used to create variables of type student.
Structures in C
• Example:
struct student A; // C declaration
• A is a variable of type student and has three member variables as
defined by the template.

• Member variables can be accessed using the dot or period


operator as follows:
strcpy (A.name, "John");
A.roll_number = 999;
A.total_marks = 595.5;
Final_total = A.total_marks + 5;

• Structures can have arrays, pointers or structures as members.


Arrays of Structures

•Example:
struct student A[90];

• Structures are generally used to hold the records.


Applications of Array

• Widely used to implement mathematical vectors,


matrices, and other rectangular tables.

• Many databases include 1D arrays whose elements


are records.

• To implement Data Structures like heaps, hash


tables, stacks, queue.

You might also like