0% found this document useful (0 votes)
19 views36 pages

Unit 3 - Arrays

The document provides an overview of arrays in programming, detailing their structure, declaration, and methods for accessing and manipulating elements. It covers operations such as insertion, deletion, and searching (linear and binary search) within arrays, along with relevant algorithms and example code snippets. Additionally, it explains how to calculate the address of array elements and the length of an array.

Uploaded by

Praghya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views36 pages

Unit 3 - Arrays

The document provides an overview of arrays in programming, detailing their structure, declaration, and methods for accessing and manipulating elements. It covers operations such as insertion, deletion, and searching (linear and binary search) within arrays, along with relevant algorithms and example code snippets. Additionally, it explains how to calculate the address of array elements and the length of an array.

Uploaded by

Praghya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Unit 3

Ch 12: ARRAYS
Introduction
 To process large amounts of data, we need a data structure
known as 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 (also
known as the subscript).
 Subscript is an ordinal number that is used to identify an
element of the array.
Declaration of Arrays
• An array must be declared before being used.
• Declaring an array means specifying three things:
o Data type- what kind of values it can store, Ex: int, char
o Name- to identify the array

o Size- the maximum number of values that the array can

hold. The size of the array is a constant and must have a


value at compilation time.
• Syntax: type name[size];
• Example: int marks[10];
• In C, the array index starts from zero.
Accessing the Elements of an Array
• For accessing an individual element of the array, the array subscript must be
used. For example, to access the 4th element of the array, we must write arr[3].
• The subscript must be an integral value or an expression that evaluates to an
integral value.
• To access all the elements of the array, we must use a loop. That is, we can
access all the elements of the array by varying the value of the subscript into
the array.

• Example: To set each element of the array to -1


int i, marks[10];
for(i=0; i<10; i++)
marks[i] = -1;
• The above code accesses every individual element of the array and sets its
value to -1.
Calculating the Address of Array Elements
• With the array name and the index, we can calculate address of any element
in the array.
• Array stores all its data elements in consecutive memory locations, storing
just the base address.
• The address of the other data elements can be calculated using the base
address.
• Formula for calculating the address of array elements is:
A[k] = BA(A) + w( k – lower_bound)
o Here, A is the array

o k is the index of the element of which we have to calculate the address

o BA is the base address of the array A.

o w is the word size of one element in memory, for example, size of int

is 2.
o Lower_bound is the index of the first element in the array.
Calculating the Address of Array Elements (Contd..)

• Given an array, int avg[] = {99, 67, 78, 56, 88}.


• Calculate the address of avg[2] if base address =1000.

99 67 78 56 88
avg [0] [1] [2] [3] [4]
1000 1002 1004 1006
1008
Storing an integer number requires 2 bytes, therefore word size
is 2 bytes.

Address(avg[2]) = 1000 + 2(2 – 0)


= 1000 + 2(2)
= 1004
Calculating the Length of an Array
● Length of the array is given by the number of elements
stored in it.
● The general formula to calculate the length of the 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.
99 67 78 56 88
avg [0] [1] [2] [3] [4]

Length = upper_bound – lower_bound + 1


Here, lower_bound=0, upper_bound=4
Therefore, Length = 4 – 0 + 1 = 5
Storing Values in Arrays

Initialize the elements


during declaration

Input values for the


Store values in an elements from the
array keyboard

Assign values to
individual elements
Initializing Arrays during Declaration
• Arrays are initialized by writing,
type array_name[size]={list of values};
• Example: int marks[5]={90, 82, 78, 95, 88};
• When initializing the array at the time of declaration, size of
the array can be omitted.
• Example: int marks[ ]={90, 82, 78, 95, 88};
int marks[5]={90, 82};
int marks[5]={0};
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]);
Assigning Values to Individual
Elements
Code to copy an array at the individual element level

int i, arr1[10], arr2[10];


for(i=0; i<10; i++)
arr2[i] = arr1[i];
Write a program to read and display n numbers using
an array.
#include<stdio.h>
int main()
{ int i=0, n, arr[20];
printf(“\n Enter the number of elements:“);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\n Arr[%d] = “, i);
scanf(“%d”,&num[i]); Output:
Enter the number of elements:3
}
Arr[0] = 10
printf(“\n The array elements are\n“); Arr[1] = 20
for(i=0;i<n;i++) Arr[2] = 30
printf(“Arr[%d] = %d\n”, i, arr[i]); The array elements are
Arr[0] = 10
return 0;
Arr[1] = 20
} Arr[2] = 30
Operations on Arrays

• There are a number of operations that can be performed on


arrays.
• These operations include the following:
Inserting an element in an array
Deleting an element from an array
Searching an element in an array
Inserting an Element in an Array

Algorithm to insert a new element to the end of an array

Step 1: Set upper_bound = upper_bound + 1


Step 2: Set A[upper_bound] = VAL
Step 3: EXIT
Inserting an Element in an Array

Algorithm to insert an element in the middle of an array


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

Step 1: [INITIALIZATION] SET I = N-1


Step 2: Repeat Steps 3 and 4 while I >= POS-1
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-1] = VAL
Step 7: EXIT
Inserting an Element in an Array (Contd..)
Example:
• Calling INSERT (Data, 6, 3, 100) will lead to the following
processing in the array.
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 34 12 56 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]

45 23 100 34 12 56 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]
Write a program to insert a number at a given location in an array.

#include <stdio.h> printf("\n Enter the position at which the


