Pop Module 3 Arrays

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

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_1 25 marks_2 23 marks_ 20

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

Syntax: type name[size];


Example: int marks[5];

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

ACCESSING THE ELEMENTS OF AN ARRAY


Accessing the array element is done using a loop statement in combination with printf
statements or any other processing statements. Example of accessing the array elements and
calculating total marks is given below:
Example code to initialize each element of the array to 1.
int i,marks[10];
for(i=0;i<10;i++)
marks[i]=1;

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.

CALCULATING THE ADDRESS OF ARRAY ELEMENTS


Array name is the symbolic reference to the address of the first byte of the array. The
subscript or the index represents the offset from the beginning of the array to the element being
referenced. To calculate the address of array elements, the formula used is

A[k]= BA(A) + w(k-lower_bound)


Here, A is the array
k is the index of the element for which we have to calculate the address
BA is the base address of the array A
w is the word size of one element in the memory
lower_bound is the index of the first element of the array

Example: Given an array int marks[]= {99,67,78,56,88,90,34,85}. Calculate the address of


marks[4] if base address=1000.

Word size is 2bytes because its an integer.

A[marks[4]] = BA(A) + w(k-lower_bound)


= 1000+2(4-0) = 1008

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.

3
MODULE 3 - ARRAYS

Length= upper_bound – lower_bound +1


=4–0+1=5
STORING VALUES IN ARRAYS
When we declare an array, we are just allocating space for the elments, no values are
stored in the array. There are 3 ways to store values in array.

Initializing Arrays during Declaration


Elements of the array can also be initialized at the time of declaration. When an array
is initialized, the value of every element of the arrays should be provided.
Syntax:
data_type_name array_name[size] = { value1, value2, ....... };
Example 1:
int rollno[6] = {10, 11, 12, 13, 14, 15};
Here, you are initializing an array of int which is „rollnno‟ , having 6 elements.

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];

//code to fill an array with even numbers


int i,arr1[10];
for (i=0; i<10; i++)
arr1[i]=i*2;

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.

Example: Write a program to read and display n numbers using an array.

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]);
}

printf("\nElements in array are: ");


for(i=0; i<10; i++)
{
printf("%d \t ", 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

Elements in array are: 1 1 2 3 4 5 6 7 8 9

Inserting an element in an array


Inserting an element in an array means adding a new data element to an already existing
array.
• Algorithm to append a new element to an existing array

7
MODULE 3 - ARRAYS

Step 1: Set upper_bound= upper_bound +1


Step 2: Set A[upper_bound]=VAL
Step 3: EXIT
For example, consider an array marks[] holding 12 values and a new values has to be added.
Then we can do the same by
marks[13]=45;
Now, the upper_bound value was 12 which was updated to 13 and the value for marks[13] is
assigned.

• Algorithm to insert an element in the middle of an array


The algorithm INSERT will be declared as (A,N,POS,VAL) where A is the array in
which 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 and VAL is the value that has to be
inserted
Step 1: [INITIALIZATION] SET I=N
Step 2: Repeat steps 3 and 4
While I>=POS
Step 3: SET A[I+1]=A[I]
[END OF LOOP]
Step 4: SET N=N+1
Step 5: SET A[POS]=VAL
Step 6: EXIT

Example: Write a program to insert a number at a given location in an array


#include <stdio.h>
int main()
{
int array[50], pos, i, n, num;
8
MODULE 3 - ARRAYS

printf("Enter number of elements in the array\n");


scanf("%d", &n);
printf("Enter %d elements\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Please enter the location where you want to insert an new element\n");
scanf("%d", &pos);
printf("Please enter the value\n");
scanf("%d", &num);
for (i = n ; i >= pos; i--)
a[i+1] = a[i];
a[pos] = num;
n++;
printf("Resultant array is\n");
for (i = 0; i <= n; i++)
printf("%d\n", a[i]);
return 0;
}

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

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.

Algorithm to delete an element from the middle of an array.

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,

Step 1: [INITIALIZATION] SET I=N


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

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++)
{

printf("\n Arr[%d] = %d", i, arr[i]);


}
getch();
return 0;
}

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

MERGING TWO ARRAYS


Merging two arrays in a third array means first copying the contents of the first array
into the third array and then copying the contents of the second array into the third array. Hence,
the merged array contains contents of the first array followed by the contents of the second
array.

Merging of two unsorted array

Write a program to merge two unsorted arrays


# include < stdio.h >
int main( )

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

Merging of two sorted arrays

12
MODULE 3 - ARRAYS

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 display the appropriate message saying search is unsuccessful

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

Step 2: Repeat Step 3 and 4 WHILE low <= high


Step 3: set mid = (low + high)/2
Step 4: IF A[mid]=val, then
pos=mid
print pos
Go to Step 6
ELSE IF A[mid]>val, then
SET high=MID – 1
ELSE
SET low=MID + 1
[END OF IF]

[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

PASSING ARRAYS TO FUNCTIONS


We can pass arrays to a function like any other variables.
Passing individual Elements
The individual elements of an array can be passed to a function by passing either data
values or their addresses.
Passing Data Values

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.

Passing the Entire Array


When we need to pass an entire array to a function, simply pass the name of the array.
In cases where we do not want the called function to make any changes to the array, the array
must be received as a constant array by the called function. This prevents any type of
unintentional modifications of the array elements.
main()
{
17
MODULE 3 - ARRAYS

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]);
}

Write a program to read and print an array of n number using function


#include <stdio.h>
void read_array(int arr[], int);
void display_array(int arr[], int);
void main()
{
int a[10],n;
printf("Enter the size of the array :\n");
scanf("%d", &n);
read_array(a,n);
display_array(a,n);
getch();
}

void read_array (int a[10], int n);


