Arrays

An array is a data structure composed of a fixed number of components of the same type which are organised in a linear sequence. A component of an array is selected by assigning an integer value to its index (or subscript) which identifies the position of the component in the sequence.

In C, the arrays are intimately related to pointers. All sorts of array manipulations can also be performed by using pointers which will be discussed later.


8.1 ARRAY DECLARATION

The syntax of array declaration is as follows,

{} data type [expression]{[expression]};

Example 8.1 :

int arr[10];

The above declaration defines an array called arr of size 10, that is arr consists of 10 elements of same data type int. The elements occupy consecutive cells (each cell houses one element) and form an ordered set of elements. Each element can be identified by its position in the array, and that is called the subscript of an array. The first element is at position 0 and nth element can be found in the (n-1)th position.

The name of the array is arr, which contains the address of the first element(i.e. &arr[0]) of the array. However, an array name such as arr differs from an ordinary pointer variable (like int *p;), because, it is static in nature and cannot point to a new memory location other than what it is pointing to.

arr[0] arr[1] arr[9]





























More examples of array declarations :

static float grade[10];

char name[20];

8.2 ARRAY MANIPULATION

The most convenient way of performing array manipulation is to use the for repetitive construct in order to access each element of the array.

The following example illustrates the usage of an array in implementing addition of two vectors :

Example 8.2 :

# include

# define dimension 100

typedef int vector[dimension];

main()

