SlideShare a Scribd company logo
Arrays
Shillpi Mishrra
Contents
• Introduction
• Classification of arrays
• One-dimensional arrays
1.Declaration of One-dimensional arrays
2. Accessing the elements of an array
3.Calculating the address of array element
4.Calculating the length of an array
5.Storing values in array
6.Operations on array
• Two-dimensional array
1. Declaration of two-dimensional arrays
2. Accessing the elements of an array
3.Calculating the address of array element
4.Calculating the length of an array
5.Storing values in array
6.Operations on array
• Applications of arrays
Example……
Suppose, we have 10 students in a class and we have been asked to write a program that reads
and prints the marks of all 10 students. So, in this situation, we will need 10 integer variables
with different names. It is easy for us.
But, would it be possible to follow this approach if we have to read and print marks of 1000
students????????????
Actually, answer is no. It is impossible. To process large amount of data, we need a data
structure known as array.
Introduction
An array is a collection of homogeneous(similar type) elements. This means that an array can
store either all integers, all floating point numbers, all characters or any other complex
data type, but all of same type.
There are some important points to be pointed out about arrays. These are follows:
 An array can store multiple values which can referenced by a single name unlike a simple
variable which store one value at a time followed by an index or subscript.
 Arrays are always stored its elements in contiguous memory location.
 An array either be a integer, character or floating data type can be initialized only during
declaration time and not afterwards.
Consecutive Memory Location
• Consecutive means following each other continuously.
• Memory is just like a human brain. It is used to store data and instruction. Computer
memory is the storage space in computer where data is to be processed and
instructions are required for processing .
• Contiguous memory allocation is a classical memory allocation model that assigns a
process consecutive memory blocks (that is, memory blocks having consecutive
addresses).
• When a process needs to execute, memory is requested by the process. The size of
the process is compared with the amount of contiguous main memory available to
execute the process. If sufficient contiguous memory is found, the process is
allocated memory to start its execution. Otherwise, it is added to a queue of waiting
processes until sufficient free contiguous memory is available.
• How to allocate contiguous memory ?
1. Using static array declaration.
2.Using alloc() / malloc() function to allocate big chunk of memory
dynamically.
Classification of array
Arrays are classified into two types:
1.One-dimensional
2.two-dimensional
One-dimensional array
• A one-dimension array is one in which only one subscript specification is
needed to specify a particular element of the array.
• This type of array can be declared as follows:
Data_type var_name[size];
Data_type: the kind of values it can store either int, char ,float etc.
Var_name: specifies the name of array, it may be given any name like other
simple variables.
Size/subscript: the maximum number of values that array can hold. Always
remember, subscript (known as length or size of array) must be an integer
value.
If the array size is n, then array index always starts from 0 to n-1
Example: int num[10]; for this case, array size is n=10. so, index start from 0
to (10-1) . That means 0 to 9.
Continue……..
Suppose, the declaration look like follows:
int num[5];
That means, the array will store 5 integer values, its name is num.
Accessing the elements of an array
There is no single statement that can read, access or print all elements of an array. To
do this, we have to use a loop to execute the same statement with different index
values.
//set each element of the array -1
int i, marks[10];
for(i=0;i<10;i++)
marks[i]=-1;
Continue…………
Before slide, the code accesses every individual element of the array and sets its value to
-1.
In for loop, first the value of marks[0] is set to -1, then the value of index (i) is incremented
and next value marks[1] is set to -1. This procedure continues until all 10 elements of
the array are set to -1.
 Total memory allocated to an Array = Number of elements * size of one element
• Total memory allocated to an Integer Array of N elements = Number of elements * size
of one element
= N * 4 bytes
= 10 * 4 bytes = 40 Bytes, where N = 10
= 500 * 4 bytes = 2000 Bytes, where N = 500
• Total memory allocated to an character Array of N elements= Number of elements *
size of one element
= N * 1 Byte
= 10 * 1 Byte = 10 Bytes, where N = 10
= 500 * 1 Byte = 500 Bytes, where N=500
This is how memory is allocated for the single dimensional array.
Calculating the address of array element
• The formula to perform address of array element:
Address of data element, A[k]= BA(A) + W(k- lower_bound)
Here,
A is array, k is the index of the element of which we have to calculate the address, BA
is the base address of the array A and w is the size of one element in memory.
For example:
Given an array int marks[]={99,67,78,56,88,90}, calculate the address of marks[4] if the
base address=1000.
Continue………..
We know that storing an integer value requires 2 byte, its size is 2 bytes.
marks[4] = 1000+ 2(4-0)
= 1000+ 2(4) = 1008
Calculating the length of an array:
The length of an array is given by the number of elements stored in it. The
general formula to calculate the length of an array is:
Length= upper_bound - lower_bound +1
Where upper_bound is the index of the last element and lower_bound is the
index of the first element in the array.
Continue……..
The memory representation of the array Age[5] is given as below:
Let, Age[5] be an array of integers such that
Age[0]= 99, Age[1]= 67, Age[2]=78, Age[3]=56 and Age[4]= 88
Length= upper_bound - lower_bound +1
Here, upper_bound= 4 and lower_bound=0
Therefore, length= 4-0+1 = 5
Storing values in array:
There are three ways to store values in an array:
Continue………..
1. Initialized the elements during declaration:
The elements of an array can be initialized at the time of declaration. When
an array is initialized, we need to provide a value for every element in the array.
Arrays are initialized by:
Continue….
2. Inputting values from the keyboard:
An array can be initialized by inputting values from the keyboard.
Code for inputting each element of the array:
int i, marks[10];
for(i=0;i<10;i++)
scanf(“%d”,&marks[i]);
In the code, we start at the index i at 0 and input value for the first element of the
array. Since the array has 10 elements, we must input values for elements whose
index varies from 0 to 9.
Continue……..
3. Assigning the values to individual elements:
The third way is to assign values to individual elements of the array by using
assignment operator.
Suppose,
// fill an array with even numbers
int i, arr[10];
for(i=0;i<10;i++)
arr[i]= i*2;
In this code, the loop accesses each element of the first array and simultaneously
assigns its value to the corresponding element of the second array. The index i is
incremented to access the next element.
Then, arr[0]=0 , arr[1]=2, arr[2]=4 and so on.
Operations on one-dimensional array
There are a number of operations that can be performed on arrays. These operations
include:
 Traversing an array
 Inserting an element in an array
 Deleting an element from an array
 Merging two arrays
1. Traversing an array:
Traversing of the array an array means accessing each and every
element for a specific purpose. Array is a linear data structure, traversing its
elements is very simple and straight-forward.
Continue………
Algorithm for array traversal:
Step-1: [initialization] set i= lower_bound
Step-2: repeat step 3 to 4 while i<=upper_bound
Step-3: apply process to A[i]
Step-4: set i=i+1
[end of loop]
Step-5: exit
Explanation of the above algorithm:
In step-1, we initialize the index of lower_bound of the array.
In step-2, while loop is executed.
In step-3, process individual array element as specified by array name and index value.
In step-4, increments the index value so that next array element could be processed until
i less than or eaual to upper_bound.
Note: we can also use for loop . Then, algorithm will change.
Continue……
2. Inserting an element in an array:
Insertion of a new element in an array can be done in two ways:
a. Insertion at the end of array
b. Insertion at required position
a) If an element has to be inserted at the end of an existing array, then the task of insertion is
simple.
Algorithm to add a new element to an existing array:
Step-1: set upper_bound = upper_bound+1
Step-2: set A[upper_bound]=val
Step-3: exit
Explanation of above algorithm:
In step-1, we increment the value of upper-bound.
In step-2, the new value is stored at the position pointed by upper_bound.
Assume that the memory space allocated for the array is still available. If an array is declared to
contain 10 elements, but currently it has only 8 elements, then obviously there is space to
accommodate two more elements.
But, if it has 10 elements, then we will not be able to add another element to it.
Continue…………
b) If we have to insert an element in the middle of the array, then it is not a simple task.
Suppose we want to insert 20 in array , at location with index 4, it means the elements
22 onwards must be shifted downwards.
Continue………….
For inserting an element into linear array insert(A,N,pos, val) where a is linear array len be
total no of elements with in array pos is the position at which number num will be
inserted.
Algorithm for inserting new element at specific position:
Step-1: [initialize the value of i] set i= N
Step-2: Repeat step 3 to 4 while i >=pos
Step-3: set A[i+1] =A[i]
Step-4: set i=i-1
[end of loop]
Step-5: set N=N+1
Step-6: set A[pos]=val
Step-7: exit
Continue………..
Explanation:
In this algorithm,
A is the array in which the element has to be inserted.
N is the number of elements in the array.
Pos is the position at which the element has to be inserted.
Val is the value that has to be inserted.
In step-1, we first initialize i with the total number of elements in the array.
In step-2, a while loop is executed which will move all the elements having an index
greater than pos one position towards right to create space for the new element.
In step-5, we increment the total number of elements in the array by 1 and finally in
step-6, the new value is inserted at the desired position.
Continue…….
3. Deletion an element from an array:
Deletion of an element from an array can be done in two ways:
a. deletion at the end of array
b. deletion at required position
a) deletion from the end of array:
deletion an element from the end of an array means removing an data
element from an already existing array. If the element has to be deleted from the end
of existing array, then the task of deletion is quit simple.
Algorithm:
Step-1: set upper_bound= upper_bound-1
Step-2: exit
Continue…………
b) deletion at required position:
if we have to delete an element from particular position of an
array, then it will be tough task.
Continue…………
Algorithm:
Step-1: [initialization] set i = pos
Step-2: repeat step 3 to 4 while i <= n-1
Step-3: set a[i] =a[i+1]
Step-4: set i=i+1
[end of the loop]
Step-5: set n=n-1
Step-6: exit
This algorithm delete will be declared as delete(a, n, pos), where
1) a is the array from which the element has to be deleted.
2) n, the number of element in the array
3) pos, the position from which the element has to be deleted.
Continue…………
Explanation of previous algorithm:
Step-1: we first initialize i with the position from which the element has to be deleted.
Step-2 to step-4: while loop is executed which will move all the elements having an index
greater than pos one space towards left to occupy the space vacated by deleted
element.
Step-5: we decrement the total number of elements in the array by 1.
In the example in slide-10: calling delete( a, 6, 4) will lead to the above process.
Continue…………
4. Merging two arrays:
merging means combining elements of two arrays to form a new array.
There are two ways:
a) if the arrays are unsorted
b) if the arrays are sorted
a) If the array are unsorted:
if the arrays are unsorted, then merging is very simple. One just need to copy the
contents of one array into another.
Continue……….
Continue…..
• Code:
int main()
{
int arr1[10],arr2[10], arr3[20];
int i,n1,n2, m, index=0;
printf(“ enter the number of elements in arra1”);
scanf(“%d”,&n1);
printf(“enter the number of elements in arr2”);
scanf(“%d”,&n2);
for( i=0;i<n1;i++)
{
scanf(“%d”,&arr1[i]); taking input for 1st array
}
for( j=0;j<n2;j++)
{
scanf(“%d”,&arr2[i]); taking input for 2nd array
}
Continue…..
m=n1+n2;
for(i=0;i<n1;i++)
{
arr3[index] = arr1[i];
index ++;
}
for(i=0;i<n2;i++)
{
arr3[index] = arr2[i];
index ++;
}
printf(“nn the merged array is”);
for(i=0; i<m;i++)
{
printf(“ n arr[%d] =%d”, i , arr3[i]);
}
return 0;
}
Continue…..
b) If the arrays are sorted:
if the two arrays are sorted, then merged array also needs to be
sorted.
Two Dimensional Array
1D arrays are organized linearly in only one direction. But at times, we need to store data in
the form of tables.
Two dimensional array (2D array) is specified using two subscripts where first subscript
denotes the row and second denotes the column.
• This type of array can be declared as follows:
Data_type var_name[row_size][column_size];
Data_type: the kind of values it can store either int, char ,float etc.
Var_name: specifies the name of array, it may be given any name like other simple
variables.
Size/subscript: the maximum number of values that array can hold. Always remember,
subscript (known as length or size of array) must be an integer value.
A two dimensional m*n array is an array that contains m*n data elements and each element
accessed using two subscript, i, j , where i<=m and j<=n.
Continue…………
Example:
If we want to store the marks obtained by three students in five different
subjects, we can declare a 2D array:
int marks[3][5];
In the above statement, a 2D array called marks has been declared that has 3 row and 5
columns.
The pictorial form of a 2D array int marks[3][5] is:
Accessing the elements of two dimensional array
• The elements of 2D array are stored in contiguous memory locations.
• In case of 1D array, we used a single for loop to vary index i in every pass, so that all
elements should be scanned.
But 2D array contains two subscripts, we will use two for loops to scan the elements.
The first for loop will scan each row in the 2D array and second for loop will scan each column
in the 2D array.
Example:
int main()
{
int marks[2][2]= {23,56,76,11};
int i, j;
for(i=0;i<2;i++) for loop scan each elements of row
{
printf(“n”);
for(j=0;j<2;j++) for loop can each elements of column
printf(“%d”,marks[i][j]);
}
return 0;
}
Storing values in array:
There are two ways to store values in an array:
Continue…………
1) Initializing elements during declaraction:
The elements of an array can be initialized at the time of declaration. The
initialization of 2D array is done row by row.
Example:
int marks[2][3]={ 90,87,56,67,23,11} ; or int marks[2][3] ={{90,87,56},{67,23,11}};
Above both statements are correct.
Continue…………
2) Inputting values from the keyboard:
An array can be initialized by inputting values from the keyboard.
Code for inputting each element of the array:
Example:
int main()
{
int marks[10][10];
int i, j;
for(i=0;i<10;i++) for loop scan each elements of row
{
printf(“n”);
for(j=0;j<10;j++) for loop can each elements of column
scanf(“%d”,&marks[i][j]);
}
for(i=0;i<10;i++)
{
printf(“n”);
for(j=0;j<10;j++)
printf(“%d”,marks[i][j]);
}
return 0;
}
Calculating the address of array element
• The formula to perform address of array element:
If the array elements are stored in column major order, then
Address of data element, A[I][J] = Base_Address + W{ M (J-1) + (I-1) }
If the array elements are stored in row major order, then
Address of data element, A[I][J] = Base_Address + W{ N (I-1) + (J-1) }
Where, W is the number of bytes required to store one element, N is the number of
columns, M is the number of rows, I and J are the size or subscripts of the array
element.
Example:
Consider a (20*5) 2D array marks which has its base address=1000, the size of an
element=2, now compute the address of the element, marks[18][4] assuming that the
elements are stored in row major order.
Continue…………
Solution:
Address of data element, A[I][J] = Base_Address + W{ N (I-1) + (J-1) }
Address (marks[18][4])= 1000+ 2 { 5 ( 18-1) + (4-1) }
= 1000 + 176
= 1176
Operations of 2D array
The two-dimensional arrays can be used to implement the mathematical
concept of matrices. In mathematics, a matrix is a grid of numbers,
arranged in rows and columns.
Using two-dimensional array, we can perform the following operations on an
m* n matrix:
1. Sum
2. Difference
3. Transpose
4. Product
Sum
Two matrices that are compatible with each other can be added together, storing
the result in the third matrix.
Two matrices are said to be compatible when they have the same number of
rows and columns.
The elements of two matrices can be added :
C i,j = A i,j + B i,j
Difference
Two matrices that are compatible with each other can be subtracted, storing
the result in the third matrix.
Two matrices are said to be compatible when they have the same number
of rows and columns.
The elements of two matrices can be subtracted:
C i,j = A i,j - B i,j
Transpose
Transpose of an m*n matrix A is a given as a n*m matrix B, where Bi,j = Ai,j
Product:
Two matrices can be multiplied with each other if the number of columns in the first
matrix is equal to the number of rows in the second matrix.
m*n matrix A can be multiplied with a p*q matrix B if n=p
The dimension of the product matrix is m*q.
The elements of two matrices can be multiplied by:
Ci,j =∑ A i,k B k,j
Application of Array
• Arrays are widely used to implement mathematical vectors,
matrices and other kind of rectangular tables.
• Arrays are also used in implement other data structures such
as string, stacks, queues, heaps and hash tables.
• Arrays can be used for sorting elements in ascending or
descending order.

