You are on page 1of 17

Computer

project

C Programming – Arrays

In this tutorial you will learn about C Programming - Arrays


- Declaration of arrays, Initialization of arrays, Multi
dimensional Arrays, Elements of multi dimension arrays
and Initialization of multidimensional arrays.

The C language provides a capability that enables the user


to define a set of ordered data items known as an array.

Suppose we had a set of grades that we wished to read


into the computer and suppose we wished to perform
some operations on these grades, we will quickly realize
that we cannot perform such an operation until each and
every grade has been entered since it would be quite a
tedious task to declare each and every student grade as a
variable especially since there may be a very large
number.

In C we can define variable called grades, which


represents not a single value of grade but a entire set of
grades. Each element of the set can then be referenced by
means of a number called as index number or subscript.

Declaration of arrays:
Like any other variable arrays must be declared before
they are used. The general form of declaration is:

type variable-name[50];

The type specifies the type of the elements that will be


contained in the array, such as int float or char and the
size indicates the maximum number of elements that can
be stored inside the array for ex:
float height[50];

Declares the height to be an array containing 50 real


elements. Any subscripts 0 to 49 are valid. In C the array
elements index or subscript begins with number zero. So
height [0] refers to the first element of the array. (For this
reason, it is easier to think of it as referring to element
number zero, rather than as referring to the first element).

As individual array element can be used anywhere that a


normal variable with a statement such as

G = grade [50];

The statement assigns the value stored in the 50th index


of the array to the variable g.
More generally if I is declared to be an integer variable,
then the statement g=grades [I];
Will take the value contained in the element number I of
the grades array to assign it to g. so if I were equal to 7
when the above statement is executed, then the value of
grades [7] would get assigned to g.

A value stored into an element in the array simply by


specifying the array element on the left hand side of the
equals sign. In the statement

grades [100]=95;

The value 95 is stored into the element number 100 of the


grades array.
The ability to represent a collection of related data items
by a single array enables us to develop concise and
efficient programs. For example we can very easily
sequence through the elements in the array by varying
the value of the variable that is used as a subscript into
the array. So the for loop

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


sum = sum + grades [i];
Will sequence through the first 100 elements of the array
grades (elements 0 to 99) and will add the values of each
grade into sum. When the for loop is finished, the variable
sum will then contain the total of first 100 values of the
grades array (Assuming sum were set to zero before the
loop was entered)

In addition to integer constants, integer valued


expressions can also be inside the brackets to reference a
particular element of the array. So if low and high were
defined as integer variables, then the statement

next_value=sorted_data[(low+high)/2]; would assign to


the variable next_value indexed by evaluating the
expression (low+high)/2. If low is equal to 1 and high were
equal to 9, then the value of sorted_data[5] would be
assigned to the next_value and if low were equal to 1 and
high were equal to 10 then the value of sorted_data[5]
would also be referenced.

Just as variables arrays must also be declared before they


are used. The declaration of an array involves the type of
the element that will be contained in the array such as int,
float, char as well as maximum number of elements that
will be stored inside the array. The C system needs this
latter information in order to determine how much
memory space to reserve for the particular array.

The declaration int values[10]; would reserve enough


space for an array called values that could hold up to 10
integers. Refer to the below given picture to conceptualize
the reserved storage space.

values[0
]

values[1
]

values[2
]

values[3
]

values[4
]

values[5
]

values[6
]

values[7
]

values[8
]

values[9
]

The array values stored in the memory.

Initialization of arrays:
We can initialize the elements in the array in the same
way as the ordinary variables when they are declared. The
general form of initialization off arrays is:

type array_name[size]={list of values};

The values in the list care separated by commas, for


example the statement

int number[3]={0,0,0};

Will declare the array size as a array of size 3 and will


assign zero to each element if the number of values in the
list is less than the number of elements, then only that
many elements are initialized. The remaining elements
will be set to zero automatically.

In the declaration of an array the size may be omitted, in


such cases the compiler allocates enough space for all
initialized elements. For example the statement

int counter[]={1,1,1,1};

Will declare the array to contain four elements with initial


values 1. this approach works fine as long as we initialize
every element in the array.

The initialization of arrays in c suffers two draw backs


1. There is no convenient way to initialize only selected
elements.
2. There is no shortcut method to initialize large number
of elements.