{

vector vect_1,vect_2,result_vect;

int i;

printf(“Enter the vector dimension :”);

scanf(“%d”,&n);

fflush(stdin);

/*accepting values for two arrays vect_1, vect_2 */

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

{

printf(“Give vector element # %d :”,i + 1);

scanf(“%d %d”,&vect_1[i],&vect_2[i]);

fflush(stdin);

result_vect[i]=0;

/* initialising the elements of the array result_vect to 0 */

}

/*vector addition and creation of the resultant vector */

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

result_vect[i] += (vect_1[i] + vect_2[i] );

/* displaying the resultant matrix */

printf(“\n\n”);

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

{

printf(“%d\t”,result_vect[i]);

}

printf(“\n”);

}

Array initialisation can be performed in the following way,

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

But this definition cum initialisation is permitted only in the form of external variable definition. To include the statement inside a function storage class clause static has to be used as a prefix. 1. Describe the output generated by each of the following program:

(a) # include

main ()

{

int a, sum = 0;

static int x[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 0};

for (i = 0; i <>

if ((i % 2) ==0)

sum + = x[i];

printf (“%d”,sum);

}

(b) # include

# define ROWS 3

# define COLS 4

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

main()

{

int i, j, max;

for (i = 0; i <>

{

max =9999;

for (j = 0; j

if (x [i][j] <>

max=z[i][j];

printf(“%d”, max);

}

}

2. Identify the errors in the following C program (if any) which initialises an array such that each of its ten elements is assigned with 0 value.

main()

{

int num_arr[10], i=0;

:

for(;++i <>

}

3. Identify the array defined in each of the following statements. Indicate what values are assigned to the individual array elements.

(a) char game[7] = {‘C’, ‘R’, ‘I’, ‘C’, ‘K’, ‘E’, ‘T’};

(b) char match[]=“Football”;

4. Write an appropriate array definition for each of the following cases:

(a) Define a one dimensional, integer array called A with 10 elements and initialise the array elements with 2,5,8,11,........, 29.

(b) Create a one dimensional, four element character array called object and assign the characters ‘C’, ‘I’, ‘R’,’C’, ‘L’ and ‘E’ to the array elements.

(c) Define a one dimensional, six element floating point array called flt_const having following initials values :

2.005, -3.05452, -1e-4, 340.179, 0.3e8, 0.023415

8.3 STRING - CHARACTER ARRAYS

A string constant, enclosed within a pair of double quotes, consists of 0 (empty string) or more characters terminated by a null (‘\0’) character, which indicates the end of the string.

The following statement in C defines a string variable,

char name[21];

which can store 20 characters each of one byte (with name[0] as the starting element). One extra byte is used to store the null character. The string name can be initialised by a constant.

Example 8.3 :

# include

main()

{

static char name[21]=“Rabindra Nath Tagore”;

printf(“%s\n”,name);

printf(“Enter a new name :”);

scanf(“%s”,name);

fflush(stdin);

printf(“\nThe new name is %s\n”,name);

}

The above program displays the content of the variable name i.e. “Rabindra Nath Tagore” and allows the user to accept a new name in the same variable, and finally comes out of the program displaying the new name on the screen. The absence of the & operator as a prefix of the variable name is conspicuous in the scanf statement, which requires the addresses of the arguments. This is possible since the variable name itself stores the address of the string variable. This will be more clear from the following diagram,





name

R


a


b


i


n


d


r


a





N


a


t


h





T


a


g


o


r


e


\0

100

Fig. 8.1 : Representation of a string array.

The variable name is a static pointer (which cannot be reassigned with a new value), which stores the address of the first element of the name array i.e &name[0].

From the above discussion it is obvious that a string variable requires only the starting address of the memory location where the string constant is located, because the end of the string is always indicated by the null.

Consider the following example, where characters in the string are read and processed individually.

Example 8.4 :

# include

# define size 100

char name[size];

main()

{

int count=0;

char c;

while((c=getchar()) != ‘\n’)

{

name[count]=c;

++count;

}

name[count]=‘\0’;

}

8.4 PASSING ARRAYS TO A FUNCTION

An array name can be used as an argument to a function, thus permitting the entire array to be passed to the invoked function. The array name must appear by itself (without brackets or subscript) as an actual argument during the function call. The formal parameter is also written in the same manner, though it must be declared as an array within the formal parameter declarations. When a one dimensional array is used as a formal parameter, in the function declaration array name is written with a pair of empty square brackets. The size of an array is not specified within the formal parameter declaration. Since array name identifies the address of the first element, specifying array name as a parameter to a function essentially implements call by reference mode of parameter transfer.

Example 8.5 : Read a set of numbers and sort them.

# include

# define dimension 100

/* sort an one dimensional integer array in ascending order */

main()

{

int i,k, data[dimension];

void bubble_sort(int m,int a[]);

void read_data(int n,int x[]);

printf(“\nEnter the number of elements to be sorted :”);

scanf(“%d”,&k);

fflush(stdin);

read_data(k,data);

bubble_sort(k,data);

printf(“\n\nSorted data elements are : \n\n”);

for(i=0;i <>

printf(“i = %d data = %d\n”,i+1,data[i]);

}

void read_data( int n, int x[] ) /* read an array of integer */

{

int j;

for( j=0; j <>

{

printf( “\n Enter data element #%d :”, j+1 );

scanf(“%d”, &x[j] );

fflush(stdin);

}

return;

}

void bubble_sort( int m, int a[] ) /* sort an integer array a of m elements in ascending order */

{ int i, j, temp, not_sorted = 1; /* not_sorted is true when the array a is not sorted */

j = m;

while ( not_sorted )

{

not_sorted = 0; /* assume sorted */

for (i = 0; i < ( j - 1) ; ++i)

{

if ( a[i] > a[i+1] )

{ /* exchange */

temp = a[i];

a[i] = a[i+1];

a[i+1]=temp;

not_sorted = 1 ; /* data was not sorted */

} /* end of exchange */

} /* end one pass */

--j ;

} /* repeat until sorted */

return;

}

/* end bubble_sort */

5. For the following cases, the indicated variables and arrays are to be transmitted from main to a function called test. The function test returns a floating point data which is to be assigned to a variable test. Give appropriate definitions and declarations of variables and arrays.

(a) The floating point variables a and b, and a ten element one dimensional integer array int_data are to be transferred..

(b)An integer variable n, a character variable c and a one dimensional 40 element long integer array data_value are to be sent to test.

(c)Transfer a two dimensional, 10 ´80 character array to text.

(d) A 20 character long message and a two dimensional floating point array price having 10 rows and 5 columns are to be transmitted to test.

8.5 MULTIDIMENSIONAL ARRAYS

A one dimensional array of size n can be represented as a contiguous block of n number of elements. Similarly a two dimensional array of m * n (here m and n are representing two dimensions) can be represented as m numbers of one dimensional arrays each consisting of n number of elements.

The syntax for declaring a multidimensional array is as follows,

storage-class datatype array_name [expression1] [expression2] .. [expression n];

Column 0 1 2 3 4 n-2 n-1

Row 0 . . .

1 . . .

:

:

m-1 . . .

Each element in the array is accessed by the combination of array name and the subscript value. The number of subscripts depend on the dimensions of the array, here we can recall that one subscript is enough to access one element of a one dimensional array.

Example 8.6 :

int x[3][3];

Initialisation of multidimensional arrays

int data_values[3][4]={

{1,2,3,4},

{5,6,7,8},

{10,11,12,13}

};

The following example of matrix manipulation illustrates the usage of multidimensional array.

Example 8.7 :

# include

# define row_dimension 100

# define col_dimension 100

typedef int matrix[row_dimension][col_dimension];

main()

{

matrix a,b,c;

int i,j,k,n;

printf(“Enter the matrix dimension :”);

scanf(“%d”,&n);

fflush(stdin);

/*accepting values of the elements of two arrays a,b to form n by n matrices */

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

for(j=0 ; j < n ; j++)

{

printf(“Give matrix element with row %d column %d:”,i + 1,j + 1);

scanf(“%d %d”,&a[i][j],&b[i][j]);

fflush(stdin);

c[i][j]=0; /* initialising the elements of the array c to 0 */

}

/* matrix multiplication and creation of the resultant matrix */

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

for(j=0 ; j < n ; j++)

for(k=0 ; k < n;k++)

c[i][j] += (a[i][k] * b[k][j] );

/* displaying the resultant matrix */

printf(“\n\n”);

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

{

for(j=0 ; j < n ; j++)

{

printf(“%d\t”,c[i][j]);

}

printf(“\n”);

}

}

6. Identify the array defined in each of the following statements. Indicate what values are assigned to the individual array elements.

(a) int a [2] [4] = {

{5, 4, 3, 2},

{9, 8, 7, 6}

};

(b) int data[2] [3] [4] = {

{

{3, 2, 1},

{9, 8},

{5, 4, 6, 7}

},

{

{1,2},

{},

{2, 3,4}

}

}:

(c) char room_colours [3] [7] = {

{‘B’, ‘l’, ‘u’, ‘e’},

{‘G’, ‘r’, ‘e’, ‘e’, ‘n’},

{‘Y’, ‘e’,’l’, ‘l’, ‘o’, ‘w’}

};

8.6 PASSING MULTIDIMENSIONAL ARRAYS AS PARAMETERS TO FUNCTIONS

The formal argument declaration within a function definition must include explicit size specifications of all the subscripts except the first. The size specification must be consistent with the corresponding size specification in the calling program. The first subscript position should be written with an empty pair of square brackets as in one dimensional array.

Example 8.8 :

# include

#define row_size 50

#define col_size 50

main()

{

int a[row_size][col_size], b[row_size][col_size], c[row_size][col_size];

int m,n,k;

void read_data(int x[][col_size], int nrows, int ncols);

void matrix_mult(int x[][col_size], int y[][col_size], int z[][col_size], int nrows,int ncols1, int ncols2);

read_data(a, m, n);

read_data(b, n, k);

:

matrix_mult(a, b, c, m, n, k);

:

:

}

void matrix_mult(int x[][col_size], int y[][col_size], int z[][col_size], int nrows,int ncols1, int ncols2)

{

int i,j,k;

for(i = 0 ; i <>

for(k = 0 ; j <>

{

z[i][k] = 0;

for(j = 0 ; j <>

z[i][k]+ = x[i][j] * y[j][k];

}

return;

}

8.7 TWO DIMENSIONAL CHARACTER ARRAYS

A two dimensional character string consists of a collection of single dimensional character strings. The declaration of a two dimensional character string does not differ much from two dimension array declaration of integer data. Each individual string however, is terminated by a null character.

The syntax for declaring a two dimensional array is as follows :

char name[3][20];

The variable name is a two dimensional string capable of storing 3 strings where maximum length of each string is 19 characters (one position is kept aside for null).

The initialisation of such an array of strings can be performed in either of the two ways as shown below :

char city[4][10]={

{“Calcutta”},

{“Bombay”},

{“Madras”},

{“Delhi”}

};

or,

char city[4][10]={

{‘C’, ‘a’, ‘l’, ‘c’, ‘u’, ‘t’, ‘t’, ‘a’, ‘\0’},

{‘B’, ‘o’, ‘m’, ‘b’, ‘a’, ‘y’, ‘\0’},

{‘M’, ‘a’, ‘d’, ‘r’, ‘a’, ‘s’, ‘\0’},

{‘D’, ‘e’, ‘l’, ‘h’, ‘i’, ‘\0’}

};

name
name[0][0]





name[0]





C


a


l


c


u


t


t


a


\0

name[1]





B


o


m


b


a


y


\0






name[2]





M


a


d


r


a


s


\0






name[4]





D


e


l


h


i


\0









name[4][5]

Fig 8.2 : Representation of two-dimensional character array

Let us consider the sample program listing that describes reading and printing elements of an array of character strings.

Example 8.9 :

#include

# define r 10

#define c 30

main()

{

char name[r][c],chr;

int i,j;

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

{

printf(“Enter Name # %d :”,i+1);

j=0;

while(((chr=getchar()) != ‘\n’) && j < (c - 1))

{

name[i][j]=chr;

++j;

}

name[j]=‘\0’;

}

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

printf(“The name %d is : %s\n”,i+1,name[i]);

}

7. Match the following :

i) arr_ele[3] a) index

ii) subscript b) three dimensional array

iii) int num[3][4] c) fourth element of an array

iv )int num[4][3] d)two dimensional array with 3 rows and 4 columns

v) int num[3][4][5] e) two dimensional array with 4 rows and three columns

0 comments: