Chapter 7.1

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

CHAPTER-7 ARRAYS

Array is a derived data type in 'C' that store same/similar type of elements. That is it is a fixed
size sequenced collection of elements of same data type. (Here sequenced collection means
contiguous memory). Arrays can be of any type supported by C , including constructed data type
(structure, union, enum). The use of arrays allows for the development of smallest and more
readable programs. Simply we can define array as a finite ordered set of homogenous elements.

Why it is necessary?
If we have to store information of 100 students.
100 students.
Without array : we use
int sr1; int sr2; int sr3; .........................; int sr100; (Inefficient Task)
With array : We use
int sr[100]; can store 100 students information. (Efficient Task)
sr[0],sr[1],...................................,sr[99] , here 0-99 are index.
Types of Arrays

There are two types of arrays. These are one-dimensional and multi-dimensional arrays. In this
text, we will study only one-dimensional and two-dimensional arrays in details.

One-dimensional arrays
It is a list of items with one variable name using only one subscript.
int ar[5]; where 5 is array size i.e. no of elements.
There is a variable with name 'ar' that can store 5 integer values.
Declaration : General form
data-type array-name [size];
example : float f1[100]; (0-99) index 0 to n-1
int i1[10]; (0-9) index 0 to n-1
char name[10]; (0-9) index 0 to n-1, Only 10 characters can be stored.
We have
WELL DONE

Global declaration Local declaration


char string[50]; void main()
void main() {
{ char string[50];
............... .......................
} }

Compiled By : Deepak Kr. Singh, Pradip Khanal


Initialization : There can be two different method for initializing one dimensional array i.e.,
compile-time and run-time initialization.

1. Compile-time initialization

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

Example:
Global initialization
int ar[5]={2,5,4,3,6};
void main()
{
.....................
}
Local initialization
void main()
{
float marks[5]={ 32.6 , 66.5 , 78.5 , 55.9 , 76.4 };
............................................
}

2. Run-time initialization : Usually applied for initializing large arrays.


example: int ar[50];
int i;
for(i=0;i<50;i++)
{
ar[i]=i+1;
}
We get, ar[0]=0+1=1
ar[1]=1+1=2 and so on.

Initialization of array in C suffers two drawbacks:


 There is no convenient way to initialize only selected elements.
 There is no shortcut method for initializing a large numbers of array elements.

How to access elements of 1D array?


To access individual elements of an array, a subscript or index must be used. The subscript
identifies the sub-element or component of the array that is to be accessed. Subscripts must start
at 0 and proceed in increments of 1.
float val[12]={11,22,33,44,55,66,77,88,11,66,77,44};
elements value:

Compiled By : Deepak Kr. Singh, Pradip Khanal


val[0] val[1] val[2] val[3] val[4] val[5] val[6] val[7] val[8] val[9] val[10] val[11]

Fig: Memory allocation for one dimensional array of type float


Example: Program to display the address of each block of allocated memory space for a float
type of array. (address may vary from one computer to another)
#include<stdio.h>
#include<conio.h>
int main()
{
float marks[5];
int i;
for(i=0;i<5;i++)
{
printf("Address of %d block is %d\n",i,&marks[i]);
}
getch();
return 0;
}
Output
Address of 0 block is 1000 (Note: Address value increases by 4 byte because of float type)
Address of 1 block is 1004
Address of 2 block is 1008
Address of 3 block is 1012
Address of 4 block is 1014

Example :Program to find average of number entered by user.