/* Program to count the no of positive and negative


numbers*/
#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the array\n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array\n”);
for I=0;I < n;I++)
scanf(“%d”,&a[I]);
for(I=0;I < n;I++)
{
if(a[I] < 0)
count_neg++;
else
count_pos++;
}
printf(“There are %d negative numbers in the
array\n”,count_neg);
printf(“There are %d positive numbers in the
array\n”,count_pos);
}

Multi dimensional Arrays:


Often there is a need to store and manipulate two
dimensional data structure such as matrices & tables.
Here the array has two subscripts. One subscript denotes
the row & the other the column.
The declaration of two dimension arrays is as follows:

data_type array_name[row_size][column_size];
int m[10][20]

Here m is declared as a matrix having 10 rows( numbered


from 0 to 9) and 20 columns(numbered 0 through 19). The
first element of the matrix is m[0][0] and the last row last
column is m[9][19]

Elements of multi dimension arrays:


A 2 dimensional array marks [4][3] is shown below figure.
The first element is given by marks [0][0] contains 35.5 &
second element is marks [0][1] and contains 40.5 and so
on.

marks [0] Marks [0] Marks [0]


[0] [1] [2]
35.5 40.5 45.5

marks [1] Marks [1] Marks [1]


[0] [1] [2]
50.5 55.5 60.5

marks [2] Marks [2] Marks [2]


[0] [1] [2]

marks [3] Marks [3] Marks [3]


[0] [1] [2]

Initialization of multidimensional arrays:


Like the one dimension arrays, 2 dimension arrays may be
initialized by following their declaration with a list of initial
values enclosed in braces

Example:

int table[2][3]={0,0,01,1,1};

Initializes the elements of first row to zero and second row


to 1. The initialization is done row by row. The above
statement can be equivalently written as

int table[2][3]={{0,0,0},{1,1,1}} By surrounding the


elements of each row by braces.
C allows arrays of three or more dimensions. The compiler
determines the maximum number of dimension. The
general form of a multidimensional array declaration is:

date_type array_name[s1][s2][s3]…..[sn];

Where s is the size of the ith dimension. Some examples


are:

int survey[3][5][12];
float table[5][4][5][3];

Survey is a 3 dimensional array declared to contain 180


integer elements. Similarly table is a four dimensional
array containing 300 elements of floating point type.

/* example program to add two matrices & store the


results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrix\n”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be added\n”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j < n;j++)
scanf(“%d”,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j < q;j++)
scanf(“%d”,&b[i][j]);
printf(“the sum of the matrix a and b is”);
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++)
printf(“%d\t”,&a[i][j]);
printf(“\n”);
}
}

TWO-DIMENSIONAL ARRAYS
Two-dimensional arrays are a little more complicated to
use than one-dimensional ones. This page presents two
methods of passing a pointer to a two-dimensional array
to a function for processing.

• The first method uses subscript notation inside the


function. This method has the same disadvantage as
in Pascal -- the function is essentially array specific in
that the data types need to match. However, while in
Pascal you need to have a programmer-defined
double-subscripted type which is used for both the
array and the parameter in the called function, in C
only the second subscript in each needs to match. A
complete sample program is provided below.
• The second method uses typecasting in the function
call and a pointer with offsets inside the function.
This method permits the programmer to use the
same function to process information in arrays with
different dimensions. A complete sample program is
provided below.

Subscript Notation
Consider an int array as declared below.
#define NUM_STUDENTS 5
#define NUM_TESTS 4
int grades[NUM_STUDENTS][NUM_TESTS];

• By convention, the first subscript is understood to be


for rows and the second for columns.
• This array can hold up to 20 integer values, the
product of the values used to declare the array.
• As is usual in C, subscripts start with zero, so the
subscripts range from 0 to 4 for the rows and 0 to 3
for the columns.
• If the system uses four bytes for an int, this array
would use 80 bytes of RAM. All of the bytes are in
consecutive memory locations, the first row
occupying the first 20 bytes, the second the next 20,
and so on.

The following table illustrates how the subscripts are


specified for this array, which has five (5) rows and four
(4) columns.
0 1 2 3
[0] [0] [0]
0 [0][3]
[0] [1] [2]
[1] [1] [1]
1 [1][3]
[0] [1] [2]
[2] [2] [2]
2 [2][3]
[0] [1] [2]
[3] [3] [3]
3 [3][3]
[0] [1] [2]
4 [4] [4] [4] [4][3]
[0] [1] [2]

Array Initialization: Inline


To initialize all elements of the grades array to -1 (a
number that is highly improbable for a grade), you could
use a nested loop structure such as the following.
for( i = 0; i < NUM_STUDENTS; i++)
for( j = 0; j < NUM_TESTS; j++)
grades[i][j] = -1;

Array Initialization: At Declaration


It is also possible to initialize elements of an array at the
time of its declaration. The following declaration assigns
values for three grades for each of the first two students in
the array. Note that the values for a specific row are
enclosed within their own pair of curly brackets.
int grades[NUM_STUDENTS][NUM_TESTS] = { {55, 60,
65},
{95, 90, 85} };
It may facilitate your programming, if you keep track of
how many elements in the array hold usable values. For
this simple example, we can initialize two variables.
int num_students = 2;
int num_tests = 3;

Array Processing: Using Subscripts in a Function


Since, by definition, the name of any array is a pointer, we
can call a function which returns the highest grade in the
array as follows.
high_test = get_highest( grades, num_students,
num_tests);
The second and third arguments allow the function to
search only the elements which have been initialized.
One of the ways of writing get_highest() uses subscript
notation:
int get_highest(int a[][NUM_TESTS], int row, int col)
/* Assumes that there is at least one element */
{
int i, j;
int highest = a[0][0];
for( i = 0; i < row; i++)
for( j = 0; j < col; j++)
if ( a[i][j] > highest)
highest = a[i][j];
return highest;
}
It is necessary in this instance to specify the number of
columns in the array (the number of items in a row) so
that the compiler can determine the offsets from the
beginning of the array. Unlike with the one-dimensional
array algorithm, where we avoided comparing the first
element with itself, here the extra code required does not
outweigh the simplicity of the above algorithm.