#include <conio.h> number has to be added: ");
int main() scanf("%d", &pos);
{
int i, n, num, pos, arr[10]; for(i=n-1;i>=pos-1;i--)
arr[i+1] = arr[i];
printf("\n Enter the number of elements in
the array: ");
scanf("%d", &n); arr[pos-1] = num;
n++;
for(i=0;i<n;i++)
{ printf("\n The array after insertion of %d
printf("\n Arr[%d] = : ", i); is: ", num);
scanf("%d", &arr[i]); for(i=0;i<n;i++)
} printf("\n Arr[%d] = %d", i, arr[i]);

printf("\n Enter the number to be inserted:


"); return 0;
Deleting an Element from an Array

Algorithm to delete an element from the end of the array

Step 1: Set upper_bound = upper_bound - 1


Step 2: EXIT
Algorithm to delete an element from
the middle of an array.
The algorithm DELETE will be declared as DELETE (A, N, POS)

Step 1: [INITIALIZATION] SET I = POS-1


Step 2: Repeat Steps 3 and 4 while I < N - 1
Step 3: SET A[I] = A[I + 1]
Step 4: SET I = I + 1
[End of Loop]
Step 5: SET N = N - 1
Step 6: EXIT
Algorithm to delete an element from the
middle of an array.
Example:
Calling DELETE (Data, 6, 2) will lead to the following processing
in the array.
45 23 34 12 56 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 34 34 12 56 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 34 12 12 56 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 34 12 56 56 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]
45 34 12 56 20 20
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]

45 34 12 56 20
Data[0] Data[1] Data[2] Data[3] Data[4]
Write a program to delete a number from a given location in an array.

#include <stdio.h> printf("\n Enter the position from


int main() which the no. has to be deleted: ");
{ scanf("%d", &pos);
int i, n, pos, arr[10];
for(i= pos-1; i<n-1;i++)
printf("\n Enter the size of the arr[i] = arr [i+1];
array:"); n--;
scanf("%d", &n); printf("\n The array after deletion
is:");
printf("\n Enter the elements of for(i=0;i<n;i++)
the array : "); printf("\n Arr[%d] = %d", i, arr[i]);
for(i=0;i<n;i++) return 0;
scanf("%d", &arr[i]); }
Searching for a value in an Array
• Searching means to find whether a particular value is present
in the array or not.
• If the value is present in the array, then search is said to be
successful and the search process gives the location of that
value in the array.
• Otherwise, if the value is not present in the array, the search
process displays the appropriate message and, in this case,
search is said to be unsuccessful.

• There are two methods for searching the array elements.


Linear Search
Binary Search
Linear Search
• Linear search, also called sequential search, is a simple
method used for searching an array for a particular value.
• It works by comparing every element of the array one by one
in sequence until a match is found.
• It is mostly used to search an unordered list of elements.
• The best case of linear search is when value is equal to the
first element of the array.
• The worst case will happen when either value is not present
in the array or it is equal to the last element of the array.
• In both the cases, n comparisons will be made.
Algorithm for Linear Search
LINEAR_SEARCH (A, N, VAL, POS)
Step 1: INITIALIZE] SET POS = -1
Step 2: INITIALIZE] SET I = 0
Step 3: Repeat Step 4 while I<N
Step 4: IF A[I] = VAL, then
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
[END OF LOOP]
Step 5: IF POS = -1
PRINT “Value Not Present In The Array”
[END OF IF]
Step 6: EXIT
Write a program to implement linear search.

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


main() {
{ if(arr[i] == num)
int arr[10], num, i, n, pos = -1; {
pos=i+1;
printf("\n Enter the number of printf("\n %d is found in the array at
elements in the array : "); position = %d", num, pos);
scanf("%d", &n); break;
}
printf("\n Enter the elements :"); }
for(i=0;i<n;i++) if (pos== -1)
scanf("%d", &arr[i]); printf("\n %d DOES NOT EXIST in the
array", num);
printf("\n Enter the number that has return 0;
to be searched : "); }
Binary Search
• Linear search algorithm is very slow on large array. However, if the
array is sorted then binary search is a better and efficient
alternative for searching.
• Binary search is a searching algorithm that works efficiently with
sorted list.
Mechanism applied to search for a value in a sorted array
• BEG = lower_bound and END = upper_bound
• MID = (BEG + END) / 2
• If VAL = A[MID], then end the search and set POS = MID.
• If VAL < A[MID], then VAL will be present in the left segment of
the array. So, the value of END will be changed as, END = MID–1
• If VAL > A[MID], then VAL will be present in the right segment of
the array. So, the value of BEG will be changed as, BEG = MID+1
• Finally, if VAL is not present in the array, then eventually END
will be less than BEG. When this happens, the algorithm will
terminate and the search will be unsuccessful.
Algorithm for Binary Search
BINARY_SEARCH(A, lower_bound, upper_bound, VAL, POS)
Step 1: [INITIALIZE] SET BEG = lower_bound, END = upper_bound, POS=-
1
Step 2: Repeat Step 3 and Step 4 while BEG <= END
Step 3: SET MID = (BEG + END)/2
Step 4: 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]
Step 5: IF POS = -1, then
PRINT “VAL IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step 6: EXIT
Write a program to implement binary search.

#include <stdio.h> while(beg <= end)


main() { mid = (beg + end)/2;
{ if (arr[mid] == num)
int arr[10], num, i, n, pos = -1, beg, end, mid, found {
=0; printf("\n %d is present in the array at position =
%d", num, mid+1);
printf("\n Enter the number of elements in the array: found=1;
"); break;
scanf("%d", &n);
}
if (arr[mid]>num)
end = mid-1;
printf("\n Enter the elements: ");
else
for(i=0;i<n;i++)
beg = mid+1;
{
}
scanf("%d", &arr[i]);
}
if (found == 0)
printf("\n %d DOES NOT EXIST IN THE
printf("\n Enter the number that has to be searched: ARRAY", num);
");
scanf("%d", &num); return 0;
}
Two Dimensional Arrays
• A two-dimensional array is specified using two subscripts where
one subscript denotes row and the other denotes column.
• C considers the two-dimensional array as an array of a one-
dimensional array.
• Figure below shows a two-dimensional array which can be
viewed as an array of arrays.
First Dimension

Second Dimension
Declaring Two-dimensional array
• A two-dimensional array is declared as:
data_type array_name[row_size][column_size];

• Therefore, a two-dimensional mXn array is an array that


contains m*n data elements and each element is accessed
using two subscripts, i and j where i<=m and j<=n.

• Example: int marks[3][5]


Rows/Columns Col 0 Col 1 Col2 Col 3 Col 4
Row 0 Marks[0][0] Marks[0][1] Marks[0][2] Marks[0][3] Marks[0][4]
Row 1 Marks[1][0] Marks[1][1] Marks[1][2] Marks[1][3] Marks[1][4]
Row 2 Marks[2][0] Marks[2][1] Marks[2][2] Marks[2][3] Marks[2][4]
Declaring Two-dimensional array
• There are two ways of storing a 2-D array in memory. The
first way is row major order and the second is column major
order.
• In the row major order, the elements of the first row are
stored before the elements of the second and third row.

(0,0) (0, 1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3) (2,0) (2,1) (2,2) (2,3)
• In the column major order, the elements of the first column
are stored before the elements of the second and third
column.

(0,0) (1, 0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) (0,2) (1,2) (2,2) (3,2)
Address of the elements is calculated
using the following formula.

• Address(A[I][J] = Base_Address + w{(M * J) + I },


if the array elements are stored in column major order.
• And, Address(A[I][J] = Base_Address + w{(N * I) + J},
if the array elements are stored in row major order.
Where,
• w is the word size of one element in memory
• M, is the number of rows
• N, is the number of columns
• I and J are the subscripts of the array element
Initializing Two-dimensional Arrays
• Arrays are initialized by writing,
type array_name[size][size]={list of values};

Example:
• int marks[2][3] = {90, 87, 78, 68, 62, 71};
• The initialization of two-dimensional array is done row by row.
• int marks[2][3] = {{90, 87, 78}, {68, 62, 71}};
• int marks[ ][3] = {{90, 87, 78}, {68, 62, 71}}; //Only size of 1st dimension
can be omitted.
• int marks[2][3] = {0}; //Entire 2D array is initialized to zero.
• int marks[ ][3] = {{90, 87, 78}}; //Elements of 2nd row will be initialized to
zero.

• Code to input the values from the keyboard into 2D array


int i, j, marks[2][3];
for(i=0; i<2; i++)
for(j=0; j<3; j++)
Write a program to read and print the elements of
a 2D array.
#include <stdio.h>
int main()
{
int i, j, arr[2][2];
printf(“Enter the array elements\n”);
for(i=0; i<2; i++)
for(j=0; j<2; j++)
scanf(“%d”, &arr[i][j]);

printf(“ The 2D array elements are:\n”);


for(i=0;i<2;i++)
{
printf("\n");
for(j=0; j<2; j++)
printf("%d\t", arr[i][j]);
}
return 0;
Operations on Two-dimensional Arrays
Following operations can be performed on an m X n matrix .

• Transpose:
Transpose - m X n matrix A is given as n X m matrix B where,B i,j =Aj,i
• Sum:
Two compatible matrices – added – storing result - third matrix. Two
matrices are compatible when they have same number of rows and
columns. Elements of the matrices - added by writing: C i,j =Ai,j + Bi,j
• Difference:
Two compatible matrices - subtracted – storing result - third matrix.
Elements of the matrices can be subtracted by writing: C i,j = Ai,j – Bi,j
• Product:
Two matrices - multiplied - if number of columns - first matrix =
number of rows - second matrix. Therefore, m X n matrix A -
multiplied with p X q matrix if n = p. Elements of the matrices can be
multiplied by writing: Ci,j =∑ Ai,k Bk,j for k=1 to k < n
Write a program to transpose a 3 × 3 matrix.
#include <stdio.h> for(i=0;i<3;i++)
int main() { printf("\n");
{ for(j=0;j<3;j++)
printf("%d\t", mat[i][j]);
int i, j, mat[3][3], transposed_mat[3][3];
}
for(i=0;i<3;i++)
printf("\nEnter the elements of the matrix"); { for(j=0;j<3;j++)
printf("\n*************************"); transposed_mat[i][j] = mat[j][i];
for(i=0;i<3;i++) }
printf("\nThe elements of the transposed
{ matrix are");
for(j=0;j<3;j++) printf("\n*************************");
{ for(i=0;i<3;i++)
scanf("%d", &mat[i][j]); { printf("\n");
}
for(j=0;j<3;j++)
printf("%d\t",transposed_mat[i][j]);
} }
printf("\nThe elements of the matrix are"); return 0;
printf("\n************************"); }

You might also like