#include<stdio.h>
#include<conio.h>
int main()
{
int ar[10],i,sum=0;
float average;
for(i=0;i<10;i++)
{
printf("Enter number:");
scanf("%d",&ar[i]);
sum=sum+ar[i];
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


average=sum/10;
printf("Average=%f",average);
getch();
return 0;
}

Example: Program to find the largest element of an array.


#include<stdio.h>
#include<conio.h>
int main()
{
float marks[5],max;
int i;
for(i=0;i<5;i++)
{
printf("Enter marks[%d]",i);
scanf("%f",&marks[i]);
}
max=marks[0];
for(i=0;i<5;i++)
{
if(marks[i]>max)
{
max=marks[i];
}
}
printf("The largest element is %f",max);
getch();
return 0;
}
Sorting of an array elements
It is the process of placing/ordering the element either in ascending or descending order. There
are a numbers of algorithms to sort list of data.
 Bubble sort
 Insertion sort
 Selection sort
Bubble sort : Bubble Sort is a simple algorithm which is used to sort a given set of n elements
provided in form of an array with n number of elements. Bubble Sort compares all the element
one by one and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by comparing
the first element of the array with the second element, if the first element is greater than the

Compiled By : Deepak Kr. Singh, Pradip Khanal


second element, it will swap both the elements, and then move on to compare the second and the
third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element in the given
array, bubbles up towards the last place or the highest index, just like a water bubble rises up to
the water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it with the
adjacent element and swapping them if required.
Implementing Bubble Sort Algorithm:
Following are the steps involved in bubble sort(for sorting a given array in ascending order):

1. Starting with the first element(index = 0), compare the current element with the next
element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat
Step 1.

Let's consider an array with values {5, 1, 6, 2, 4, 3}


Below, we have a pictorial representation of how bubble sort will sort the given array.

So as we can see in the representation above, after the first iteration, 6 is placed at the last index,
which is the correct position for it.
Similarly after the second iteration, 5 will be at the second last index, and so on.
Program
#include<stdio.h>
#include<conio.h>

Compiled By : Deepak Kr. Singh, Pradip Khanal


int main()
{
int i,j,temp,n,ar[50];
printf("Enter number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
{
printf("%d",ar[i]);
}
getch();
return 0;
}

Insertion Sort : Consider you have 10 cards out of a deck of cards in your hand. And they are
sorted, or arranged in the ascending order of their numbers.
If I give you another card, and ask you to insert the card in just the right position, so that the
cards in your hand are still sorted. What will you do?
Well, you will have to go through each card from the starting or the back and find the right
position for the new card, comparing it's value with each card. Once you find the right position,
you will insert the card there.
Similarly, if more new cards are provided to you, you can easily repeat the same process and
insert the new cards and keep the cards sorted too.
This is exactly how insertion sort works. It starts from the index 1(not 0), and each index
starting from index 1 is like a new card, that you have to place at the right position in the sorted
subarray on the left.
Following are some of the important characteristics of Insertion Sort:
1. It is efficient for smaller data sets, but very inefficient for larger lists.
2. Insertion Sort is adaptive, that means it reduces its total number of steps if a partially
sorted array is provided as input, making it efficient.
3. It is better than Selection Sort and Bubble Sort algorithms.
4. Its space complexity is less. Like bubble Sort, insertion sort also requires a single
additional memory space.
5. It is a stable sorting technique, as it does not change the relative order of elements which
are equal.

Compiled By : Deepak Kr. Singh, Pradip Khanal


How Insertion Sort Works?
Following are the steps involved in insertion sort:
1. We start by making the second element of the given array, i.e. element at index 1,
the key. The key element here is the new card that we need to add to our existing sorted
set of cards(remember the example with cards above).
2. We compare the key element with the element(s) before it, in this case, element at
index 0:
 If the key element is less than the first element, we insert the key element before the
first element.
 If the key element is greater than the first element, then we insert it after the first
element.

3. Then, we make the third element of the array as key and will compare it with elements to
it's left and insert it at the right position.

4. And we go on repeating this, until the array is sorted.

Let's consider an array with values {5, 1, 6, 2, 4, 3}


Below, we have a pictorial representation of how bubble sort will sort the given array.

Compiled By : Deepak Kr. Singh, Pradip Khanal


As you can see in the diagram above, after picking a key, we start iterating over the elements to
the left of the key. We continue to move towards left if the elements are greater than
the key element and stop when we find the element which is less than the key element. And,
insert the key element after the element which is less than the key element.
Program
#include <stdio.h>
int main()
{
int n, ar[1000],i, j, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &ar[i]);
}
for (i = 1 ; i <= n - 1; i++) {
j = i;
while ( j > 0 && ar[j-1] > ar[j]) {
t = ar[j];
ar[j] = ar[j-1];
ar[j-1] = t;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++) {
printf("%d\n", ar[i]);
}
getch();
return 0;}

Searching of elements in array


Finding the required element from an array is called searching.
Linear search process
In this process, we keep on comparing each element with the element to search until it is found
or the list ends.
Program
#include <stdio.h>
#include<conio.h>
int main()
{
int ar[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);

Compiled By : Deepak Kr. Singh, Pradip Khanal


for (c = 0; c < n; c++)
{
scanf("%d", &ar[c]);
}
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (ar[c] == search) /* If required element is found */
printf("%d is present at location %d.\n", search, c+1);
break;
}
if (c == n){
printf("%d isn't present in the array.\n", search);}
getch();
return 0;}
Example: Program to print negative element in array
int main()
{
int ar[1000];
int i, n;
printf("Enter size of array:");
scanf("%d",&n);
printf("Enter elements in array\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
}
printf("\nAll negative elements in this array are\n");
for(i=0;i<n;i++)
{
if(ar[i]<0)
{
printf("%d\t",ar[i]);
}
}
getch();
return 0;
}
Example : Program to count and find the sum of all the numbers in the array which are exactly
divisible by 7 but not by 5.
int main()
{
int ar[5],count=0,sum=0,i;

Compiled By : Deepak Kr. Singh, Pradip Khanal


for(i=0;i<5;i++)
{
printf("Enter ar[%d]:",i);
scanf("%d",&ar[i]);
}
for(i=0;i<5;i++)
{
if(ar[i]%7==0 && ar[i]%5!=0)
{
sum=sum+ar[i];
count++;
printf("%d is required array element",ar[i]);
}
}
printf("\n Sum = %d",sum);
printf("Total number of required number is %d",count);
getch();
return 0;
}
How to insert an element in one dimensional array?
Logic to insert element in array
Step by step descriptive logic to insert element in array.
 Input size and elements in array. Store it in some variable say size and ar.
 Input new element and position to insert in array. Store it in some variable
