Vous êtes sur la page 1sur 17

What is an Array?

• An array is collection of variables of a certain type,


placed contiguously (alongside) in memory.
• An array is simply a number of memory locations, each
of which can store the same data type and which can be
referenced through the same variable name.
• An array is a collective name given to a group of
similar quantities & the similar quantities could be
marks of 100 students, or salaries of 300 employee or
ages of 50 employees.
• These similar elements could be all integers, or all
floats or all characters etc.

Declaration of an Array
• Standard array declaration is as follows:
type var_name[size];
• For example:
int temp[7];
Here the int specifies the type of variable, and temp is
the name of array.
[7] tells how many variables of type int will be in the
array.
Each separate variable in array is called an “element”
More Examples:
double height[10];
float width[20];

1
Arrays in Memory
• In C Language, arrays starts at position 0.
• The elements of the array occupy adjacent locations
in memory
• Example: int temp[10];
• The k-th element of array A is specified by A[k-1]
(0 based)
Subscripts: the numbers in brackets following the
array name are called subscript and are used to refer to
individual elements of array.

0 1 2 3 4 5 6 7 8 9 …

int temp[10]
10 elements

• This number has a different meaning when referring


to an array element than it does when defining array;
when the number in brackets is size of array.
• When referring to an array element, this number
specifies the element’s position in array
• All array elements are numbered, starting at 0, the
element of array with number 2 would be referred as:
temp[2]
• This is not the second element but the third, as
numbering starts from 0, thus the last array element
is one less than the size of array.
0 1 2 3 4 5 6 7 8 9 …

temp[2]
largest element one less than size of
array

2
Using Arrays

int a[5], i; int a[5];


for(i=0; i<5; i++) a[0] = 2;
a[1] = 4;
{
a[2] = 6;
a[i] = i;
a[3] = 8;
}
a[4] = 10;

0 1 2 3 4 2 4 6 8 10

a[0] a[1] a[2] a[3] a[4] a[0] a[1] a[2] a[3] a[4]

• Suppose you wanted to find the average temperature for a


particular week.
void main ( void )
{
int temper [ 7 ] ; /*array definition*/
int day , sum ;
for ( day = 0; day < 7; day ++ )
{ printf (“Enter Temperature for day %d : “, day ) ;
scanf ( “ %d “, &temper [ day ] ) ;
}
sum = 0 ;
for ( day = 0; day < 7; day ++ )
sum + = temper [ day ] ;
printf ( “ Average is %d “, sum / 7 );
}

3
• The program reads in 7 temperatures, stores them in
an array and then to calculate average temperature,
reads them back out of the array, adding them
together, dividing by 7.
Output:
Enter temperature for day0: 74
Enter temperature for day1: 76
Enter temperature for day2: 77
Enter temperature for day3: 77
Enter temperature for day4: 64
Enter temperature for day5: 66
Enter temperature for day6: 69
Average is 71.

• Entering data into Array:


– For loop causes the process of asking for and receiving a
temperature from the user to be repeated 7 times.
for ( day = 0; day < 7; day ++ )
{ printf (“Enter Temperature for day %d : “, day ) ;
scanf ( “ %d “, &temper [ day ] ) ;
}
• Entering data into Array:
– For loop is much the same, but now the body of loop causes
each day’s temperature to be added to a running total sum.
When all of them are added up, the result is divided by 7
sum = 0 ;
for ( day = 0; day < 7; day ++ )
sum + = temper [ day ] ;
printf ( “ Average is %d “, sum / 7 );

4
Using Different Variable Type
void main (void)
{
float temper [ 7 ] , sum;
int day ;
for ( day = 0 ; day < 7 ; day + + )
{
printf ( “Enter Temperature for day %d: “, day ) ;
scanf ( “ %f “, &temper [ day ] ) ;
}
sum = 0.0 ;
for ( day = 0; day < 7; day ++ )
sum + = temper [ day ] ;
printf ( “ Average is %.1f “, sum / 7.0 );
}

Reading in an Unknown Number of Elements


void main (void)
{ float temper [ 40 ] , sum = 0.0;
int num , day = 0;
do
{
printf (“Enter Temperature for day %d: “, day ) ;
scanf (“ %f “, &temper [ day ] ) ;
}
while ( temper [ day + + ] > 0 ) ;
num = day - 1 ; /* no of temps entered */
for ( day = 0 ; day < num ; day + + )
sum + = temper [ day ] ;
printf (“ Average is %.1f “, sum / num ) ;
getch ( );
}

5
• For loop is replaced with a do while loop, which
repeatedly asks the user to enter a temperature and store
the responses in the array temper, until a temperature
of zero or less is entered.
• When the last item has been typed, the variable day will
have reached a value 1 greater than the total number of
items entered because it counts 0 (or –ve number)
which the user entered to terminate the input.
• Thus to find the number of items entered, num we
subtract 1 from day.
• num is then used as limit in the second for loop, which
adds up temperatures, and its also used as divisor of the
resulting sum.

Bound Checking
• In the previous program we have made the size of the
array to be 40. But a user decided to enter 2 months
worth of data? As it turns out, there probably would be
big trouble. How?
• In C there is no check to see if the subscript used for an
array will exceed the size of array.
• Data entered with too large a subscript will simply be
placed in memory outside the array, this will lead to
unpredictable results.
• C Language does not warn you when array subscripts
exceed the size of the array.

6
Bound Checking
• Solution:
– If there is the slightest possibility that the user might
enter too many items, we have to check for this
possibility.

• Now if the loop is entered with day = 40, which is 1


past the end of buffer at 39, the message “Buffer full”
is printed, and break statement takes us out of the loop
and enters the second part of the program.
• day is incremented since the while statement won’t be
executed.

Bound Checking
do
{
if ( day > = 40 ) /* beyond array end */
{
printf ( “ Buffer Size Full “ ) ;
day + + ;
break ; /* exit loop*/
}

printf ( “ Enter temperature for day %d : “, day ) ;


scanf ( “ %f “, %temper [ day ] ) ;
}
while ( temper [ day + + ] > 0 ) ;

7
Initializing Arrays
• Suppose we want to compile our program with
specific values already fixed in the array.
• This is analogous to initializing a simple variable
i.e. int marks = 45

# define LIM 5

int table [ LIM ] = { 50, 25, 10, 5,1 } ;

void main (void)


{
int count , a[5] = { 10, 20, 30, 40, 50 } ;
for (count=0; count < 5; count++)
{
printf("Value of array [%d] is = %d \n", a[count] );
}
getch( );
}

Output
Value of array[0] = 10
Value of array[1] = 20
Value of array[2] = 30
Value of array[3] = 45
Value of array[4] = 50

8
Array Size and Initialization
• There is a change in the array definition in the previous
two programs.

int table [ 5 ] = { 50, 25, 10, 5,1 } ;

static int table [ ] = { 50, 25, 10, 5,1 } ;

• If no number is supplied for the size of the array, the


compiler will very kindly count the number of items in the
initialization list and fix that as the array size.

• If the number is larger than the number of items, the extra


spaces in the array will be filled in with zeros. If the
number is too small, the compiler will complain.

Array Contents and Initialization


• If we execute an array declaration like this, what will be the
output?
void main()
{
int array[10];
printf(“Array element 3 has the value %d”,array[3]);
}
• Garbage value will be printed i.e. whatever value is sitting in
that particular part of memory before the function was called
and the array declared.
• If declared as static or external then it will be initialized with
0. so if you want the array initialized to all zero’s, but don’t
want to do yourself, make it external or static.