More Related Content

What's hot

Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
LATHA LAKSHMI
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injavairdginfo
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
Hock Leng PUAH
 
array
array array
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-stringsPrincess Sam
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8mlrbrown
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
7array in c#
7array in c#7array in c#
7array in c#
Sireesh K
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
SivaSankar Gorantla
 
Arrays
ArraysArrays
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
Gopal Ji Singh
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 

What's hot (20)

Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
Java arrays
Java arraysJava arrays
Java arrays
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
array
array array
array
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
Array lecture
Array lectureArray lecture
Array lecture
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
7array in c#
7array in c#7array in c#
7array in c#
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Arrays
ArraysArrays
Arrays
 

Similar to Arrays

arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
HarmanShergill5
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
HarsimranKaur362773
 
Arrays
ArraysArrays
Arrays
ViniVini48
 
unit 2.pptx
unit 2.pptxunit 2.pptx
unit 2.pptx
researchgrad82
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
MamataAnilgod
 
Programming fundamentals week 12.pptx
Programming fundamentals week 12.pptxProgramming fundamentals week 12.pptx
Programming fundamentals week 12.pptx
dfsdg3
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structures
Senthil Murugan
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
chin463670
 
Arrays accessing using for loops
Arrays accessing using for loopsArrays accessing using for loops
Arrays accessing using for loops
sangrampatil81
 
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
teddiyfentaw
 