say num and pos.

 To insert new element in array, shift elements from the given insert position to one
position right. Hence, run a loop in descending order from size to pos to insert. The loop
structure should look like for(i=size; i>=pos; i--).
 Inside the loop copy previous element to current element by ar[i] = ar[i - 1];.

 Finally, after performing shift operation. Copy the new element at its specified position
i.e. ar[pos-1]=num;.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Program
#include <stdio.h>
#include<conio.h>
#define MAX_SIZE 100
int main()
{
{
int ar[MAX_SIZE];
int i, size, num, pos;
/* Input size of array */
pritf("Enter size of the array:");
scanf("%d", &size);
/*Input elements in array */
printf("Enter elements in array\n");
for(i=0;i<size;i++)
{
scanf("%d", &ar[i]);
}

/* Input new element and position to insert */


printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &pos);
/* If position of element is not valid */
if(pos > size+1 || pos <= 0)
{
printf("Invalid position! Please enter position between 1 to %d", size);
}
else
{
/* Make room for new array elements by shifting to right */
for(i=size; i>=pos; i--)
{
ar[i] = ar[i-1];
}
/* Insert new element at given position and increment size */
ar[pos-1] = num;
size++;

/* Print array after insert operation */


printf("Array elements after insertion : ");
for(i=0; i<size; i++)
{
printf("%d\t", ar[i]);
}
}
getch();
return 0;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


How to delete an element of array?
Logic to remove element from array
Array is a linear data structure. It provides index based fast mechanism to access its elements.
But insertion or deletion from an array is a costly operation. Literally speaking there isn't
anything such as deleting element from array. In general you copy elements of the array towards
left. Suppose I say you need to delete the 2nd element from given array. You will do it as.

Step by step descriptive logic to remove element from array.


1. Move to the specified location which you want to remove in given array.
2. Copy the next element to the current element of array. Which is you need to
perform array[i] = array[i + 1].
3. Repeat above steps till last element of array.
4. Finally decrement the size of array by one.
Program
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int ar[MAX_SIZE];
int i, size, pos;
printf("Enter size of the array : ");
scanf("%d", &size);
printf("Enter elements of array : ");
for(i=0; i<size; i++)
{
scanf("%d", &ar[i]);
}
printf("Enter the element position to delete : ");
scanf("%d", &pos);
if(pos < 0 || pos > size)
{
pritf("Invalid position! Please enter position between 1 to %d", size);
}
else
{
for(i=pos-1; i<size-1; i++)
{
ar[i]= ar[i+1];
}
size--;}

Compiled By : Deepak Kr. Singh, Pradip Khanal


printf("\nElements of array after delete are : ");
for(i=0; i<size; i++)
{
printf("%d\t", ar[i]);
}
getch();
return 0;
}
Program to print unique element