9
Preprocessor Directives
• Normal program statements are instructions to the
microprocessor ; Preprocessor directives are
instructions to the compiler
• Rather than being translated into machine language,
they are operated on directly by the compiler before
the compilation process even begins; hence the
name preprocessor.
• Preprocessor directives always start with a number
sign ( # )
• The directives can be placed anywhere in a
program, but are often used at the beginning of a
file, before main ( ), or before the beginning of
particular functions.

More than One Dimension


• It is also possible to have two or more dimensions of an array.
• This permits them to emulate or model multi-dimensional
objects such as graph paper or computer screen itself.
• C stores two-dimensional arrays in row-major order.
• The elements of row 0 come first, followed by the elements of
row 1, and so forth. An array with r rows would have the
following appearance:

one two
dimension dimensions

10
This program records, not one list of data as our previous programs
have, but 2 lists side-by-side. It stores the travel expenses for a no.
of secret agents who are known only by their code numbers.

# define ROWS 10 # define directive


# define COLS 2 Identifier – ROW
Text – 10
void main (void) ROW and COLS will be
{ replaced by 10 & 2 resp.
float number, expenses ;
float agents [ROWS] [COLS] ;
int index = 0, outdex ;

printf ( “Enter 3-digit Agent number , \n “ ) ;


printf ( “Travel expenses i.e. ( 007 1500.50 ) \n “ ) ;
printf ( “Enter 0 0 to quit \n “ ) ;

do */ get list of agents and expenses */


{
printf ( “ Agent’s number and expenses: “ ) ;
scanf ( “ %f %f “, &number, &expenses ) ;
agents [ index ] [ 0 ] = number ;
agents [ index ] [ 1 ] = expenses ;
}
while ( agent [ index ++ ] [ 0 ] ! = 0 ) ;

for ( outdex = 0 ; outdex < index - 1; outdex + + )


{ */ print list */
printf ( “ Agent %03.0f “, agent [ outdex ] [ 0 ] ) ;
printf ( “ Spent %7.2f. \n “, agent [ outdex ] [ 1] ) ;
}
}

11
Output:

Enter 3-digit Agent number:


Travel expenses i.e. ( 007 1500.50 ):
Enter 0 0 to quit:
Agent’s number and expenses : 101 2331.50
Agent’s number and expenses : 007 8640
Agent’s number and expenses : 901 123.25
Agent’s number and expenses : 904 500.6
Agent’s number and expenses : 0 0
Agent 101 spent 2331.50
Agent 7 spent 8640
Agent 901 spent 123.25
Agent 904 spent 500.60

• There are 2 parts to the program


– A do-while loop that gets the data from the user and stores
it in the 2-dimensional array table[ ][ ].
• Instead of getting only one piece of data each time through the
loop, we get two; placing them in the variables agents[index][0]
and agents[index][1] with the scanf() statement.

scanf ( “ %f %f “, & agents[index][0], & agents[index][1] ) ;

– A for loop that prints out the contents of the array.


• Entire array is of type float, but decimal places are not printed
in agent numbers. Reason for float data type is we want to use
dollars and cents for expenses.
• Ideal arrangement would be to have agent numbers be of type
int and expenses of type float but arrays must be of single data
type. This is an important limitation of arrays.

12
row Column 0 Column 1
0 101 2331.50
1 007 8640.00
2 901 123.25
agents [2] [0] 3 904 500.60
4
agents [4] [1]
5
6
7
8
9
agents [index] [0]

this is the row this is the column

Initializing 2-Dimensional Arrays


• The value used to initialize an array are separated by commas
and surrounded by braces.
void main (void)
{
int table [5] [2] = { {1,2}, {3,4}, {5,6}, {7,8}, {9,0} } ;
int x, y ;
printf (“Initializing a 2-Dimensional Array “) ;
for ( x = 0 ; x < 5 ; x ++ )
{ for ( y = 0 ; y < 2 ; y ++ )
printf ( “ %d \t “, table[ x ] [ y ] ) ;
}
getch ( );
}

13
• Output:
1 2 3 4 5 6 7 8 9 0

You can also write the array like this:

int table [ 5 ] [ 2 ] = { {1,2},


{3,4},
Columns {5,6},
row 0 1 {7,8},
{9,0} };
0 1 2
1 3 4
2 5 6
3 7 8
4 9 0

Initializing 3-Dimensional Arrays


int table [ 3 ] [ 2 ] [ 4 ] = { { { 1, 2, 3, 4 } ,
{ 5, 6, 7, 8 } , },
row set column { { 7, 9, 3, 2 } ,
{ 4, 6, 8, 3 } , },
{ { 7, 2, 6, 3 } ,
{ 0, 1, 9, 4 } , } , };
• This is an array of arrays. The outer array has three elements,
each of which is a 2-dimensional array of two elements, each of
which is a one-dimensional array of four numbers.
• table [2] [1] [0] = = 0 is true or not?
– First subscript is [2], as it’s the third group of 3 2D arrays.
– Second subscript is [1], its in the second of 2 1D array.
– Third subscript is [0], it’s the first element in the 1D array.
So its true.

14
Arrays as Arguments
# define MAXSIZE 20
int max ( int [ ] , int ) ;
void main (void)
{
int list [ MAXSIZE ] , num, size = 0 ;
do
{
printf ( “ Type number: “ ) ;
scanf ( “ %d “, &list [ size ] ) ;
}
while ( list [ size ++ ] ! = 0 ) ;
size--;
num = max ( list, size-1 );
printf ( “ Largest number is %d “, num ) ;
getch ( ) ;
}

Arrays as Arguments
int max ( int list [ ] , int size )
{
int dex, max ; max = list [ 0 ] ;
for (dex = 1 ; dex < size ; dex + + )
if ( max < list [ dex ] )
max = list [ dex ] ;
rerurn ( max ) ;
}
Output
Type number: 45
Type number: 1
Type number: 15
Type number: 99
Type number: 50
Type number: 0
Largest number is 99

15
Arrays as Arguments
• In the above program there is a new element here in this
statement:
num = max ( list, size-1 ) ;
• This is call to the function max ( ), which returns the largest
number. There are two arguments to the function: the first is
the array list, the second is the variable size.

• Lets imagine an integer variable num with a value 25, initialize


like this: int num = 25 ;
• Here 4 things to know about the variable:
Name of the variable: num
Value of the variable: 25
Name of the address: &num
Address of the variable: 1234 (suppose)
• Now lets see what a similar representation looks like for an
array.

“ An array is referred to by its address, which is represented by the


name of the array, used without subscripts.”
• Value of the ( First ) element of the Array: 11
• Address of the Array: 1500
• Name of element in Array: list [ 0 ]
• Name of the address of the Array: list
• Name of the address of elements in the Array: &list [ 0 ]
Why is not the address of the array called something like &list?
• consistent with the way the address of variables are named, but it would
leave the word “list”, which is not used to name anything else about the
variable
• list refers to an address if list is an array, but would refer to a value if list
were a simple variable
• Since list [ 0 ] is the first element of the array, it will have the same
address as the array itself. And since & is the address operator, &list [ 0 ]
gives the address of the first element of the array. In other words:
list = = & list [ 0 ]

16
• To summarize, to tell the compiler the address of array, we use
the name of the array, with no brackets following it.
• Thus call to the function max() passes the address of array,
represented by the word list, to the function.
• When a simple variable name is passed to the function , it takes
the value corresponding to this variable name and installs it as a
new variable in a new memory location created by the function
for that purpose.
• Since arrays can be very large, it is better to have only one copy
of array, no matter how many functions wanted to access it.
• So instead of passing the values in the array, only address of
array is passed.
• The function then uses the address to access the original array.
• So passing an array name to function does not create a new
copy of the array.

17

Vous aimerez peut-être aussi