{ int i;
printf("Enter the elements in the array :\n");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
}
void display_array(int a[10], int n);
{ int i;
printf("The elements in the array are:\n");
for(i=0; i<n; i++)
printf("%d \t", a[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.

Declaring Two-dimensional array


The declaration statement tells the compiler the name of the array, the data type of
each element in the array and the size of each dimension. A two-dimensional array can be
declared as

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

Adress of the elements of 2D array can be calculated using the formula:


Address(A[I][J]= B_A + w { M(J-1) + (I-1)} if the array elements are stored in column
major order.
Address(A[I][J]= B_A + w { N(I-1) + (J-1)} if the array elements are stored in row major
order.
Where w is the word size, M is the number of rows, N is the number of columns, I and J are
the subscripts of the array element and B_A is the base address.
Example: Consider a 20 X 5 2D array Marks which has base address 1000 and the word size
is 2. Now compute the address of the element Marks[18][4] assuming that the elements are
stored in row major order.
Address(A[I][J]= B_A + w { N(I-1) + (J-1)}
= 1000 + 2{(5(18-1)+(4-1)}
=1176

INITIALIZING TWO-DIMENSIONAL ARRAYS


A two-dimensional array can be initialized as follows:

Syntax: data_type array_name[size]={list of values};

2
Arrays

Examples: int marks[3][4]={ 1,2,3, 4, 5, 6, 7,8,9,10,11,12};


The initialization is done row by row.
The above statement can also be written as:
int marks[3][4]= {{1,2,3,4} {5,6,7,8} {9,10,11,12}};

• While initializing the size of the first dimension can be omitted. Therefore, the below
statement is valid.

int marks[][4]= {{1,2,3,4} {5,6,7,8} {9,10,11,12}};

• 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]);
}

ACCESSING THE ELEMENTS OF TWO-DIMENSIONAL ARRAYS


The elements of a 2D array are stored in contiguous memory locations. Two for loops
are used to scan the elements. The first for loop will scan each row in the 2D array and the
second for loop will scan individual columns for every row in the array.

Write a program to print the elements of a 2D array


#include<stdio.h>
int main(){
int rows, columns;
int a[2][2] = {{10, 20}, {30, 70}};
printf("\nPrinting the 2D Array\n");

3
Arrays

for(int rows = 0; rows < 2; rows++)


{
for(int columns = 0; columns < 2; columns++)
{
printf("%d ", a[rows][columns]);
}
printf("\n");
}
return 0;
}
Output:
Printing the 2D array
10 20
30 40

OPERATIONS ON TWO-DIMENSIONAL ARRAY


Two dimensional arrays can be used to implement mathematical concept of matrices.
Matrix is a grid of numbers arranged in rows and columns.
Transpose: Transpose of a m X n matrix A is given as n X m matrix B where
B i, j = A j, i
Sum: Two matrices that are compatible 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.

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.

C i, j = ∑A i, k B k, j for k=1 to k<n

Write a program to transpose a matrix in c


#include <stdio.h>

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]);
}

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


for ( j = 0; j < c; j++)
{
transpose[j][i] = a[i][j];
}
printf("\nTranspose of the matrix:\n");
for ( i = 0; i < c; i++)
{
for ( j = 0; j < r; j++)
{
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}

Output:
Enter rows and columns:
2
3
Enter matrix elements:
1 4 0 -5 2 7

Transpose of the matrix:


1 -5
4 2
0 7

5
Arrays

write a program to add two matrix in c


#include <stdio.h>
int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows ");
scanf("%d", &r);
printf("Enter the number of columns ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd matrix:\n");


for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
scanf("%d", &b[i][j]);
}
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
sum[i][j] = a[i][j] + b[i][j];
}
printf("\nSum of two matrices: \n");
for (i = 0; i < r; i++)
{
for (j = 0; j < c; i++)
{
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 2

6
Arrays

Enter the number of columns: 3


Enter elements of 1st matrix:
2 3 4 5 2 3
Enter elements of 2nd matrix:
-4 5 3 5 6 3

Sum of two matrices:


-2 8 7
10 8 6

PASSING TWO-DIMENSIONAL ARRAYS TO FUNCTIONS


There are 3 ways of passing two-dimensional arrays to functions.

Passing individual elements: Individual array can be passed to the functions.


main()
{
int arr[2][3] = {{1,2,3},{4,5,6}};
func(arr[1][2]);
}
void func(int x)
{
printf(“%d”,x);
}

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.

An n-dimensional array is specified using n indices. An n-dimensional m1 X m2 X m3


X…..mn array is a collection m1* m2 * m3 *-……. mn elements. A multidimensional array can

8
Arrays

contain as many indices as needed and the requirement of the memory increases with number
of indices.

Write a program to read and display a 2 X 2X 2 array.


include <stdio.h>
int main()
{
int a[2][2][2],i,j,k;
printf("Enter elements of the matrix: \n");
for (i = 0; i < 2;i ++)
{
for (j = 0; j < 2; j++)
{
for ( k = 0; k < 2;k ++)
{
scanf("%d", &a[i][j][k]);
}
}
}

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.

Tridiagonal matrix: Here, the elements are present on

• The main diagonal, it contains non-zero elements for i=j


• Below the main diagonal, it contains non-zero elements for i=j+1
• Above the man diagonal, it contains non-zero elements for i=j-1.

Array Representation of Sparse Matrices


Consider the sparse matrix given below

10
Arrays

0 2 0
0 0 4
0 0 0

This sparse matrix can be represented as

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.

CASE STUDY: SORTING


Bubble Sort
Bubble sort will start by comparing the first element of the array with the second
element, if the first element is greater than the second element, it will swap both the elements,
and then move on to compare the second and the third element, and so on.

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

You might also like