Sample Program 1
This is a complete program which initializes part of an
array of integer grades at the time of its declaration with 6
values and then calls a function to find, return, and print
the highest grade. Note that the dimensions of the array
have been changed from those used in the discussion
above by altering the compiler directives.
#include <stdio.h>

#define NUM_STUDENTS 25
#define NUM_TESTS 10

int get_highest(int a[][NUM_TESTS], int row, int col);

int main()
{
int grades[NUM_STUDENTS][NUM_TESTS] = { {55, 60,
65},
{85, 90, 95} };
int num_students = 2;
int num_tests = 3;
int high_test;

high_test = get_highest( grades, num_students,


num_tests);

printf("The highest score is %d.\n", high_test);


return 0;
}

int get_highest(int a[][NUM_TESTS], int row, int col)


/* Assumes that there is at least one element */
{
int i, j;
int highest = a[0][0];

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


for( j = 0; j < col; j++)
if ( a[i][j] > highest)
highest = a[i][j];
return highest;
}
Back to Top

Pointer Notation with Offset


Consider the int array as declared below. It is the same as
the one discussed above except for the slight modification
of the identifiers. This change was made so that we can
have a second array which will be declared with different
dimensions.
#define NUM_STUDENTS1 5
#define NUM_TESTS1 4
int grades1[NUM_STUDENTS1][NUM_TESTS1];
The following table illustrates the offsets of the elements
from the start of this array, which has five (5) rows and
four (4) columns. The italicized numbers are the subscripts
for the rows and columns.
0 1 2 3
0 0 1 2 3
1 4 5 6 7
1
2 8 9 11
0
1 1 1
3 15
2 3 4
1 1 1
4 19
6 7 8
Array Initialization: Inline
To initialize all elements of the grades1 array to -1 (a
number that is highly improbable for a grade), you could
use a nested loop structure as was done above or do a
cheat such as the following.
for( i = 0; i < NUM_STUDENTS1 * NUM_TESTS1; i++)
*((int *)grades1 + i) = -1;
This method takes advantage of the fact that grades1 is a
pointer constant for a two-dimensional array. It uses the
loop control variable as the offset from the beginning of
the array. The casting of the pointer constant fools the
compiler into thinking that the array is one-dimensional.
Since both our two-dimensional grade1 array and a one-
dimensional array capable of holding 20 ints would be
stored using a total of 80 consecutive bytes of RAM, no
harm is done by this trickery.