Step by step descriptive logic to find unique elements in array.

1. Input size and elements in array. Store it in some variable say size and arr.
2. Find frequency of each element and store it in an array say freq.
3. Print array elements with frequency 1 which is our required unique elements.
Program
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int ar[MAX_SIZE], freq[MAX_SIZE];
int size, i, j, count;
printf("Enter size of array : ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d",&ar[i]);
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
if(ar[i] == ar[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i]! = 0)
{
freq[i] = count;
}
}
printf("\nUnique elements in the array are : ");
for(i=0; i<size; i++)
{
if(freq[i] == 1)
{
printf("%d", ar[i]);
}
}getch();return 0}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Program to reverse an array
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i, ar[100];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements\n");
for(i=0; i<n; i++)
{
scanf("%d", &ar[i]);
}
printf("Array in reverse order\n");
for(i=n-1; i>=0; i--)
{
printf("%d\t", ar[i]);
}
getch();
return 0;
}
Program to find frequency of element of an array
#include <stdio.h>

void main()
{
int arr1[100], fr1[100];
int n, i, j, ctr;
printf("\n\nCount frequency of each element of an array:\n");
printf("------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
fr1[i] = -1;
}
for(i=0; i<n; i++)
{
ctr = 1;
for(j=i+1; j<n; j++)
{
if(arr1[i]==arr1[j])
{
ctr++;

Compiled By : Deepak Kr. Singh, Pradip Khanal


fr1[j] = 0;
}
}
if(fr1[i]!=0)
{
fr1[i] = ctr;
}
}
printf("\nThe frequency of all elements of array : \n");
for(i=0; i<n; i++)
{
if(fr1[i]!=0)
{
printf("%d occurs %d times\n", arr1[i], fr1[i]);
}
}
getch();
return 0;
}
Output
Count frequency of each element of an array:
------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 25
element - 1 : 12
element - 2 : 43

The frequency of all elements of array :


25 occurs 1 times
12 occurs 1 times
43 occurs 1 times

Passing an 1D array to function


Actually, an array is a contiguous area of memory location for sorting a group of related data
items of same data type together.
The area consists of n number of blocks of equal size, where n is the number of data items to be
stored there. Before running program, required amount of contiguous memory must be reserved.
Each block of the reserved memory stores an element of the array.
The name of an array stores the beginning address of reserved memory, by which we can reach
each member of the array by incrementing the starting address.
To pass an array to a function as an argument, we need to pass the name of the array. It means
starting address of the memory where members of the array are stored. If we know the starting
address of contagious memory inside function and number of members of the array, we can
easily access each member by using loop. Passing arrays to function is passing by reference. We
can pass arrays by value by copying all members inside function but it consumes time and
memory spaces because arrays are large structure.
Example
#include<stdio.h>
#include<conio.h>
void sort_array(int [], int);
void display_array(int [], int);

Compiled By : Deepak Kr. Singh, Pradip Khanal


