Array

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

Problem : 5

int a = 0, b = 0;
for (i = 0; i < N; i++)
{
a = a + random();
}
for (j = 0; j < M; j++)
{
b = b + random();
}
Problem : 5

int a = 0, b = 0;
for (i = 0; i < N; i++)
{
a = a + random();
}
for (j = 0; j < M; j++)
{
b = b + random();
}

Answer :- O(N + M)
Problem :- 6

int a = 0;
for (i = 0; i < N; i++)
{
for (j = N; j > 0; j--)
{
a = a + i + j;
}
}
Problem :- 6

int a = 0;
for (i = 0; i < N; i++)
{
for (j = N; j > 0; j--)
{
a = a + i + j;
}
}

Answer:- O(N*N)
Problem:- 7

int a = 0, i = N;
while (i > 0)
{
a += i;
i /= 2;
}
Problem:- 7

int a = 0, i = N;
while (i > 0)
{
a += i;
i /= 2;
}

Answer:- O(Log2N)
Problem:- 8

for(i=0;i<n;i++)
i*=k
Problem:- 8

for(i=0;i<n;i++)
i*=k

Answer:- O(LogkN)
Unit-2
Linear Data Structure
(Array)
Array
• Definition & Declaration of array
• Reason of introducing Array data structure
• Representation of array
– Single dimensional array
– Multi dimensional array
• Sparse matrix
• Application of array
Concept of Array:-

Consider a situation in which we have 20 students in a class and we have been asked to
write a program that reads and prints the marks of all the 20 students.

• In this program, we will need 20 integer variables with different names,


- Now to read the values of these 20 variables, we must have 20 read statements.
- Similarly, to print the value of these variables, we need 20 write statements

• if it is just a matter of 20 variables, then it might be acceptable for the


user to follow this approach, But would it be possible to follow this approach if we have to
read and print the marks of students,

– in the entire course (say 100 students)


– in the entire college (say 500 students)
– in the entire university (say 10,000 students)

The answer is no, definitely not!


To process a large amount of data, we need a data structure Known as array.
Definition & Declaration of array
• An array is a collection of similar data elements.
• These data elements have the same data type.
• The elements of the array are stored in consecutive memory
locations and are referenced by an index.
• arrays are declared using the following syntax:
type name[size];
• For example,
int marks[10]; [Data type , Name , size]
• Arrays are generally used when we want to store large amount of
similar type of data.
• But they have the following limitations:
– Arrays are of fixed size.

– Data elements are stored in contiguous memory locations

– Insertion and deletion of elements can be problematic


because of shifting of elements from their positions
Single dimensional array

#include <stdio.h>
int main()
{
int array[10], i;
printf("\n Enter the size of the array: ");
scanf("%d", &size);

printf("\n Enter %d elements of the array: ", size);

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


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

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


Printf(“%d”, array[i]);

return 0;
}
Operations on array
• Traversing
• Insertion
• Deletion
• Searching
• Etc..
Algorithm for traversing an array (Traversing a Linear Array)
Here LA is a linear array with lower bound LB and upper bound UB.
This algorithm traverses LA applying an operation PROCESS to each
element of LA.

1. [Initialize counter] Set K := LB.

2. Repeat steps 3 and 4 while K <= UB.

3. [Visit element] Apply PROCESS to LA[K].

4. [Increment counter] Set K := K + 1. [End of Step 2 loop.]

5 . Exit.
Algorithm for inserting an element into an array (Inserting
into a linear array) 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 the Kth
position in LA.

1. [Initialize 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 counter.] Set J := J – 1. [End of Step 2 loop.]
5. [Insert element.] Set LA[K] := ITEM.
6. [Reset N.] Set N := N + 1.
7. Exit.
Algorithm for deleting an element from an array
(Deleting from a linear array) 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 the Kth element from LA.

1. Set ITEM := LA[K].

2. Repeat for J = K to N - 1.
[Move J + 1st element upward.] Set LA[J] := LA[J + 1].
[End of loop.]

