You are on page 1of 25

Arrays

in
C

Needs

So far, our programs have been very limited


because we could assign only one value to
one specific variable. What we would like to
do is to assign values to a whole group of
variables and manipulate the entire group of
data. For example, if you take 6000 readings
in an experiment and you want to calculate
their average, it would be ridiculous if you
had to type in your C program a statement

Needs

Therefore, let's look at the problem from


a mathematical viewpoint and express it
using a mathematical equation:

This expression is much simpler to


understand than our first expression with
the 6000 terms as it uses a summation

Subscripted Variables

We have already learned how to


implement a
summation in C, namely by using a
loop statement, but we have not yet
learned how to express something
like an indexed variable or
subscripted variable in C.
Hence, we need to learn about

Array Declaration

In computer science an array is a data


structure consisting of a group of
homogeneous elements that are accessed by
indexing or subscripting.
An array is a series of elements of the same
type placed in contiguous memory locations
that can be individually referenced by adding
an index/subscript to a unique identifier.
Like other variables an array needs to be
declared so that the compiler will know what

Array Declaration

One-Dimensional Array Declaration:


Where each
<data_type> array_name1 [size
size1],
i
array_name2 [size2], (i=1,2,3, n)
is an
array_namen [sizeunsigned
n] ;
positive
integer
For example the declaration:
constant. It
float mydata[ 5000 ];
can not be a
variable.
sets aside sufficient memory for 5000
members
of an array called 'mydata'. Each member of the
array is type 'float'. Each individual member of

Accessing the elements of an array

Each element is taking


4 bytes

To assign a value to the 3rd element of the above


declaration, we write: e.g. numbers[2] = 23;
To access and display the same value, we write:

printf(%d, numbers[2]);

Create an array of 10 integers, store 10


numbers to them. Then display them.
void main()
{
/* Create and Reading
int no[10], index;
part */
printf(Enter 10 numbers\n);
for( index = 0; index < 10; index ++ )
{
printf (Number-%d, index + 1);
scanf(%d, & no[ index ]);
}

Pgm contd

printf(Numbers are \n); /* Display part


*/ index ++ )
for( index = 0; index < 10;
{
printf (%d\n, no[ index ] );
}
} /* end of main() */
Outp
ut 10
Enter
numbers
Number-1: 12 Users
Entry
Number-2: 13
Number-3: 34

Numbers are
12
13
34

Arrays and Addresses


In the following array, the name number
identifies the address of the area of memory
where your data is stored, and the specific
location of each element is found by combining
this with the index value, because the index
value represents an offset of a number of
elements from the beginning of the array.

long number[4];
When you declare an array, you give the
compiler all the information it needs to allocate
the memory for the array. You tell it the type of
value, which will determine the number of bytes
that each element will require, and how many

An index value specifies how many elements


from the beginning you have to go to address
the element you want. The address of an array
element is going to be the address where the
array starts, plus the index value for the
element multiplied by the number of bytes
required to store each element of the type
stored in the array. Following Figure represents
the way that array variables are held in
memory.

You can obtain the address of an array


element in a fashion similar to ordinary
variables. For an integer variable called
value, you would use the following
statement to print its address:

printf("\n%p", &value);
To output the address of the third
element of an array called number, you
could write the following:

The following fragment sets the value of the


elements in an array and outputs the address
and contents of each element:
int data[5];
for(int i = 0 ; i<5 ; i++)
{
data[i] = 12*(i+1);
printf("\ndata[%d] Addr: %p Content: %d", i,
&data[i], data[i]);
}

The for loop variable i iterates over all the legal


index values for the data array. Within the loop,
the value of the element at index position i is
set to 12*(i+1). The output statement displays
the current element with its index value, the

Initializing a 1-Dim Array


To initialize the elements of an array, you just
specify the list of initial values between braces
and separated by commas in the declaration

<data_type> array_name [ size ] =