int main()
{
int marks[50], temp, i, j, n;
printf("Enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter elements\n");
scanf("%d",&marks[i]);
}
sort_array(marks,n);
display_array(marks,n);
getch();
return 0;
}
void sort_array(int marks[], int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(marks[i]>marks[j])
{
temp=marks[i];
marks[i]=marks[j];
marks[j]=temp;
}
}
}
}
void display_array(int marks[], int n)
{
int i;
printf("Sorted array is : ");
for(i=0;i<n;i++)
{
printf("%d",marks[i]);
}
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Two Dimensional Array(2D Array)
It can be seen as array of arrays. It is organized in two direction : horizontal and vertical. The
data items arranged in horizontal direction are referred as rows and the data items arranged in
vertical direction are referred as columns. The matrices those we studied in mathematics are
examples of two-dimensional arrays. A pair of indices representing the position of the element in
the array can be used to access each element of the array. In real case, the marks of 4 students in
five subjects can be arranged in a two directional array as below:
Name/Subjects A B C D E
Ram 70 80 40 80 90
Shyam 88 44 65 76 90
Gita 77 46 77 78 45
Sita 45 56 98 66 65

Declaration
Two-dimensional array can be declared as:

data_type array_name [row_size] [column_size];


example: int ar[3][4];

Global declaration
char string[50][30];
void main()
{
.............................
}

Local declaration
void main()
{
int ar[3][3];
..................
}

Initialization
example:
int ar[2][3]={{1, 2, 3},{5, 7, 8}};

Accessing elements of 2d array


A two dimensional array can be defined as an array of one-dimensional arrays. Accessing
elements in two-dimensional arrays is similar to one-dimensional arrays. Where, only one
subscript is used to indicate the column position of the element in the array but in case of two-

Compiled By : Deepak Kr. Singh, Pradip Khanal


dimension, it is required to use a pair of subscript to indicate row and column-position of an
element in the array. For example, int marks[3][3]; is an array of size 3x3. It means there are
three rows and three columns in the array marks. In one dimensional array, one loop is used to
access each member, whereas in two-dimensional array it is required to use two loops in nested
loop structure. The outer loop is for reaching to each row and inner loop for reaching to each
column of the row. As the index in one-dimensional arrays, the indexes for rows and column for
two-dimensional arrays are also started from zero.

Columns
Rows 0 1 2

Program: To store elements in 2d array (matrix) and display.


#include<stdio.h>
#include<conio.h>
int main()
{
int ar[3][3],i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Enter values\n");
scanf("%d",&ar[i][j]);
}
}
printf("Printing the elements of array\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",ar[i][j]);
}
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


getch();
return 0;
}
Memory allocation for 2d array
Although elements of two-dimensional arrays are arranged in rows and columns, memory
allocation is done sequentially and in single dimension as done in one dimensional array as
shown below, where, memory allocation is illustrated for a two-dimensional integer array of size
2x3.

Various operations on matrices


1. Matrix addition and substraction
#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, A[10][10], B[10][10], r1, c1, r2, c2, C[10][10];
printf("Enter the maximum size of row and column of array A:");
scanf("%d%d", &r1, &c1);
printf("Enter the maximum size and column of array B:");
scanf("%d%d", &r2, &c2);
if(r1==r2 && c1==c2)
{
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("Enter A[%d][%d]:", i, j);
scanf("%d", &A[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j==0;j<c2;j++)
{
printf("Enter B[%d][%d]:", i, j);

Compiled By : Deepak Kr. Singh, Pradip Khanal


scanf("%d", &B[i][j]);
}
}
printf("Addition of two matrix:")
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
C[i][j] = A[i][j] + B[i][j];
printf("\t%d", C[i][j]);
}
printf("\n");
}
printf("Subtraction of two matrix:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
C[i][j] = A[i][j] - B[i][j];
printf("\t%d", C[i][j]);
}
printf("\n");
}

}
else
{
printf("Array size mismatched.");
}
getch();
return 0;
}

Passing 2d array to function


To pass a two-dimensional array to a function as an argument, it is required to pass the starting
address of the memory area reserved for the arrays as done in one dimensional array.
The starting address is stored in array name. So, we have to pass the name of the array as
argument of the function.
Passing 2d array to function by passing array name is also passing by reference. Inside the called
function, actual working area for the passed array is the actual memory area reserved for it. So

Compiled By : Deepak Kr. Singh, Pradip Khanal


any operation done on the array inside called function is actually done in their actual location.
Therefore, arrays are not required to return to the calling function. The size of all dimensions
except the first (optional, dummy) must be included in the function prototype and in function
declarator.
The size of those dimensions of the array must be exactly the same as in the array declaration.

Array multiplication
#include<stdio.h>
#include<conio.h>
void multi2darray(int [][10], int [][10], int [][10], int, int, int);
int main()
{
int i, j, A[10][10], B[10][10], r1, c1, r2, c2, C[10][10], k;
printf("Enter the maximum size of row and column of array A:");
scanf("%d%d", &r1, &c1);
if(c1==r2)
{
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("Enter A[%d][%d]:", i, j);
scanf("%d", &A[i][j]);
}
}
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("Enter B[%d][%d]", i, j);
scanf("%d",&B[i][j]);
}
}
multi2darray(A, B, C, r1, c1, c2);
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d", C[i][j]);
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