3. [Reset the number N of elements in LA.] Set N := N - 1.

4. Exit.
Traversing example
WAP to find largest number from an array:
#include <stdio.h>
int main() 5
{
int array[10], size, i, largest;
3
10
printf("\n Enter the size of the array: ");
scanf("%d", &size); 3
4
printf("\n Enter %d elements of the array: ", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);

largest = array[0];

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


{
if (largest < array[i])
largest = array[i];
}
printf("\n largest element present in the given array is : %d",
largest);
return 0;
}
WAP to interchange min and max value from an array
#include<stdio.h>
5
#include<conio.h>
void main() 7
{ int a[5],max,min,maxpos,minpos,i,temp; 10
clrscr(); 1
printf("Enter 5 integers: "); 2
for(i=0;i<5;i++)
scanf("%d",&a[i]);
max=a[0]; temp=a[max];
min=a[0]; a[max]=a[min];
for(i=1;i<5;i++) a[min]=temp;
{ if(a[i]>max)
{ max=a[i];
maxpos=i; printf("After interchange array
} elemnts are: ");
if(a[i]<min) for(i=0;i<5;i++)
{ min=a[i]; printf("%d ",a[i]);
minpos=i; getch();
} }
}
Insertion operation
WAP to insert an element at given position from an array

#include <stdio.h> 2
int main()
5
{ int array[10], position, c, n, value;
99 10
printf("Enter number of elements in array\n"); 22
scanf("%d", &n);

printf("Enter %d elements\n", n);


for (c = 0; c < n; c++) for (c = n - 1; c >= position - 1; c--)
scanf("%d", &array[c]); { array[c+1] = array[c];}

array[position-1] = value;
printf("Enter the location where you wish to
printf("Resultant array is\n");
insert an element\n");
scanf("%d", &position); for (c = 0; c <= n; c++)
printf("%d\n", array[c]);
printf("Enter the value to insert\n");
scanf("%d", &value); return 0;
}
Deletion operation
WAP to delete an element at given position from an array 5
#include <stdio.h> 10
#define MAX_SIZE 10
20
int main()
{ int arr[MAX_SIZE]; 4
int i, size, pos;
clrscr();
else
printf("Enter size of the array : "); {for(i=pos-1; i<size-1; i++)
scanf("%d", &size); {
printf("Enter elements in array : "); arr[i] = arr[i+1];
for(i=0; i<size; i++) }
size--;
{
}
scanf("%d", &arr[i]);
printf("\nElements of array after
} delete are:");
printf("Enter the element position to delete : for(i=0; i<size; i++)
"); {
scanf("%d", &pos); printf("%d\t", arr[i]);
if(pos==size+1 || pos<0) }
{ getch();
printf("Invalid position! Please enter return 0;
position between 1 to %d", size); } }
Searching operation 5
10

#include<stdio.h> 1
44
int main() { 32
int a[30], ele, num, i;
clrscr(); i = 0;
printf("\nEnter no of elements :"); while (i < num && ele != a[i])
scanf("%d", &num); {
i++;
printf("\nEnter the values :"); }
for (i = 0; i < num; i++) { if (i < num) {
scanf("%d", &a[i]);
} printf("Number found at location = %d", i +1);
printf("\nEnter the elements to be }
searched :"); else {
scanf("%d", &ele); printf("Number not found");
}
getch();
return (0);
}
2 D array
• One-dimensional arrays are organized linearly in only one
direction.
• But at times, we need to store data in the form of grids or
tables.
• Here, the concept of single-dimension arrays is extended to
incorporate two-dimensional data structures.
• A two-dimensional array is specified using two subscripts
where the first subscript denotes the row and the second
denotes the column.

• Declaration of 2D array
• Ex:
– Int marks[3][3];
Write a program to represent 2D array matrix.
#include<conio.h>
#include<stdio.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("\nenter first matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ scanf("%d",&a[i][j]); }
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
getch();
}
Ex: addition in 2D array
Write a program to perform addition of matrix.

#include<conio.h>
for(i=0;i<3;i++)
#include<stdio.h>
{for(j=0;j<3;j++)
void main()
{
{int a[3][3],b[3][3],c[3][3],i,j; c[i][j]=a[i][j]+b[i][j];
clrscr(); }
printf("\nenter first matrix\n"); }
for(i=0;i<3;i++)
{ for(i=0;i<3;i++)
for(j=0;j<3;j++) {
for(j=0;j<3;j++)
{
{
scanf("%d",&a[i][j]);
printf("%d",c[i][j]);
}} }
printf("\n");
printf("\nenter second matrix\n"); }
for(i=0;i<3;i++)
{for(j=0;j<3;j++) getch();
{ }
scanf("%d",&b[i][j]);
}}
Multiplication of array
Write a program to perform multiplication of matrix.

#include<conio.h> printf("\nenter second


#include<stdio.h> matrix\n");
int main() for(i=0;i<3;i++)
{ { for(i=0;i<3;i++)
Int a[3][3],b[3][3],c[3][3],i,j; for(j=0;j<3;j++) {
Int sum=0,k; { for(j=0;j<3;j++)
scanf("%d",&b[i][j]); {
printf("\nenter first }} printf("%d",c[i][j]);
matrix\n"); }
for(i=0;i<3;i++) for(i=0;i<3;i++) printf("\n");
{ { }
for(j=0;j<3;j++) for(j=0;j<3;j++) }
{ {
scanf("%d",&a[i][j]); sum=0;
} for(k=0;k<3;k++)
} {sum=sum+a[i][k]*b[k][j];
}
c[i][j]=sum;
}}
Application of array
1. Symbol Manipulation (matrix representation of polynomial
equation)
2. Sparse Matrix

 Matrix representation of polynomial equation


 We can use array for different kind of operations in polynomial equation
such as addition, subtraction, division, differentiation etc…
 We are interested in finding suitable representation for polynomial so that
different operations like addition, subtraction etc… can be performed in
efficient manner.
 Array can be used to represent Polynomial equation.
Application of array
Y Y2 Y3 Y4
X XY XY2 XY3 XY4
X2 X 3Y X2Y2 X2Y3 X2Y4
X3 X 3Y X3Y2 X3Y3 X3Y4
X4 X 4Y X4Y2 X4Y3 X4Y4
Introducing sparse matrix terminology
• In computer programming, a matrix can be defined with a 2-
dimensional array.
• Any array with ‘m’ columns and ‘n’ rows represents a mXn matrix.
• There may be a situation in which a matrix contains more number of
ZERO values than NON-ZERO values.
• Such matrix is known as sparse matrix.

• Sparse matrix is a matrix which contains very few non-zero elements.


• When a sparse matrix is represented with 2-dimensional array, we
waste lot of space to represent that matrix.
• For example, consider a matrix of size 100 X 100 containing only 10
non-zero elements.
• In this matrix, only 10 spaces are filled with non-zero values and
remaining spaces of matrix are filled with zero.
• That means, totally we allocate 100 X 100 X 2 = 20000 bytes of space
to store this integer matrix.
• And to access these 10 non-zero elements we have to make
scanning for 10000 times.
• 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..

• Sparse Matrix Representations:


• following are two common representations:

– Array representation OR Triplet Representation


– 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)
Method 2: Using Linked Lists
• 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
Application of array
• Array Can be Used for Sorting Elements
• Array Can Perform Matrix Operation
• Arrays are used to implement Search Algorithms (Linear
Search, Binary Search)
• Arrays are used to implement Data structures (Stack, Queue
etc..)
• Array Can be Used in CPU Scheduling (CPU Scheduling is
generally managed by Queue. Queue can be managed and
implemented using the array)
• Array Can be Used in Recursive Function
• When the function calls another function or the same function
again then the current values are stores onto the stack and
those values will be retrieve when control comes back. This is
similar operation like stack.
• Arrays are used to implement mathematical vectors and
matrices.

You might also like