Array Notes
Array Notes
Definition:
Array is an ordered collection of elements that share the same name. We use declarations to tell the compiler
when we want an array. The compiler needs to know the same things about an array that it needs to know about
an ordinary variable (known as a scalar variable in the trade): the type and the storage class. In addition, it
needs to know how many elements the array has. Arrays can have the same types and storage classes as
ordinary variables, and the same default rules apply.
Declaration of arrays:
The number 30 tells how many elements of type int will be in the array. This number is often called the
dimension of the array. The brackets tells compiler that we are dealing with arrays.
The dimension used to declare an array must always be a positive integer constant or an expression that can be
evaluated to be a constant, when the program is compiled.
The method of subscribing arrays is C is different from that used in many other programming languages. The
first element in the array is numbered zero so the last element is 1 less than the size of the array. However big
the array, its elements are always stored in contiguous memory locations.
The first element in the array is numbered 0. The reason for this unusual numbering scheme is that C was
designed to model the operation of computer at lower level than that dealt with by most programming
languages. The calculation of the address corresponding to subscript is simpler, when first array element is
numbered zero.
int num[5];
Since we know that array elements are stored in one continuous memory location. This is how the memory map
looks like:
num[0]
num[1]
num[2]
num[3]
num[4]
main() {
floatavg,sum=0;
int marks[30],i;
for(i=1;i<=29;i++){
printf(“Enter the marks”);
scanf(“%d”, &marks[I]);
}
for(i=0;i<=29;i++)
sum+=marks[i];
avg=sum/30;
printf(“Average is %f”,avg);
}
Initializing of an array:
A global variable is one that is declared outside any function (usually before main). A special feature of global
array is that they can be initialized when they are declared. This is done by following an array name with
dimension and equal sign, followed by pair of braces. These braces contain series of constant values, separated
by commas.
101 1 num[0]
103 2 num[1]
105
3 num[2]
107 4 num[3]
109 num[4]
5
It is not always necessary to specify dimension of the array, if it is being declared as follows:
int name[]={1,2,3,4,5};
Since the square brackets following the array name are empty, compiler determines how many elements to
allocate for array by counting number of values within curly braces.This approach can avoid errors.
NOTE: Defining the size of each array as a symbolic constant makes programs more scalable.
When the compiler sees a constant string it terminates it with an additional null character – called as NULL
character.
Static : we have seen how global arrays can be initialized. The global variables are classified in C as static
variables, means they come into existence when program is executed, to continue to exist until entire program
terminates.
#include<stdio.h>
intmain(){
intarr[5], i, s =0;
for(i =0; i <5; i++){
printf("Enter a[%d]: ", i);
scanf("%d",&arr[i]);
}
for(i =0; i <5; i++){
s +=arr[i];
}
printf("\nSum of elements = %d ", s);
// signal to operating system program ran fine
return0;
}
Expected Output:
Enter a[0]: 22
Enter a[1]: 33
Enter a[2]: 56
Enter a[3]: 73
Enter a[4]: 23
The first for loop asks the user to enter five elements into the array. The second for loop reads all the elements
of an array one by one and in the process, accumulate the sum of all the elements of an array in the variable s.
Note that the variable s is initialized to 0, otherwise, we will get the wrong answer because of the garbage value
of s.
#include<stdio.h>
int main(){
int i, n;
floatarr[100];
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&n);
printf("\n");
OUTPUT:
#include <stdio.h>
void main () {
int number[30];
int i, j, a, n, counter, average;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i){
for (j = i + 1; j < n; ++j) {
if (number[i] < number[j]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in descending order are given below \n");
for (i = 0; i < n; ++i) {
printf("%d\n", number[i]);
}
printf("The 2nd largest number is = %d\n", number[1]);
printf("The 2nd smallest number is = %d\n", number[n - 2]);
average = (number[1] + number[n - 2]) / 2;
counter = 0;
for (i = 0; i < n; ++i){
if (average == number[i]){
++counter;
}
}
if (counter == 0 )
printf("The average of %d and %d is = %d is not in the array \n", number[1], number[n - 2], average);
else
printf("The average of %d and %d in array is %d in numbers \n",number[1], number[n - 2], counter);
}
OUTPUT:
Enter the value of N
4
Enter the numbers
450
340
120
670
The numbers arranged in descending order are given below
670
450
340
120
The 2nd largest number is = 450
The 2nd smallest number is = 340
The average of 450 and 340 is = 395 is not in the array
#include <stdio.h>
void main(){
intvectorx[10];
int i, n,pos, element, found =0;
printf("Enter how many elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i =0; i < n; i++){
scanf("%d",&vectorx[i]);
}
printf("Input array elements are\n");
for(i =0; i < n; i++){
printf("%d\n",vectorx[i]);
}
printf("Enter the element to be deleted\n");
scanf("%d",&element);
for(i =0; i < n; i++){
if(vectorx[i]== element){
found=1;
pos= i;
break;
}
}
if(found ==1){
for(i =pos; i < n -1; i++){
vectorx[i]=vectorx[i +1];
}
printf("The resultant vector is \n");
for(i =0; i < n -1; i++){
printf("%d\n",vectorx[i]);
}
}
else
printf("Element %d is not found in the vector\n", element);
}
OUTPUT:
Enter how many elements
4
Enter the elements
345
234
678
987
Input array elements are
345
234
678
987
Enter the element to be deleted
234
The resultant vector is
345
678
987
#include <stdio.h>
int main(){
intarr[]={10,20,30,40,50};
int n;
n=sizeof(arr)/sizeof(int);
printf("Number of elemenets are: %d\n",n);
return 0;
}
OUTPUT
Another method
We can divide the occupied size of all array elements by size of any one array element. Consider the following
statement:
n=sizeof(arr)/sizeof(arr[0]);
#include <stdio.h>
#define MAX 100
int main(){
intarr[MAX],revArr[MAX];
inti,j
int n;
printf("Enter total number of elements: ");
scanf("%d",&n);
printf("Enter array elements:\n");
for(i=0;i<n;i++){
printf("Enter element %d: ",i+1);
scanf("%d",&arr[i]);
}
for(i=(n-1),j=0; i>=0; i--,j++){
revArr[j]=arr[i];
}
printf("\nArray elements after reverse:\n");
for(i=0;i<n;i++){
printf("%d\n",revArr[i]);
}
return 0;
}
OUTPUT:
Enter total number of elements: 5
Enter array elements:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
We have a convenient way to initialize the array at the beginning of a program. There is a way, but only static
and extern array can be initialized but automatic and register array cannot be initialized
Before trying to initialize an array, let’s see what in it if we don’t put anything there.
main(){
int fun[2]; /*automatic array */
static int win[2]; /*static array */
printf(“%d %d\n”, fun[1], win[1]);
}
This reflects the following rules. If you do noting, external and static arrays are initialized to zero. Automatic
and register arrays get whatever garbage happens to be left over in the part of memory.
When the array elements are initialized by at least one initializer, then the remaining elements are initialized to
zero.
During compile time static array gets initialized and at run time automatic array gets initialized.
Ex : main() {
int days[12] = {31,28,31,30,31,30,31,31,30,31};
int i;
for(i=0;i<12;i++)
printf(“days[%d] = %d“ , i, days[i] “);
}
days[0] = 31
days[1] = 28
days[2] = 31
days[3] = 30
days[4] = 31
days[5] = 30
days[6] = 31
days[7] = 31
days[8] = 30
days[9] = 31
days[10] = 0
days[11] = 0
Bounds checking:
In C there is no check to see if subscript used for an array exceeds size of the array. Data entered with subscript
exceeding array size will simply be placed in memory outside array: probably on top of other data. This will
lead to unpredictable results, to say the least & there will be no error message to warn you that you are going
beyond array size. In some cases, the computer may just hang. The following program my turn suicidal.
main() {
intnum[40],i;
for(i=0;i<100;i++)
num[i]=i;
}
So do remember to see to it that a subscript does not reach beyond array size is entirely the programmers
botheration & not the compilers.
Interestingly though, C is the only language which lets you exceed the limit defined in an array. Other
languages would not even allow you to trespass that boundary, acting as caretakers and dictating your
movements. C, on the other hand, acknowledges your acumen, and assuming you are aware and ready to take
the risks associated, gives you that freedom.
This situation with array bounds is one of the most unsatisfactory aspects of C. If you read or write outside of
an array's bounds, you may read or write garbage or (if you are lucky) you may get a segmentation fault which
at least tells you there's a problem.
In the end, it is up to you to make sure that your program respects the bounds of its arrays. You'll get very little
help from C.
When looping through an array, the array subscript should never go below 0 and should always
be less than the total number of elements in the array (size-1). Make sure the loop terminating
condition prevents accessing elements outside this range.
The effects of referencing elements outside the array bounds are system dependent.
main() {
static int a[5]={5,10,15,20,25);
inti,j,m,n;
i=++a[1];
j=a[1]++;
printf(“\n i = %d j = %d a[1]=%d”,i,j,a[1]);
i=1;
m=a[i++];
printf(“\n i = %d m = %d”,i,m);
i=2;
n=a[++i];
printf(“\n i = %d n = %d”,i,n);
}
Output:
i = 11 j = 11 a[1]=12
i = 2 m = 12
i = 3 n = 20
main() {
int list[10]={0};
int i;
for(i=0;i<5;i++)
list[2*i+1]=i+2;
for(i=0;i<10;i++)
printf(“\n %d”,list[i]);
}
Sol : 0 2 0 3 0 4 0 5 0 6
main() {
int list[10]={2,1,2,1,1,2,3,2,1,2};
printf(“\n %d”,list[2]);
printf(“\n %d”,list[list[2]]);
printf(“\n %d”,list[list[2]+list[3]]);
printf(“\n %d”,list[list[list[2]]]);
}
Sol : 2 2 1 2
Example: find the validity of the following code:
main() {
int n[3][3]={1,2,3,4,5,6,7,8,9};
printf(“\n %d”,n);
printf(“\n %d”,n[2]);
printf(“\n %d ”,n[2][2]);
}
Advantages of arrays
1) It is better and convenient way of storing the data of same datatype with same size.
2) It allows us to store known number of elements in it.
3) It allocates memory in contiguous memory locations for its elements. It does not allocate any extra
space/ memory for its elements. Hence there is no memory overflow or shortage of memory in arrays.
4) Iterating the arrays using their index is faster compared to any other methods like linked list etc.
5) It allows to store the elements in any dimensional array - supports multidimensional array.
Disadvantages of arrays
1) It allows us to enter only fixed number of elements into it. We cannot alter the size of the array once
array is declared. Hence if we need to insert more number of records than declared then it is not
possible. We should know array size at the compile time itself.
2) Inserting and deleting the records from the array would be costly since we add / delete the elements
from the array, we need to manage memory space too.
3) It does not verify the indexes while compiling the array. In case there is any indexes pointed which is
more than the dimension specified, then we will get run time errors rather than identifying them at
compile time.
Application to sorting:
The concept of an ordered set of elements is one that has considerable impact on our daily lives. There are
different methods of sorting. The programmer must be aware of several interrelated and often conflicting
efficiency considerations to make an intelligent choice about which sorting method is most appropriate to a
particular problem.
Bubble sort: The most widely known among beginning students of programming – BUBBLE SORT. One of
the main characteristic of this sort is that it is easy to understand and code.
1) [ Initialise ]
LAST N ( entire list unsorted at this point )
6) [ Finished ]
25 57 48 37 12 92 86 33
Thus after the first pass, array elements are like this :
25 48 37 12 57 86 33 92
Notice that after first pass, largest element 92 is in its proper position. This method is called BUBBLE SORT,
because each number slowly BUBBLES up to its position.
25 37 12 48 57 33 86 92
Iteration 1 25 48 37 12 57 88 33 92
Iteration 2 25 37 12 48 57 33 86 92
Iteration 3 25 12 37 48 33 57 86 92
Iteration 4 12 25 37 33 48 57 86 92
Iteration 5 12 25 33 37 48 57 86 92
Iteration 6 12 25 33 37 48 57 86 92
Iteration 7 12 25 33 37 48 57 86 92
12 25 33 37 48 57 86 92
PROGRAM: TO sort elements of an array using BUBBLE SORT
#include<stdio.h>
int main(){
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("\nArray after sorting: ");
for(i=0;i<n;++i)
printf("%d ",a[i]);
return 0;
}
OUTPUT:
Enter the size of array: 5
Enter the array elements: 8 4 9 6 3
Array after sorting: 3 4 6 8 9
OUTPUT:
Enter the size of array: 7
Enter the array elements: 23 12 45 78 43 89 31
Array after sorting: 12 23 31 43 45 78 89
Selection sort:
One of the easiest ways to sort a table is by selection. Suppose we have an array A with N elements A[1], A[2].
... A[N] is in memory. The selection sort algorithm for sorting works as follows :
First, find the smallest element in the list and put it in first position. Then find second smallest in list and put it
in second position. And so on.
More precisely:
Pass I : Find location LOC of smallest in list of N elements. A[1], A[2] … A[N] Then interchange A[LOC] and
A[1]. Thus A[1] is sorted.
Pass II : Find location LOC of smallest in sublist of N-1 elements. A[2], A[3] … A[N] Then interchange
A[LOC] and A[2]. Thus A[1] and A[2] is sorted. Since A[1] <= A[2].
Pass N-1 : Find location LOC of smaller of elements A[N-1], A[N] Then interchange A[LOC] and A[N-1].
Thus A[1], A[2] … A[N] is sorted. Since A[N-1] <= A[N].
77 33 44 11 88 22 66 55
Applying selection sort algorithm to array A yields the data as given in table :
voidmain(){
inta[100],n,i,j,min,temp;
clrscr();
printf("\n Enter the Number of Elements: ");
scanf("%d",&n);
printf("\n Enter %d Elements: ",n);
for(i=0;i<n;i++) {
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++){
min=i;
for(j=i+1;j<n;j++){
if(a[min]>a[j])
min=j;
}
if(min!=i){
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
printf("\n The Sorted array in ascending order: ");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
getch();
}
OUTPUT:
Enter the size of array: 5
Enter the array elements: 8 4 9 6 3
Array after sorting: 3 4 6 8 9
OUTPUT:
Enter the size of array: 7
Enter the array elements: 23 12 45 78 43 89 31
Array after sorting: 12 23 31 43 45 78 89
Application to searching:
Searching refers to operation of finding the location LOC of ITEM in DATA. The search is said to be
successful if ITEM does appear in DATA and unsuccessful otherwise.
Binary search:
Suppose DATA is an array which is sorted in increasing numerical order or equivalently or alphabetically.
Then there is an extremely efficient searching algorithm called binary search which can be used to find the
location LOC of given ITEM of information in DATA.
Set BEG := LB
END := UB
MID = INT((BEG+END)/2)
2) Repeat steps 3 and 4 while BEG <= END and DATA[MID] <> ITEM
[ end of if structure ]
6) Exit.
DATA : 11 22 30 33 40 44 55 60 66 77 80 88 99
Now since DATA[MID]=ITEM we draw conclusion that ITEM is found and search is successful. We have
found the ITEM in location LOC = MID = 5
#include <stdio.h>
int main(){
int c, first, last, middle, n, search, array[100];
printf("\n Enter number of elements:");
scanf("%d",&n);
printf("\n Enter %d integers:", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("\n Enter value to find:");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("\n Not found! %d isn't present in the list.", search);
return 0;
}
OUTPUT:
45 found at location 3
OUTPUT:
1) Compared to linear search (checking each element in the array starting from the first), binary search is
much faster. Linear search takes, on average N/2 comparisons (where N is the number of elements in
the array), and worst case N comparisons. Binary search takes an average and worst-case log2(N)
comparisons. So for a million elements, linear search would take an average of 500,000 comparisons,
whereas binary search would take 20.
2) It’s a fairly simple algorithm, though people get it wrong all the time.
3) It’s well known and often implemented for you as a library routine.
1) It’s more complicated than linear search, and is overkill for very small numbers of elements.
2) It works only on lists that are sorted and kept sorted. That is not always feasible, especially if elements
are constantly being added to the list.
3) It works only on element types for which there exists a less-than relationship. Some types simply
cannot be sorted (though this is rare).
4) There is a great lost of efficiency if the list does not support random-access. You need, for example, to
immediately jump to the middle of the list. If your list is a plain array, that’s great. If it’s a linked-list,
not so much. Depending on the cost of your comparison operation, the cost of traversing a non-random-
access list could dwarf the cost of the comparisons.
5) There are even faster search methods available, such as hash lookups. However a hash lookup requires
the elements to be organized in a much more complicated data structure (a hash table, not a list).
Linear search:
Also called as sequential search.Linear search is a very simple search algorithm. In this type of search, a
sequential search is made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data collection.
#include <stdio.h>
int main(){
int array[100], search, c, n;
printf("\n Enter the number of elements in array:");
scanf("%d", &n);
printf("\n Enter %d integer(s):", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("\n Enter a number to search:");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) /* If required element is found */
{
printf("\n %d is present at location %d.", search, c+1);
break;
}
}
if (c == n)
printf("\n %d isn't present in the array.\n", search);
return 0;
}
OUTPUT:
OUTPUT:
#include <stdio.h>
int main(){
int array[100], search, c, n, count = 0;
printf("\n Enter the number of elements in array:");
scanf("%d", &n);
printf("\n Enter %d numbers", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("\n Enter the number to search");
scanf("%d", &search);
for (c = 0; c < n; c++) {
if (array[c] == search) {
printf("\n %d is present at location %d.\n", search, c+1);
count++;
}
}
if (count == 0)
printf("\n %d isn't present in the array.\n", search);
else
printf("\n %d is present %d times in the array.\n", search, count);
return 0;
}
OUTPUT:
1) The linear search is inefficient - If the array being searched contains 20,000 elements, the algorithm
will have to look at all 20,000 elements in order to find a value in the last element. In an average case,
an item is just as likely to be found near the beginning of the array as near the end. Typically, for an
array of N items, the linear search will locate an item in N/2 attempts. If an array has 50,000 elements,
the linear search will make a comparison with 25,000 of them in a typical case. This is assuming that
the search item is consistently found in the array. N/2 is the average number of comparisons. The
maximum number of comparisons is always N.
Multidimensional array:
From flat abstract presentations let’s move to dimensional data presentation. So far we have looked at arrays
having single dimension. It is also possible for arrays to have more than single dimension, i.e..either two or
more.
Initializing a 2-D array:
It is important to remember that while initializing an array it is necessary to mention second column(dimension)
whereas first dimension is optional.
Whereas skipping both the dimensions or skipping the row dimension is not permitted.
Col No 0 Col No 1
Row No 0 11 21
Row No 1 31 41
Row No 2 51 61
This is drawn for our reference. This arrangement is conceptually true. This is because in memory there are no
rows & columns. In memory, irrespective of dimensions the array elements are stored in one continuous chain.
The actual memory map is shown below :
101 marks[0][0] 11
103 marks[0][1] 21
105 marks[1][0] 31
107 marks[1][1] 41
109 marks[2][0] 51
111 marks[2][1] 61
PROGRAM: To illustrate the concept of two dimensional array
#include<stdio.h>
int main(){
intdisp[2][3];/* 2D array declaration*/
int i, j;
for(i=0; i<2; i++){
for(j=0;j<3;j++){
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d",&disp[i][j]);
}
}
OUTPUT:
PROGRAM: To read a matrix and prints sum and product of all elements of the two dimensional array.
#include <stdio.h>
#define MAXROW 10
#define MAXCOL 10
int main(){
int matrix[MAXROW][MAXCOL];
inti,j,r,c;
intsum,product;
printf("Enter number of Rows :");
scanf("%d",&r);
printf("Enter number of Cols :");
scanf("%d",&c);
printf("\nEnter matrix elements :\n");
for(i=0;i<r;i++) {
for(j=0;j<c;j++) {
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
} }
sum=0; /*initializing sum and product variables*/
product=1;
for(i=0;i<r;i++){
for(j=0;j<c;j++){
sum+=matrix[i][j];
product*=matrix[i][j];
}
}
printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);
return 0;
}
OUTPUT:
Enter number of Rows :3
Enter number of Cols :3
void main(){
staticint array[10][10];
int i, j, m, n;
printf("Enter the order of the matrix \n");
scanf("%d %d",&m,&n);
printf("Enter the coefiicients of the matrix\n");
for(i =0; i < m;++i){
for(j =0; j < n;++j){
scanf("%d",&array[i][j]);
} }
printf("The given matrix is \n");
for(i =0; i < m;++i){
for(j =0; j < n;++j){
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for(j =0; j < n;++j){
for(i =0; i < m;++i){
printf(" %d", array[i][j]);
}
printf("\n");
}
}
OUTPUT:
#include<stdio.h>
int main(){
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d %d",&r1,&c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2,&c2);
for(i=0; i<r1;++i)
for(j=0; j<c2;++j){
result[i][j]=0;
}
printf("\nOutput Matrix:\n");
for(i=0; i<r1;++i)
for(j=0; j<c2;++j){
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return0;
}
OUTPUT:
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.
Output Matrix:
24 29
6 25
PROGRAM: To find row sum and column sum of matrix
#include<stdio.h>
int main(){
int i, j, rows, columns, a[10][10], Sum;
printf("\n Please Enter Number of rows and columns : ");
scanf("%d %d", &i, &j);
printf("\n Please Enter the Matrix Elements \n");
for(rows = 0; rows < i; rows++){
for(columns = 0; columns < j; columns++){
scanf("%d", &a[rows][columns]);
}
}
for(rows = 0; rows < i; rows++) {
Sum = 0;
for(columns = 0;columns < j; columns++){
Sum = Sum + a[rows][columns];
}
printf("\n The Sum of Elements of a Rows in a Matrix = %d", Sum );
}
OUTPUT:
OUTPUT:
3-D array can be thought of array of array of array. The outer array has two elements, each of which is one
dimensional array of 5 elements.
The first subscript should be [1], since element is in second 2-D array, the second subscript is [2], since element
is in third row of 2-D array. The third subscript should be [3] since elements is in fourth position of one
dimensional array.
i.e, arr[1][2][3];