{ val1, val2, };
Size may be

e.g.

optional, if ignored
size will automatically
be set to the number
of values supplied.

Number of
values may be
equal or less
to the size of
the array

double values[5] = { 1.5, 2.5, 3.5,


Unsized Array, size set
4.5, 5.5 };
to 4

char

exampl
text[5]={ a , b , c , d , e };
es

tex
t

char t[10] = { a , b , c , d , e };
t

a b

Unused
space

char s[ ] = { a , b , c , d , e };
s

char str[ ] = comp;


str

\0

st

\0

char st[ ] = { c , o , m , p , \0 };
int num[10] ={ 12, 34, 56, 76, 8, 33 };
num 12 34 56 76

33

Unused
space

char st[ ] ={ a , b , c };
printf(%c%c%c, st[0], st[1],
st[2]);
Outpu

exampl
es

ab
c ] ={ a , b , c };
char st[
t

printf(%s, st );
Outpu
t

abc

Unwanted
%s in printf searches a nul
symbol

character ( \0 ) from the


starting address designated
by the array variable (st).
printf() function displays all
the characters until it gets a

exampl
char st[ ] ={ a , b , c, \0 };
es
printf(%s, st );

ab
c ] = abc;
char st[

Outpu
t

printf(%s, st );

ab
c = "comp" , s[4] =
char st[4]

Outpu
t

"uter" ;
clrscr ();
printf ("%s" , s );
Outpu
t

uterco

n-Dim Array Declaration

Multi-Dimensional Array Declaration:

<data_type> array_name1 [size1]


[size2]. . . [sizer],
array_name2 [size1] [size2]. . .
[sizer],

[sizer];

array_namen [size1] [size2]. . .

For example the declaration:

int no[3] [4];


0,0

0,1 0,2 0,3 1,0 1,1 1,2 1,3 2,0 2,1 2,2
Creates
an array of 3 x 4 = 12 consecutive

2,3

int numbers[3]
[5]

Organization of a 3 5 element array


in memory

Read marks in 3 subjects of 10 students in a


class. Display the total and average marks
of each student.

int marks[10][3], sub, stud;


/*
Declaration */
/* Reading */
for( stud = 0; stud < 10; stud ++)
{
printf(Enter Marks for sudent-%d \n ,
stud +1);
for( sub = 0; sub < 3; sub ++)
{
scanf( %d, &marks [stud] [sub] );

Initializing Multidimensional Arrays


Lets first consider how you initialize a twodimensional array. The basic structure of the
declaration, with initialization, is the same as
youve seen before, except that you can
optionally put all the initial values for each row
between braces {}:
int numbers[3][4] = {
{ 10, 20, 30, 40 },
row */
{ 15, 25, 35, 45 },

/* Values for first


/* Values for

int numbers[2][3][4] = {
{ /* First block of 3 rows */
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 }
},
{ /* Second block of 3 rows */
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 47, 48, 49, 50 }
}
};

char text [3] [5] = {


{ a , b , c , d , \0 },
{ x , y , z , \0 },
{ m , n , \0 }
};
Is equivalent to
char text [3] [5] = { abcd , xyz ,
mn };

a b c d \ x y z \
0
0

mn \
0

Unused

Unsized double
dimensional array

int num[ ][6] = {


{1 , 2 , 3 , 4} ,
{11 , 22 , 33 , 44 },
{5 , 6 , 7 , 8 , 9 , 10}
};
1st dimension size
automatically set
to number of
grouping
i.e. 3

Examples Sized and Unsized


double dimensional array
int first[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
int second[3][4] = {{0, 1, 2, 3}, {4, 5, 6,
7}, {8, 9,10,11}}; /* a clearer definition
than the first */
int third[][5] = {0,1,2,3,4};
/* third[] only has one index of 1 */
int fourth[][6] = {0,1,2,3,4,5,6,7,8,9,10,11};

You might also like