printf("\n");
}
}
else
{
printf("Array mismatched..");
}
}
void multi2darray(int A[][10], int B[][10], int C[][10], int r1, int c1, int c2)
{
int i, j, k;
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
C[i][j]=0;
// In pointer, we use "*(*(C+i)+j)==0"//
for(k=0;k<c1;k++)
{
C[i][j] = C[i][j] + A[i][k] * B[k][j];
// In pointer, we use "(*(*(C+i)+j))=(*(*(C+i)+j))+(*(*(A+i)+k)) * (*(*(B+k)+k));" //
}
}
}
}

Multidimensional arrays
Two or more dimensional arrays are in this category. C allows arrays of three or more
dimensions. The exact limit depends on the compiler. We can check it by compiling a simple
program having a multidimensional array by our compiler and decide up to which dimension
does our compiler support. The general form of a multidimensional array declaration is

data_type array_name [s1][s2][s3][s4].......[sn];

Where si(i=1,2,3...,n) is the size of ith dimension.


Example: int num[2][3][5];
where num is three dimensional array declared to contain 30 integer type elements. Other
prrocedures are similar to the one and two-dimensional arrays.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Q. Explain how 2d array is passed to a function. WAP to display largest and smallest elements of
a 2d array. [2073 Chaitra]
Q. How two dimensional arrays are created in C programming? Write a program to read square
matrix of size NxN and find sum of both diagonals. [2074 Ashwin]
Q. What are overflow and underflow errors in context of array? WAP to add corresponding
elements of two arrays. The results should form a new array. [2073 Shrawan]
These are both examples of indexing an array outside the bounds of an array. Every array
has several properties. Among those are the data type of the array element, the length of the
array, and the valid index values for the array. The index values of an array are bounded set of
contiguous values. For example, a 10 element array of int values in C is declared as:

example: int a[10];

The valid range of values for the example above is 0 through 9. The first element of the array is
accessed using index value 0 and the last element of the array is accessed using index value 9.
An overflow error occurs when one attempts to access the example array using an index value
greater than 9. An underflow error occurs when one attempts to access the example array using
an index value less than 0. Either of these errors results in accessing memory not allocated to the
array. The result of accessing memory outside the memory allocated to the array is undefined in
many languages. Neither C nor C++ provide the ability to check for either error when an array is
passed to a function through a function parameter. Some languages such as Ada, Java, and Pascal
check the index values and prohibit use of index values which would reference memory outside
the memory allocated to the array. If the invalid array access can be detected at compile time a
compilation error is generated. If the invalid array access happens during run-time a run-time
exception is raised in Ada or Java.

