Unit 1 - Array
Overview:
In this unit, you will learn to work with arrays. You will learn to declare, initialize and access
elements of an array with the help of examples. An array is a collection of data items, all
of the same type, accessed using a common name. A one-dimensional array is like a list;
A two dimensional array is like a table; The C language places no limits on the number of
dimensions in an array, though specific implementations may.
Unit Objectives:
After successful Completion of this unit, you should be able to:
know in details the basic concepts of Arrays.
be more familiar with the different uses of Arrays.
be able to apply the use of Arrays in some complicated applications.
make the student develop good programming techniques using Arrays.
Course Materials:
ARRAY CONCEPTS
Imagine we have a problem that requires 20 integers to be processed. We need
to read them, process them, and print them. We must also keep these 20 integers in
memory for the duration of the program. We can declare and define 20 variables, each
with a different name, as shown in the figure below.
Number0
Number1
Number2
. .
. .
. .
Number19
Illustration: Twenty variables
5
But having 20 different names creates another problem. How can we read 20
integers from the keyboard and store them? To read 20 integers from the keyboard, we
need twenty references, each to one variable. Furthermore, once we have them in
memory, how can we print them? To print them, we need another twenty references.
Although this may be acceptable for 20 integers, it is definitely not acceptable for
200 or 2000 or 20000 integers. To process large amounts of data we need a powerful
data structure, such as array.
Characteristics of an Array
An array is a fixed-size, sequenced collection of elements of the same data type.
An array is a sequence of data items that are of the same type, that are indexible, and that
are stored contiguously.
Arrays are data type that is used to represent a large number of homogenous values.
Since an array is a sequenced collection, we can refer to the elements in the array as the
first element, the second element, and so forth until we get to the last element. If we were
to put our twenty numbers into an array, we could designate the first element as shown
below.
Number0
In similar fashion, we could refer to the second number as Number1, and the third number
as Number2. Continuing the series, the last number would be Number19.
Process twenty variables
Number0 Number1 N mbe n-1
What we have seen is that the elements of the array are individually addressed through
their subscripts. This concept is graphically shown in the next figure to be presented. The
array as a whole has a name, numbers, but each member can be accessed individually
using its subscript.
The advantages of the a a ld be limi ed if e didn al ha e g amming
constructs that would allow us to process the data more conveniently. Fortunately, there
is a powerful set of programming constructs loops- that makes array processing easy.
Number0 Number[0]
Number1 Number[1]
. .
. .
. .
.Number19 .
Number[19]
a. Subscript form b. Index from
6
An array of numbers
We can use loops to read and write the elements in an array. We can use oops to
add, subtract, multiply, and divide the elements. We can also use loops for more complex
processing such as calculating averages.
But one question still remains. How can we write an instruction so that at one time it refers
to the first element of an array, and the next time it refers to another element. IT is really
quite simple: we simply borrow from the subscript concept we have been using.
Rather than using subscripts, however, we will place the subscript value in square
brackets. Using this notation, we would refer to Number 0 as : Number[0]
Following the convention, Number 1 becomes Number[1] and Number 19 becomes
Number[19]. This is known as indexing. Using reference, we now refer to our array using
the variable i : Number[i]
USING ARRAYS IN C
We will first show how to declare and define arrays. Then we will look at several typical
applications using arrays including reading values into arrays, accessing and exchanging
elements in arrays, and printing arrays.
Declaration and Definition
An array must be declared and defined before it can be used. Declaration and definition
tell the compiler the name of the array, the type of each element, and the size or number
of elements in the array. The size of the array is a constant and must have a value at
compilation time.
#include<stdio.h>
#include<conio.h>
int scores[20], i, sum=0;
void main()
array declaration
{
clrscr();
in f( lea e enter 20 scores:\n );
for(i=0; i<20; i++)
canf( %d , & c e [i]);
sum=sum + scores[i];
}
getch();
}
7
Declaring and Defining Arrays
An array is defined in much the same manner as ordinary variables, except that each array
name must be accompanied by a size specification (the number of elements). For one
dimensional array, the size is specified by a positive integer expression enclosed in square
brackets. The expression is usually written as a positive integer constant.
The General Form – One-dimensional array
storage class data-type array[expression];
where storage class refers to storage class of the array, data-type is the data type, array
is the array name and expression is positive-valued integer expression that indicates the
number of array elements. Storage class is optional.
Example of one-dimensional array definition or array declaration:
int ccmit[5];
char bscs[30];
float bsit[20];
double ITCS[12];
the first line indicates that ccmit is a 5 element integer array, the second line describes
that bscs is a 30 element character array. In line 3, bsit is defined as 20 element floating
point array and the last line, ITCS is a 12 element double array.
Consider the following array definition:
int x[4] = {1, 2, 3};
float y[5] = {1.0, 1.25, 1.5};
The results on an element by element basis are:
x[0] = 1 y[0] = 1.0
x[1] = 2 y[1] = 1.25
x[2] = 3 y[2] = 1.5
x[3] = 0 y[3] = 0
y[4] = 0
In each case, all of the array elements are automatically set to zero except those that have
been explicitly initialized within the array definition.
One dimensional array string data type a character in a string can be accessed either
as an element in an array by making use of a pointer to character. The flexibility it provides
makes C especially useful in writing string processing programs. The standard library
provides many useful string handling functions.
8
Strings are handled somewhat differently. In particular, when a string constant is assigned
to an external or a static character array as part of the array definition, the array size
specification is usually omitted. The proper array size will be assigned automatically. This
will include a provision f he n ll cha ac e hich i \0 and a ma icall added a he
end of every string.
Example:
Consider the character array definition. It includes an initial assignment of the string
c n an CCMIT .
cha c llege[6] = CCMIT ;
It defines the following five element character array:
c llege[0] = C;
c llege[1] = C;
c llege[2] = M;
c llege[3] = I;
c llege[4] = T;
c llege[5] = \0 ;
The array definition could have been written as :
cha c llege[] = CCMIT ;
Accessing Elements in Arrays
C uses an index to access individual elements in an array. The index must be an integral
value or an expression that evaluates to an integral value. The simplest form for accessing
an element is a numeric constant. For example, given an array scores[20], we could
access the first element as follows:
scores[0]
Typically, however, the index is a variable or an expression. To process all the elements
in scores, a loop similar to the following code is used:
for(i=0; i<10; i++)
scores[i] ..;
You might be wondering how C know where an individual element is located in memory.
In scores, for example, there are ten elements. How does it find just one? The answer is
im le. The a a name i a mb lic efe ence f he add e to the first byte of the
a a . Whene e e e he a a name, he ef e, e a e ac all efe ing he fi
byte of the array. The index represents an offset from the beginning of the array to the
element being referred to. With these two pieces of data, C can calculate the address of
any element in the array using the following simple formula:
element address = array address + (sizeof(element) * index
9
For example, assume that scores is stored in memory at location 10,000. Since scores is
an integer, the size of one element is the size of an integer. Assuming an integer size of
two, the address of the element at index 3 is:
element address = 10,000 + 2 * 3 + 10,006
Storing Values in Array
Declaration and definition only reserve space for the elements in the array. No values will
be stored. If we want to store values in the array, we must either initialize the elements,
read values from the keyboard, or assign values to each individual element.
Initialization
Initialization of all elements in an array can be done at the time of declaration and
definition, just as with variables. For each element in the array we provide a value. The
only difference is that the values must be enclosed in braces and, if there are more than
one, separated by commas. It is a compile error to specify more values than there are
elements n the array. The initial values must appear on the order in which they will be
assigned to the individual array elements, enclosed in braces and separated by commas.
The general form is:
Storage class data-type arrayname[expression]={value1,
value2,..value n};
Where value1 refers to the value of the first array element, value 2 refers to the value of
the second element and so on. The appearance of the expression which indicates the
number of array elements is optional when initial values are present.
Examples of array initialization:
int first_array[5] ={5, 3, 2, 7, 9};
int second_array[] ={11, 21, 75, 24, 5};
int third_array[15]={3, 7, 4, 6, 1};
The first example is a simple array declaration of five integers. It is typically the way array
initialization is coded. When the array is completely initialized, it is not necessary to
specify the size of the array. This case is seen in the second example. It is a good idea,
however to define the size explicitly because it allows the compiler to do some checking
and it is also good documentation.
If the number of value provided is less than the number of elements in the array, the
unassigned elements are filled with zeros. This case is seen in the third example. We
can use this rule to easily initialize a array to all zeros by supplying just the first zero value
of the first element.
Inputting Values
Another way to fill the array is to read the values from the keyboard or a file. This can be
done using a loop when the array I going to be completely filled, the most appropriate loop
is the for because the number of element are fixed and known.
10
Example:
int scores[10];
for(i=0; i<10; i++)
canf( %d , c e [i]);
Several concepts need to be studied in this simple statement. First, we start the index, i,
at zero. Since there are ten elements in the array, we must load the values from index
locations zero through nine. The limit test, therefore, is set at i<10, which conveniently is
the number of elements in the array. Then, even though we are dealing with array
elements, the address operator (&) is still necessary in the scanf call.
Finally, when there is a possibility that all the elements are not going to be filled, then one
of the event-controlled loops (while or do-while) should be used. Which one you use would
depend on the application.
Individual elements can be assigned values using the assignment operator. Any value
that reduces to the proper type can be assigned to an individual array element.
Example:
scores[4] = 23;
On the other hand, you cannot assign one array to another array, even if they match full
in type and size. You have to copy arrays at the individual element level. For example,
to copy an array of 25 integers to a second array of 25 integers, you could use a loop as
shown below:
for(i=0l i<25; i++)
second[i] = first[i];
If the values of an array follow a pattern, we can use a loop to assign values. For example,
the following loop assigns a value that is twice the index number to array scores.
for(i=0l i<25; i++)
scores[i] = I * 2;
Sample program 1:
This is a program that sorts the values of the array num.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num[3] = {5, 3, 7};
int h, i, temp;
for(h=0; h<3; ++h)
11
for(i=0; i<h; ++i)
{
if(num[i] > num[I + 1])
{
temp = num[i];
num[i] = num[I + 1];
num[i+ 1] = temp;
}
}
for(i=0; i<3; i++)
in f( %d\n , n m[i]);
getch();
}
sample run:
Output:
3
5
7
Sample program 2:
/* Program to count the number of positive and negative numbers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50], n, count_neg = 0, count_pos = 0, i;
clrscr();
in f( En e he i e f he a a );
canf( %d ,&n);
in f( En e he elemen f he a a );
for(i=0; i<n; i++)
canf( %d , &a[i]);
for(i=0; i<n; i++)
{
if(a[i] < 0)
count_neg++;
else
count_pos++;
}
in f( The e a e %d nega i e n mbe in he a a \n , c n _neg);
in f( The e a e %d i i e n mbe in he a a \n , c n _ );
getch();
}
12
Multidimensional Arrays
Multidimensional arrays are defined in much the same manner as one-
dimensional. A two-dimensional array requires two pairs of square brackets.
In general term, a multidimensional array definition can be written as:
storage-class data-type arrayname[expression1][expression2];
where storage-class refers to the storage-class of the array, data-type is its data-type,
arrayname is the name of the array and expression1, expression2 are positive-values
integer expression that indicate the number of array elements associated with each
subscript. Remember that storage-class is optional; the default is automatic for arrays
that are defined inside of a function and external for arrays, defined outside of a function.
Several multidimensional array definitions are shown below:
float IT[5][3];
int CS[3][3];
The first line defines array IT as floating-point array having 5 rows and 3 columns while
the second line indicates that array name CS has 3 row and 3 column integer array
elements.
Multidimensional array definition includes the assignment of initial values, the care
must be given to the order in which the initial values are assigned to the array elements.
Consider the following two-dimensional array definition:
int ccmit[3][3] ={1,2,3,4,5,6,7,8,9};
Note that the values can be thought of as a table having 3 rows and 3 columns. Since the
initial values are assigned by rows (last subscript increasing most rapidly), the result of
this initial assignment are as follows;
ccmit[0][0] = 1 ccmit[0][1] = 2 ccmit[0][2] = 3
ccmit[1][0] = 4 ccmit[1][1] = 5 ccmit[1][2] = 6
ccmit[2][0] = 7 ccmit[2][1] = 8 ccmit[2][2] = 9
The natural order in which the initial values are assigned can be altered by forming groups
of initial values enclosed within braces. The values within each innermost pair of braces
will be assigned to those array elements whose last subscript changes most rapidly. In a
two-dimensional array, for example, the value within an inner part of braces will be
assigned to the elements of a row, since the second subscript increases most rapidly. If
there are few values within the pair of braces, the remaining elements of that row will be
assigned zeros.
Remember: On the other hand, the number of values within each part of braces cannot
exceed the defined row size.
13
Example: Here is a variation of the two-dimensional array definition presented in the last
example:
int ccmit[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
This definition results in the same initial assignment as in the last example. Thus the three
values in the first inner pair of braces are assigned to the array elements in the first row,
the values in the second inner part of braces are assigned to the array elements in the
second row, and so on. Note that an outer pair of braces is required.
Now consider the following two-dimensional array definition
int ccmit[3][4] = {{1,2,3},{4,5,6},{7,8,9}};
This definition assigns values only to the first three elements in each row. Therefore, the
array elements will have the following initial values:
ccmit[0][0]=1 ccmit[0][1]=2 ccmit[0][2]=3 ccmit[0][3]=0
ccmit[1][0]=4 ccmit[1][1]=5 ccmit[1][2]=6 ccmit[1][3]=0
ccmit[2][0]=7 ccmit[2][1]=8 ccmit[2][2]=9 ccmit[2][3]=0
Notice that the last character in each row is assigned a value zero.
If the preceding array definition is written as
int ccmit[3][4] = {1,2,3,4,5,6,7,8,9};
then three of the array elements will again be assigned a value of zero, though the order
of the assignment will be different. In particular, the array elements will have the following
initial order:
ccmit[0][0]=1 ccmit[0][1]=2 ccmit[0][2]=3 ccmit[0][3]=4
ccmit[1][0]=5 ccmit[1][1]=6 ccmit[1][2]=7 ccmit[1][3]=8
ccmit[2][0]=9 ccmit[2][1]=0 ccmit[2][2]=0 ccmit[2][3]=0
Finally, consider the array definition below:
int ccmit[3][3]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
This will result in a compilation error since the number of values in each inner pair of
braces exceeds the defined array size.
Sample Program 3
/* example program to add two matrices and store the results in the 3 rd matrix*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]10], b[10][10], c[10][10], i, j, m=0,n=0,p=0,q=0;
clrscr();
in f( en e he de f he ma i \n );
canf( %d%d , & , & );
if(m==p && n==q)
14
{
in f( ma i can be added\n );
in f( en e he elemen f he ma i a );
}
for(i=0;i<m;i++)
for(j=0;j<n;j++)
canf( %d , &a[i][j]);
in f( en e he elemen f he ma i b );
for(i=0;i<p;i++)
for(j=0;j<q;j++)
canf( %d , &b[i][j]);
in f( he m f he ma i a and b i );
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] + b[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
in f( d\ ,a[i][j]);
in f( \n );
getch();
return;
}}
Watch:
[Link]
[Link]
Read:
Programming Logic and Design, 8 th ed/ 3rd edition, Joyce Farrel,2015
Review:
1. What is array?
2. What are the types of array? Differentiate each.
Activities/Assessments: Unit 1 Array
1. Write an appropriate array definition for each of the following problem situations:
a. Define a one-dimensional, 12-element integer array called C. Assign the
al e 1, 4, 7, 10, , 34 he a a elemen .
b. Define a one-dimensional character array called point. Assign the string
NORTH he a a elemen . End he ing i h he n ll cha ac e .
c. Define a one-dimensional, four-character array called letters, assign the
cha ac e N , S , E , and W he a a elemen .
15