Pop Module 3 Arrays
Pop Module 3 Arrays
Pop Module 3 Arrays
MODULE 3ARRAYS
WHY DO WE NEED ARRAYS?
Say we have a problem in our hand to store marks scored by 50 students in C language subject.
To store 50 marks we have to declare 50 variables of integer data type as shown below:
int marks_1, marks_2, marks_3, marks_4….............................. marks_50;
Now suppose we have to store values into these variables then 50 scanf statements or
initializing 50 values has to be done as shown:
scanf(“%d”, &marks_1);
scanf(“%d”, &marks_2);
scanf(“%d”, &marks_3);
…......................scanf(“%d”, &marks_50);
OR
marks_1= 25;
marks_2=23;
marks_3=20;
…...............so on marks_50=21;
marks_5
marks_4 15 0 21
So on…………
This style of programming is fine for a small set of values. But if we have to store 1000 or
10000 values declaring so many variables is a cumbersome process. Alternative solution is
Arrays!
An array is a collection of similar data elements. These data elements have the same
data type. The elements are stored in consecutive memory location and referenced by an
index(subscript). Subscript is an ordinal number which is used to identify an element of the
array.
1
MODULE 3 - ARRAYS
DECLARATION OF ARRAYS
Declaring an array means specifying three things:
• Data type – what kind of values it can store, for example int, char, float, double
• Name – to identify the array
• Size – the maximum number of values that the array can hold
In C, the array index starts from zero. The first element will be stored in
marks[0], the second element is stored in marks[1] and so on.
2
MODULE 3 - ARRAYS
In the for loop, first the value of marks[0] is set to 1, then the value of marks[1] and so on. The
procedure is continued until all the 10 elements of the array is set to 1.
Where upper_bound is the index of the last element and lower_bound is the index of the first
element in the array.
3
MODULE 3 - ARRAYS
Example 2:
int rollno[6] = {10, 11, 12};
Here, only 3 elements are initialized are given, hence the remaining values are
initialized to zero.
4
MODULE 3 - ARRAYS
Example 3:
int rollno[6] = {};
Example 4:
int rollno[] = {10, 11, 12, 13, 14, 15};
While initializing the array at the time declaration, the programmer may omit the size
of the array. Here, the compiler will allocate enough space for all initialized elements.
Inputting values from the keyboard
An array can be filled by inputting the values from the keyboard. This can be done
using looping statements.
int i, marks[5];
for (i=0; i<5; i++)
{
scanf("%d", &marks[i]);
}
In this loop, the iteration starts from 0 to 4 i.e it fills the values from first till last elements.
Assigning the values to individual elements
The third way is to use assignment operator in order to give elements their respective
values. Any value that evaluates to the data type of the array can be assigned to the individual
array element.
Example:
rollno[0] = 1;
Here, we are assigning value 1 st element of the array to 1.
//code to copy an array at the individual element level
5
MODULE 3 - ARRAYS
int i,arr1[10],arr2[10];
arr1[10]={0,1,2,3,4,5,6,7,8,9};
for (i=0; i<10; i++)
arr2[i]=arr1[i];
OPERATIONS ON ARRAYS
There are number of operations that can be performed on arrays. These operations
include the following:
• Traversing an array
• Inserting an element in an array
• Deleting an element in an array
• Merging two arrays
• Searching an element in an array
• Sorting an array
Traversing an array
Traversing an array means accessing each and every element of the array for the specific
purpose.
Algorithm for array traversal
Step 1: [INTIALIZATION] SET I=lower_bound
Step 2: Repeat Steps 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
I is initlaized to lower_boudn of the array. A while loop is executed until I value is less
than the upper_bound value. Step 3 process the individual array elements as specified by the
array name and index value.
6
MODULE 3 - ARRAYS
#include <stdio.h>
void main()
{
int arr[10],i,n;
clrscr();
printf("enter the number of elements");
scanf("%d", &n);
printf("enter elements in the array :\n");
for(i=0; i<n; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
Output:
enter the number of elements: 10
enter elements in the array :
element - 0 : 1
element - 1 : 1
element - 2 : 2
element - 3 : 3
element - 4 : 4
element - 5 : 5
element - 6 : 6
element - 7 : 7
element - 8 : 8
element - 9 : 9
7
MODULE 3 - ARRAYS
Output:
Enter the number of elements in the array
5
Enter 5 elements
1 2 3 4 5
Please enter the location where you want to insert a new element
3
Please enter the value
7
Resultant array is
1 2 3 7 4 5
Deleting an element from an array means removing a data element from an already
existing array.
Algorithm to delete the last element of an array
Step 1: SET upper_bound = upper_bound – 1
Step 2: EXIT
For example, if there are 54 students and the student with roll number 54 leaves the course then
we should just decrement the upper_bound.
The algorithm DELETE will be declared as (A,N,POS) where A is the array in which
9
MODULE 3 - ARRAYS
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,
Program:
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, pos, a [10];
clrscr ();
printf("\n Enter the size of the array:");
scanf("%d",&n);
printf("\n Enter the elements of the array: ");
for(i=0;i<n;i++)
{
scanf("%d", &a[i] );
}
printf("\n Enter the position from which the number has to be deleted: ");
scanf ("%d", &pos );
for(i= pos; i<n;i++)
{
a[i] = a [i+1];
n--;
printf("\n The array after deletion is:");
10
MODULE 3 - ARRAYS
}
for(i=0;i<n;i++)
{
Output:
Enter the size of the array: 5
Enter the elements of the array:
1 2 3 4 5
Enter the position from which the number has to be deleted: 3
The array after deletion is:
Arr[0]=1
Arr[1]=2
Arr[2]=3
Arr[3]=5
11
MODULE 3 - ARRAYS
{
int a1[25], a2[25], a3[50],n1,n2,i,m,index=0;
printf(" Enter the number of element in first array : ") ;
scanf("%d ",& n1) ;
printf("\n Enter the element of araay : \n") ;
for ( i = 0 ; i < n1 ; i++)
scanf("%d ",& a1[i]) ;
printf(" Enter the number of element in second array : ") ;
scanf("%d ",& n2) ;
printf("\n Enter the element of araay : \n") ;
for ( i = 0 ; i < n2 ; i++)
scanf("%d ",& a2[i]) ;
m = n1 + n2 ;
for ( i = 0 ; i <n1 ; i++)
{
a3 [index] = a1[i] ;
index++;
}
for ( i = 0 ; i <n2 ; i++)
{
a3 [index] = a2[i] ;
index++;
}
printf("\n Element of array after merging:\n") ;
for ( i = 0 ; i <m ; i++)
pcanf("%d \t",a3[i]) ;
return ( 0 ) ;
}
Output:
Enter the number of elements of the array 1:3
Enter the elements of the first array
10 20 30
Enter the number of elements of the array 2 :3
Enter the elements of the second array
15 25 35
Element of array after merging
10 20 30 15 25 35
12
MODULE 3 - ARRAYS
LINEAR SEARCH
Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.
Algorithm: LINEAR_SEARCH(A,N,VAL)
Step1: [INTIIALIZE] SET POS=-1
Step 2: [INTIIALIZE] SET I=1
Step 3: Repeat Step 4 WHILE I<=N
Step 4: IF A[I]=VAL
SET POS=I
PRINT POS
Go to Step 6
[END OF IF]
SET I=I+1
[END OF LOOP]
Step 5: IF POS=-1
Print “value is not present “
[END OF IF]
Step 6: EXIT
Program:
#include<stdio.h>
void main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
13
MODULE 3 - ARRAYS
if(key == a[i])
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
Output:
Enter the size of the array
5
Enter the elements of array
12 25 8 10 32
Enter the key element to be searched
3
The element 8 is found at 3
BINARY SEARCH
Binary search works only on a sorted set of elements. To use binary search on a
collection, the collection must first be sorted. The array is divided into two parts, compared
with middle element if it is not successful, then it is compared whether it is lesser or greater
than middle element. If it is lesser, search is done towards left part else right part.
Algorithm: BINARY_SEARCH(A,lower_bound,upper_bound,VAL)
Step1: [INTIIALIZE] SET low=lower_bound, high=upper_bound, POS=-1
14
MODULE 3 - ARRAYS
[END OF LOOP]
Step 5: IF POS=-1
Print “value is not present “
[END OF IF]
Step 6: EXIT
Program:
#include<stdio.h>
void main( )
{
int n, a[100], i, key, loc, high, low, mid;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
loc = mid+1;
break;
}
else
if(ele<a[mid])
high=mid-1;
15
MODULE 3 - ARRAYS
else
low=mid+1;
}
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);
else
printf("The search is unsuccessful\n");
}
Output:
Enter the size of the array
5
Enter the elements of array in sorted order
1 2 3 4 5
Enter the key element to be searched
4
The element 4 is found at 4
16
MODULE 3 - ARRAYS
The individual elements can be passed in the same manner as we pass variables of any
other data type. The condition is just that the data type of the array element must match with
the type of the function parameter.
main()
{
int arr[5]={1,2,3,4,5};
func(arr[3]);
}
void func(int num)
{
printf(“%d”,num);
}
In the above example, only one element of the array is passed to the calling function.
Single element arr[3] is passed to the function.
Passing Address
Address of an individual array element can be passed to the function using the addres
operator(&).
main()
{
int arr[5]={1,2,3,4,5};
func(arr[3]);
}
void func(int *num)
{
printf(“%d”,*num);
}
In the above example, the address of the fourth element is passed to the calling function.
In the called function the value of the array element must be accessed using the indirection (*)
operator.
int arr[5]={1,2,3,4,5};
func(arr);
}
void func(int arr[5])
{ int i;
for(i=0;i<5;i++)
printf(“%d”,arr[i]);
}
Output:
Enter the size of the array: 5
Enter the elements of the array: 1 2 3 4 5
The elements of the array are : 1 2 3 4 5
18
Arrays
TWO-DIMENSIONAL ARRAYS
A two-dimensional array is specified using two subscripts where one subscript denotes
row and the other denotes column. Two dimensional array can be viewed as an array of arrays
as shown below.
data_type array_name[row_size][column_size];
A two dimensional m X n array is an array that can contain 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];
A two-dimensional array called marks is declared that contains 3 rows and 5 columns.
There are two ways of storing a two-dimensional array in memory. The first ways is
row major order and the second is column major order. In row major order, the elements of
the first row are stored before the elements of the second and third row. i.e., the elements of
the array are stored row by row. In column major order, the elements of the first column are
stored before the elements of second and third column i.e., the elements of the array are
stored column by column.
1
Arrays
2
Arrays
• While initializing the size of the first dimension can be omitted. Therefore, the below
statement is valid.
• In order to initialize the entire 2D array to zero, we can write the following statement
int marks[3][4]= {0};
• If some values are missing during initialization, then it is automatically set to zero.
For example, the below statement will initialize the first row and the remaining
elements will be initialized to zero.
int marks[3][4]= {{1,2,3,4}};
• Individual elements can also be initialized using assignment operator as shown below:
marks[1][2]=10;
marks[2][1]=marks[1][1] + 10;
• In order to input the values from the keyboard, we must use the following code:
for(i=0; i<3; i++)
for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}
3
Arrays
C i, j = A i, j + B i, j
Difference: Two matrices that are compatible 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.
C i, j = A i, j - B i, 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. A matrix of order m X n can
be multiplied with the matrix of order p X q if n is equal to p.
4
Arrays
int main() {
int a[10][10], transpose[10][10], r, c,i,j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("\nEnter matrix elements:\n");
for ( i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
scanf("%d", &a[i][j]);
}
Output:
Enter rows and columns:
2
3
Enter matrix elements:
1 4 0 -5 2 7
5
Arrays
6
Arrays
Passing a Row: A row of a 2D array can be passed by indexing the array name with the row
number. When we send a single row of 2D array, then the called function receives a one-
dimensional array.
main()
{
int arr[2][3] = {{1,2,3},{4,5,6}};
func(arr[1]);
}
void func(int arr[])
{
7
Arrays
int i;
for(i=0;i<3;i++)
printf(“%d”,arr[i]);
}
Passing an Entire 2D array: To pass a 2D array to a function, array name can be used as the
actual parameter.
main()
{
int arr[2][3] = {{1,2,3},{4,5,6}};
func(arr);
}
void func(int arr[])
{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf(“%d”,arr[i][j]);
}
MULTIDIMENSIONAL ARRAY
A multidimensional array is an array of arrays.
8
Arrays
contain as many indices as needed and the requirement of the memory increases with number
of indices.
printf("\nDisplaying values:\n");
for (i = 0; i < 2;i ++)
{ printf(“\n\n”);
for (j = 0; j < 2; j++)
{ printf(“\n”);
for ( k = 0; k < 2;k ++)
{
printf("\t arr[%d] [%d] [%d]",i,j,k,a[i][j][k]);
}
}
}
return 0;
}
Output:
Enter the elements of the matrix
1 2 3 4 5 6 7 8
Displaying Values:
a[0][0][0] = 1 a[0][0][1] = 2
a[0][1][0] = 3 a[0][1][1] = 4
a[1][0][0] = 5 a[1][0][1] = 6
a[1][1][0] = 7 a[1][1][1] = 8
9
Arrays
SPARSE MATRICES
Sparse matrix is a matrix that has large number of elements with a zero value. There
are two types of sparse matrices.
• Lower triangular matrix: Here, all the elements above the main diagonal have zero
value
• Upper triangular matrix: In this matrix, all the elements below the main diagonal have
zero value.
10
Arrays
0 2 0
0 0 4
0 0 0
3 3 2
0 1 2
1 2 4
• The first row give the number of rows(3) , number of columns (3) and number of non-
zero elements(2) in the sparse matrix
• The second row specifies the location and value of first non-zero element. The first
non-zero value is 2 is at (0,1) location.
• Similarly, third row specifies the location and value of the next non-zero i.e, value 4
at (1,2) location.
APPLICATIONS OF ARRAYS
• Arrays are widely used to implement mathematical vectors, matrices and other
kinds of rectangular tables.
• Many databases include one-dimensional arrays where elements are recorded.
• Arrays are also used to implement other data structures such as strings, stacks,
queues, heaps and hash tables.
• Arrays can be used for sorting elements in ascending or descending order.
11
Arrays
#include<stdio.h>
void main( )
{
int i,j,n,temp,a[100];
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
Output
Enter the value of n
5
Enter the numbers in unsorted order
12
Arrays
67 89 4 35 23
The sorted array is
4 23 35 67 89
13