Array Initialization: Generalized Using a Function


However, since the code above is array specific, we may
want to generalize by creating a function which will
initialize any two-dimensional array of ints.
void init_int_array(int *a, int num_rows, int num_cols)
{
int i;

for( i = 0; i < num_rows * num_cols; i++)


*(a + i) = -1;
}
Here we are using the generic variable name a which is a
pointer to an int. The loop control variable i is the offset
into the array. The call to this function for grades1 would
be:
init_int_array( (int *)grades1, NUM_STUDENTS1,
NUM_TESTS1);
Here we cast the pointer constant into a pointer to an
integer, which matches the declaration in the function.
The constants for the dimensions of the array are passed
to init_int_array() to be used for the calculation of the total
number of elements in the array.
Array Processing: Generalized Using a Function
If all of the usable data is stored in the upper left corner of
the array, it is a relatively simple matter to access the
appropriate elements. The following call to get_highest()
sends a casted pointer to the array, the number of
columns in the array, and the bounds of the upper left
corner where the data is.
high_test1 =
get_highest( (int *)grades1, NUM_TESTS1,
num_students1, num_tests1);
The code for the function which follows illustrates the
power of pointers and offsets in the C language. While we
may wish to view a list of items as a number of sub-lists,
the items are stored in the computer in consecutive
memory locations. We can use pointer arithmetic to
convert our two-dimensional perception of reality to the
linear view dictated by how RAM is utilized. The four
arguments passed by the function call above are sufficient
for this purpose.

1. The pointer constant grades1 provides the array's


starting point in RAM.
2. NUM_TESTS1 provides the maximum number of
possible items in the sub-list.
3. num_students1 provides the number of rows to be
checked.
4. num_tests1 provides the number of columns to be
checked.

The following expression can be used to access an


element of the array.
*(a + i*cols + j)

1. a, which remains constant, points at the zeroth


element of the list.
2. cols, which remains constant, is the number of
columns in a row.
3. i ranges from 0 to one less than the number of rows
to be searched.
4. j ranges from 0 to one less than the number of
columns to be searched.
With a remaining constant, it can be seen that i*cols + j
provides the offset from the beginning of the list.
Here is a complete function which can be used to return
the largest int in a portion of a two-dimensional array of
any size.
int get_highest(int *a, int cols, int row, int col)
/* Assumes that the elements with usable values are
in the upper left corner of the array as
delimited by row and col;
cols is the number of columns in the array passed */
{
int i, j;
int highest = *a;

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


for( j = 0; j < col; j++)
if ( *(a + i*cols + j) > highest)
highest = *(a + i*cols + j);
return highest;
}

Sample Program 2
This is a program which initializes parts of two arrays of
integer grades at the time of their declaration, each with 6
values. Then it calls a function to find, return, and print
the highest grade in each of the two arrays.
#include <stdio.h>

#define NUM_STUDENTS1 25
#define NUM_TESTS1 10
#define NUM_STUDENTS2 15
#define NUM_TESTS2 8

int get_highest(int *a, int cols, int row, int col);

int main()
{
int grades1[NUM_STUDENTS1][NUM_TESTS1] = { {55,
60, 65},
{85, 90, 95} };
int num_students1 = 2;
int num_tests1 = 3;
int high_test1;

int grades2[NUM_STUDENTS2][NUM_TESTS2] = { {55,


60},
{85, 90},
{75, 70} };
int num_students2 = 3;
int num_tests2 = 2;
int high_test2;

high_test1 =
get_highest( (int *)grades1, NUM_TESTS1,
num_students1, num_tests1);
printf("The highest score in the first class is %d.\n",
high_test1);

high_test2 =
get_highest( (int *)grades2, NUM_TESTS2,
num_students2, num_tests2);
printf("The highest score in the second class is %d.\n",
high_test2);

return 0;
}

int get_highest(int *a, int cols, int row, int col)


/* Assumes that the elements with usable values are
in the upper left corner of the array as
delimited by row and col;
cols is the number of columns in the array passed */
{
int i, j;
int highest = *a;

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


for( j = 0; j < col; j++)
if ( *(a + i*cols + j) > highest)
highest = *(a + i*cols + j);
return highest;
}

You might also like