Q. What is string? WAP to read 3x3 square matrix, find minimum integer value of a matrix,
replace the diagonal elements by the minimum element and display it records of 10 colleges.
[2072 chaitra]
Q. Explain with an example for compiler time initialization of 2D array. Describe how compiler
manages according to the number of initializers and size of an array given by a user in case of
1D array. [2072 Kartik]
There are two ways to initialize a two Dimensional arrays during declaration.
int disp[2][4]={
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR
int disp[2][4] = {10, 11, 12, 13, 14, 15, 16, 17};

Although both the above declarations are valid, I recommend you to use the first method as it is
more readable, because you can visualize the rows and columns of 2d array in this method.
Things that you must consider while initializing a 2D array
We already know, when we initialize a normal array (or you can say one dimensional array)
during declaration, we need not to specify the size of it. However that’s not the case with 2D

Compiled By : Deepak Kr. Singh, Pradip Khanal


array, you must always specify the second dimension even if you are specifying elements during
the declaration. Let’s understand this with the help of few examples –
/* Valid declaration */
int abc[2][2] = {1, 2, 3, 4};
/* Valid declaration */
int abc[][2] = {1, 2, 3, 4};
/* Invalid declaration */
int [][] = {1, 2, 3, 4};
/* Invalid declaration */
int abc[2][] = {1, 2, 3, 4};
How to store user input data into 2D array
We can calculate how many elements a two dimensional array can have by using this formula:
The array arr[n1][n2] can have n1*n2 elements. The array that we have in the example below is
having the dimensions 5 and 4. These dimensions are known as subscripts. So this array has first
subscript value as 5 and second subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.
To store the elements entered by user we are using two for loops, one of them is a nested loop.
The outer loop runs from 0 to the (first subscript -1) and the inner for loops runs from 0 to the
(second subscript -1). This way the the order in which user enters the elements would be
abc[0][0], abc[0][1], abc[0][2]…so on.
#include<stdio.h>
int main(){
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {
printf("Enter value for abc[%d][%d]:", i, j);
scanf("%d", &abc[i][j]);
}
}
return 0;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


In above example, I have a 2D array abc of integer type. Conceptually you can visualize the
above array like this:

However the actual representation of this array in memory would be something like this:

Pointers & 2D array


As we know that the one dimensional array name works as a pointer to the base element (first
element) of the array. However in the case 2D arrays the logic is slightly different. You can
consider a 2D array as collection of several one dimensional arrays.
So abc[0] would have the address of first element of the first row (if we consider the above
diagram number 1).
similarly abc[1] would have the address of the first element of the second row. To understand it
better, lets write a C program –
#include <stdio.h>
int main()
{
int abc[5][4] ={
{0,1,2,3},
{4,5,6,7},
{8,9,10,11},
{12,13,14,15},
{16,17,18,19}
};
for (int i=0; i<=4; i++)

Compiled By : Deepak Kr. Singh, Pradip Khanal


{
/* The correct way of displaying an address would be
* printf("%p ",abc[i]); but for the demonstration
* purpose I am displaying the address in int so that
* you can relate the output with the diagram above that
* shows how many bytes an int element uses and how they
* are stored in contiguous memory locations.
*
*/
printf("%d ",abc[i]);
}
return 0;
}
Output:
1600101376 1600101392 1600101408 1600101424 1600101440
The actual address representation should be in hex for which we use %p instead of %d, as
mentioned in the comments. This is just to show that the elements are stored in contiguous
memory locations. You can relate the output with the diagram above to see that the difference
between these addresses is actually number of bytes consumed by the elements of that row. The
addresses shown in the output belongs to the first element of each row abc[0][0], abc[1][0],
abc[2][0], abc[3][0] and abc[4][0].
Q. Write an algorithm to insert a value in an array at a position given by user. [2071 chaitra]
Q. A multinational company has hired 3 sales persons for marketing/selling its 3 different
products in Kathmandu. Each sales person sells each of these products. WAP to read number of
each product sold by all sales persons, Calculate total sells of each item and the total sells of each
sales-person. Use arrays.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int pro[3][3], sum=0;
int i, j;
char per[3][10] = {"first","second","third"};
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Enter number of selling of %s person %s products",per[i],per[j]);
scanf("%d", &pro[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)

Compiled By : Deepak Kr. Singh, Pradip Khanal


{
sum = sum + pro[i][j];
}
printf("Total sum of %s person is %d\n",per[i],sum);
sum=0;
}
for(j=0;j<3;j++)
{
for(i=0;i<3;i++)
{
sum = sum + pro[i][j];
}
printf("Total sell of %s item is %d\n",per[i],sum);
sum=0;
}
getch();
return 0;
}

Q. Write down the significance of array in C. WAP to multiply two 3x3 matrix. Two matrix are
input from main() function and pass to a user defined function with argument with array. The
result is also displayed from main() function.
Q. Briefly explain array of pointers. How are array and pointer related? Give example. [2070]
Q. How are one dimensional and two dimensional arrays created in C? Explain with examples.
Q. WAP to read two matrices from user, add them and display the result in matrix form. [2070]
Q. How can we pass two dimensional arrays from one function to another? Explain with
example.
Q. WAP to find the second largest number in an array of n numbers. Read the value of n and the
elements of the array from the user. [2069]
Q. Can we pass whole array element from the function? WAP to pass an array to function and
sort them.

Compiled By : Deepak Kr. Singh, Pradip Khanal

You might also like