Arrays
ArraysArrays
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
RockyIslam5
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
vrgokila
 
numpy.pdf
numpy.pdfnumpy.pdf
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
eShikshak
 
Chap 6 c++
Chap 6 c++Chap 6 c++

Similar to Arrays (20)

arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Arrays
ArraysArrays
Arrays
 
unit 2.pptx
unit 2.pptxunit 2.pptx
unit 2.pptx
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
Programming fundamentals week 12.pptx
Programming fundamentals week 12.pptxProgramming fundamentals week 12.pptx
Programming fundamentals week 12.pptx
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structures
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
Arrays accessing using for loops
Arrays accessing using for loopsArrays accessing using for loops
Arrays accessing using for loops
 
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Arrays
ArraysArrays
Arrays
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
numpy.pdf
numpy.pdfnumpy.pdf
numpy.pdf
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 

Recently uploaded

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
itech2017
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
AkolbilaEmmanuel1
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 

Recently uploaded (20)

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 

Arrays

  • 2. Contents • Introduction • Classification of arrays • One-dimensional arrays 1.Declaration of One-dimensional arrays 2. Accessing the elements of an array 3.Calculating the address of array element 4.Calculating the length of an array 5.Storing values in array 6.Operations on array • Two-dimensional array 1. Declaration of two-dimensional arrays 2. Accessing the elements of an array 3.Calculating the address of array element 4.Calculating the length of an array 5.Storing values in array 6.Operations on array • Applications of arrays
  • 3. Example…… Suppose, we have 10 students in a class and we have been asked to write a program that reads and prints the marks of all 10 students. So, in this situation, we will need 10 integer variables with different names. It is easy for us. But, would it be possible to follow this approach if we have to read and print marks of 1000 students???????????? Actually, answer is no. It is impossible. To process large amount of data, we need a data structure known as array.
  • 4. Introduction An array is a collection of homogeneous(similar type) elements. This means that an array can store either all integers, all floating point numbers, all characters or any other complex data type, but all of same type. There are some important points to be pointed out about arrays. These are follows:  An array can store multiple values which can referenced by a single name unlike a simple variable which store one value at a time followed by an index or subscript.  Arrays are always stored its elements in contiguous memory location.  An array either be a integer, character or floating data type can be initialized only during declaration time and not afterwards.
  • 5. Consecutive Memory Location • Consecutive means following each other continuously. • Memory is just like a human brain. It is used to store data and instruction. Computer memory is the storage space in computer where data is to be processed and instructions are required for processing . • Contiguous memory allocation is a classical memory allocation model that assigns a process consecutive memory blocks (that is, memory blocks having consecutive addresses). • When a process needs to execute, memory is requested by the process. The size of the process is compared with the amount of contiguous main memory available to execute the process. If sufficient contiguous memory is found, the process is allocated memory to start its execution. Otherwise, it is added to a queue of waiting processes until sufficient free contiguous memory is available. • How to allocate contiguous memory ? 1. Using static array declaration. 2.Using alloc() / malloc() function to allocate big chunk of memory dynamically.
  • 6. Classification of array Arrays are classified into two types: 1.One-dimensional 2.two-dimensional
  • 7. One-dimensional array • A one-dimension array is one in which only one subscript specification is needed to specify a particular element of the array. • This type of array can be declared as follows: Data_type var_name[size]; Data_type: the kind of values it can store either int, char ,float etc. Var_name: specifies the name of array, it may be given any name like other simple variables. Size/subscript: the maximum number of values that array can hold. Always remember, subscript (known as length or size of array) must be an integer value. If the array size is n, then array index always starts from 0 to n-1 Example: int num[10]; for this case, array size is n=10. so, index start from 0 to (10-1) . That means 0 to 9.
  • 8. Continue…….. Suppose, the declaration look like follows: int num[5]; That means, the array will store 5 integer values, its name is num.
  • 9. Accessing the elements of an array There is no single statement that can read, access or print all elements of an array. To do this, we have to use a loop to execute the same statement with different index values. //set each element of the array -1 int i, marks[10]; for(i=0;i<10;i++) marks[i]=-1;
  • 10. Continue………… Before slide, the code accesses every individual element of the array and sets its value to -1. In for loop, first the value of marks[0] is set to -1, then the value of index (i) is incremented and next value marks[1] is set to -1. This procedure continues until all 10 elements of the array are set to -1.  Total memory allocated to an Array = Number of elements * size of one element • Total memory allocated to an Integer Array of N elements = Number of elements * size of one element = N * 4 bytes = 10 * 4 bytes = 40 Bytes, where N = 10 = 500 * 4 bytes = 2000 Bytes, where N = 500 • Total memory allocated to an character Array of N elements= Number of elements * size of one element = N * 1 Byte = 10 * 1 Byte = 10 Bytes, where N = 10 = 500 * 1 Byte = 500 Bytes, where N=500 This is how memory is allocated for the single dimensional array.
  • 11. Calculating the address of array element • The formula to perform address of array element: Address of data element, A[k]= BA(A) + W(k- lower_bound) Here, A is array, k is the index of the element of which we have to calculate the address, BA is the base address of the array A and w is the size of one element in memory. For example: Given an array int marks[]={99,67,78,56,88,90}, calculate the address of marks[4] if the base address=1000.
  • 12. Continue……….. We know that storing an integer value requires 2 byte, its size is 2 bytes. marks[4] = 1000+ 2(4-0) = 1000+ 2(4) = 1008 Calculating the length of an array: The length of an array is given by the number of elements stored in it. The general formula to calculate the length of an array is: Length= upper_bound - lower_bound +1 Where upper_bound is the index of the last element and lower_bound is the index of the first element in the array.
  • 13. Continue…….. The memory representation of the array Age[5] is given as below: Let, Age[5] be an array of integers such that Age[0]= 99, Age[1]= 67, Age[2]=78, Age[3]=56 and Age[4]= 88 Length= upper_bound - lower_bound +1 Here, upper_bound= 4 and lower_bound=0 Therefore, length= 4-0+1 = 5
  • 14. Storing values in array: There are three ways to store values in an array:
  • 15. Continue……….. 1. Initialized the elements during declaration: The elements of an array can be initialized at the time of declaration. When an array is initialized, we need to provide a value for every element in the array. Arrays are initialized by:
  • 16. Continue…. 2. Inputting values from the keyboard: An array can be initialized by inputting values from the keyboard. Code for inputting each element of the array: int i, marks[10]; for(i=0;i<10;i++) scanf(“%d”,&marks[i]); In the code, we start at the index i at 0 and input value for the first element of the array. Since the array has 10 elements, we must input values for elements whose index varies from 0 to 9.
  • 17. Continue…….. 3. Assigning the values to individual elements: The third way is to assign values to individual elements of the array by using assignment operator. Suppose, // fill an array with even numbers int i, arr[10]; for(i=0;i<10;i++) arr[i]= i*2; In this code, the loop accesses each element of the first array and simultaneously assigns its value to the corresponding element of the second array. The index i is incremented to access the next element. Then, arr[0]=0 , arr[1]=2, arr[2]=4 and so on.
  • 18. Operations on one-dimensional array There are a number of operations that can be performed on arrays. These operations include:  Traversing an array  Inserting an element in an array  Deleting an element from an array  Merging two arrays 1. Traversing an array: Traversing of the array an array means accessing each and every element for a specific purpose. Array is a linear data structure, traversing its elements is very simple and straight-forward.
  • 19. Continue……… Algorithm for array traversal: Step-1: [initialization] set i= lower_bound Step-2: repeat step 3 to 4 while i<=upper_bound Step-3: apply process to A[i] Step-4: set i=i+1 [end of loop] Step-5: exit Explanation of the above algorithm: In step-1, we initialize the index of lower_bound of the array. In step-2, while loop is executed. In step-3, process individual array element as specified by array name and index value. In step-4, increments the index value so that next array element could be processed until i less than or eaual to upper_bound. Note: we can also use for loop . Then, algorithm will change.
  • 20. Continue…… 2. Inserting an element in an array: Insertion of a new element in an array can be done in two ways: a. Insertion at the end of array b. Insertion at required position a) If an element has to be inserted at the end of an existing array, then the task of insertion is simple. Algorithm to add a new element to an existing array: Step-1: set upper_bound = upper_bound+1 Step-2: set A[upper_bound]=val Step-3: exit Explanation of above algorithm: In step-1, we increment the value of upper-bound. In step-2, the new value is stored at the position pointed by upper_bound. Assume that the memory space allocated for the array is still available. If an array is declared to contain 10 elements, but currently it has only 8 elements, then obviously there is space to accommodate two more elements. But, if it has 10 elements, then we will not be able to add another element to it.
  • 21. Continue………… b) If we have to insert an element in the middle of the array, then it is not a simple task. Suppose we want to insert 20 in array , at location with index 4, it means the elements 22 onwards must be shifted downwards.
  • 22. Continue…………. For inserting an element into linear array insert(A,N,pos, val) where a is linear array len be total no of elements with in array pos is the position at which number num will be inserted. Algorithm for inserting new element at specific position: Step-1: [initialize the value of i] set i= N Step-2: Repeat step 3 to 4 while i >=pos Step-3: set A[i+1] =A[i] Step-4: set i=i-1 [end of loop] Step-5: set N=N+1 Step-6: set A[pos]=val Step-7: exit
  • 23. Continue……….. Explanation: In this algorithm, A is the array in which the element has to be inserted. N is the number of elements in the array. Pos is the position at which the element has to be inserted. Val is the value that has to be inserted. In step-1, we first initialize i with the total number of elements in the array. In step-2, a while loop is executed which will move all the elements having an index greater than pos one position towards right to create space for the new element. In step-5, we increment the total number of elements in the array by 1 and finally in step-6, the new value is inserted at the desired position.
  • 24. Continue……. 3. Deletion an element from an array: Deletion of an element from an array can be done in two ways: a. deletion at the end of array b. deletion at required position a) deletion from the end of array: deletion an element from the end of an array means removing an data element from an already existing array. If the element has to be deleted from the end of existing array, then the task of deletion is quit simple. Algorithm: Step-1: set upper_bound= upper_bound-1 Step-2: exit
  • 25. Continue………… b) deletion at required position: if we have to delete an element from particular position of an array, then it will be tough task.
  • 26. Continue………… Algorithm: Step-1: [initialization] set i = pos Step-2: repeat step 3 to 4 while i <= n-1 Step-3: set a[i] =a[i+1] Step-4: set i=i+1 [end of the loop] Step-5: set n=n-1 Step-6: exit This algorithm delete will be declared as delete(a, n, pos), where 1) a is the array from which the element has to be deleted. 2) n, the number of element in the array 3) pos, the position from which the element has to be deleted.
  • 27. Continue………… Explanation of previous algorithm: Step-1: we first initialize i with the position from which the element has to be deleted. Step-2 to step-4: while loop is executed which will move all the elements having an index greater than pos one space towards left to occupy the space vacated by deleted element. Step-5: we decrement the total number of elements in the array by 1. In the example in slide-10: calling delete( a, 6, 4) will lead to the above process.
  • 28. Continue………… 4. Merging two arrays: merging means combining elements of two arrays to form a new array. There are two ways: a) if the arrays are unsorted b) if the arrays are sorted a) If the array are unsorted: if the arrays are unsorted, then merging is very simple. One just need to copy the contents of one array into another.
  • 30. Continue….. • Code: int main() { int arr1[10],arr2[10], arr3[20]; int i,n1,n2, m, index=0; printf(“ enter the number of elements in arra1”); scanf(“%d”,&n1); printf(“enter the number of elements in arr2”); scanf(“%d”,&n2); for( i=0;i<n1;i++) { scanf(“%d”,&arr1[i]); taking input for 1st array } for( j=0;j<n2;j++) { scanf(“%d”,&arr2[i]); taking input for 2nd array }
  • 31. Continue….. m=n1+n2; for(i=0;i<n1;i++) { arr3[index] = arr1[i]; index ++; } for(i=0;i<n2;i++) { arr3[index] = arr2[i]; index ++; } printf(“nn the merged array is”); for(i=0; i<m;i++) { printf(“ n arr[%d] =%d”, i , arr3[i]); } return 0; }
  • 32. Continue….. b) If the arrays are sorted: if the two arrays are sorted, then merged array also needs to be sorted.
  • 33. Two Dimensional Array 1D arrays are organized linearly in only one direction. But at times, we need to store data in the form of tables. Two dimensional array (2D array) is specified using two subscripts where first subscript denotes the row and second denotes the column. • This type of array can be declared as follows: Data_type var_name[row_size][column_size]; Data_type: the kind of values it can store either int, char ,float etc. Var_name: specifies the name of array, it may be given any name like other simple variables. Size/subscript: the maximum number of values that array can hold. Always remember, subscript (known as length or size of array) must be an integer value. A two dimensional m*n array is an array that contains m*n data elements and each element accessed using two subscript, i, j , where i<=m and j<=n.
  • 34. Continue………… Example: If we want to store the marks obtained by three students in five different subjects, we can declare a 2D array: int marks[3][5]; In the above statement, a 2D array called marks has been declared that has 3 row and 5 columns. The pictorial form of a 2D array int marks[3][5] is:
  • 35. Accessing the elements of two dimensional array • The elements of 2D array are stored in contiguous memory locations. • In case of 1D array, we used a single for loop to vary index i in every pass, so that all elements should be scanned. But 2D array contains two subscripts, we will use two for loops to scan the elements. The first for loop will scan each row in the 2D array and second for loop will scan each column in the 2D array. Example: int main() { int marks[2][2]= {23,56,76,11}; int i, j; for(i=0;i<2;i++) for loop scan each elements of row { printf(“n”); for(j=0;j<2;j++) for loop can each elements of column printf(“%d”,marks[i][j]); } return 0; }
  • 36. Storing values in array: There are two ways to store values in an array:
  • 37. Continue………… 1) Initializing elements during declaraction: The elements of an array can be initialized at the time of declaration. The initialization of 2D array is done row by row. Example: int marks[2][3]={ 90,87,56,67,23,11} ; or int marks[2][3] ={{90,87,56},{67,23,11}}; Above both statements are correct.
  • 38. Continue………… 2) Inputting values from the keyboard: An array can be initialized by inputting values from the keyboard. Code for inputting each element of the array: Example: int main() { int marks[10][10]; int i, j; for(i=0;i<10;i++) for loop scan each elements of row { printf(“n”); for(j=0;j<10;j++) for loop can each elements of column scanf(“%d”,&marks[i][j]); } for(i=0;i<10;i++) { printf(“n”); for(j=0;j<10;j++) printf(“%d”,marks[i][j]); } return 0; }
  • 39. Calculating the address of array element • The formula to perform address of array element: If the array elements are stored in column major order, then Address of data element, A[I][J] = Base_Address + W{ M (J-1) + (I-1) } If the array elements are stored in row major order, then Address of data element, A[I][J] = Base_Address + W{ N (I-1) + (J-1) } Where, W is the number of bytes required to store one element, N is the number of columns, M is the number of rows, I and J are the size or subscripts of the array element. Example: Consider a (20*5) 2D array marks which has its base address=1000, the size of an element=2, now compute the address of the element, marks[18][4] assuming that the elements are stored in row major order.
  • 40. Continue………… Solution: Address of data element, A[I][J] = Base_Address + W{ N (I-1) + (J-1) } Address (marks[18][4])= 1000+ 2 { 5 ( 18-1) + (4-1) } = 1000 + 176 = 1176
  • 41. Operations of 2D array The two-dimensional arrays can be used to implement the mathematical concept of matrices. In mathematics, a matrix is a grid of numbers, arranged in rows and columns. Using two-dimensional array, we can perform the following operations on an m* n matrix: 1. Sum 2. Difference 3. Transpose 4. Product
  • 42. Sum Two matrices that are compatible with each other can be added together, storing the result in the third matrix. Two matrices are said to be compatible when they have the same number of rows and columns. The elements of two matrices can be added : C i,j = A i,j + B i,j
  • 43. Difference Two matrices that are compatible with each other can be subtracted, storing the result in the third matrix. Two matrices are said to be compatible when they have the same number of rows and columns. The elements of two matrices can be subtracted: C i,j = A i,j - B i,j
  • 44. Transpose Transpose of an m*n matrix A is a given as a n*m matrix B, where Bi,j = Ai,j Product: Two matrices can be multiplied with each other if the number of columns in the first matrix is equal to the number of rows in the second matrix. m*n matrix A can be multiplied with a p*q matrix B if n=p The dimension of the product matrix is m*q. The elements of two matrices can be multiplied by: Ci,j =∑ A i,k B k,j
  • 45. Application of Array • Arrays are widely used to implement mathematical vectors, matrices and other kind of rectangular tables. • Arrays are also used in implement other data structures such as string, stacks, queues, heaps and hash tables. • Arrays can be used for sorting elements in ascending or descending order.