Vous êtes sur la page 1sur 59

C ARRAY

Dr. Md. Al Mamun

ARRAY

Variable
with
Multiple
Elements

What is variable?
Data_type
Variable_name;

10

First
Element

20
30
40
50
60

Last Element

Arrays
Declaration
Initialization
Input/Output
Passing arrays to functions

Declaring Array
Data_type arrayName [ arraySize ];
This is called a single-dimensional array.
The arraySize must be an integer constant
greater than zero.
Data_type can be any valid C data type.

Declaring Array
For example, to declare a 10- element
array called balance of type double, use
this statement:
double balance[10];
Now balance is a variable array which is
sufficient to hold up-to 10 double
numbers.

Arrays
A group of contiguous memory
locations used to store a series of
related values
The array name is a pointer to the
first element
All values have the same type
Individual elements of an array are
accessed via an integer index:
array[index]
Element indices start at 0, array[0]
is the first element
9

Initializing Arrays
Arrays may be initialized with a list of
suitable values
No need to specify the number of elements
for a 1D (1-dimensional) array
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

double balance[] = {1000.0, 2.0, 3.4, 17.0,


50.0};

10

Accessing Array Elements

0
1000.00
3
4
balance

2.0

1
3.4

2
17.00

50.00

Accessing Array Elements


An element is accessed by indexing
the array name. This is done by placing
the index of the element within square
brackets after the name of the array.
balance[0]=1000.00;
balance[1]=2.00;
balance[2]=3.4;
balance[3]=17.00;
balance[4]=50.00;

double salary = balance[0];

#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i +
100 */

}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}

Element[0]
Element[1]
Element[2]
Element[3]
Element[4]
Element[5]
Element[6]
Element[7]
Element[8]
Element[9]

=
=
=
=
=
=
=
=
=
=

100
101
102
103
104
105
106
107
108
109

Example: MonthlyRainfall
Problem: using
Rainfall Table
input month
output mean
rainfall for that
month

month
0
1
2
3
4
5
6
7
8
9
10
11

mean rainfall (in mm)


30
40
45
95
130
220
210
185
135
80
40
45
Rainfall Table
16

Example (cont): MonthlyRainfall (v.1)


#include <stdio.h>
int main()
{
int
month;
int
table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };
printf("Enter month: ");
scanf("%d", &month);
printf("Average rainfall: %d mm.\n", table[month-1]);
return 0;
}

rainfall1
.c
17

Example (cont): MonthlyRainfall (v.1)


#include <stdio.h>
int main()
{
int
month;
int
table[12] = { 30, 40, 45, 95, 130, 220,
210, 185, 135, 80, 40, 45 };
printf("Enter month: ");
scanf("%d", &month);
printf("Average rainfall: %d mm.\n", table[month-1]);
return 0;
}

rainfall1
.c
18

Input / Output of Arrays


Library functions printf() and scanf()
do not know about arrays
So we have to do I/O
ourselves

19

Example: IORainfall-1
#include <stdio.h>
#define NMONTHS 12
/* Store and print rainfall */
int main()
{
int data[NMONTHS];
int month;
for ( month=0; month < NMONTHS; month++ )
{
scanf("%d", &data[month] );
}
...

rainio1.c
20

Example (cont): IORainfall-1


#include <stdio.h>
#define NMONTHS 12
/* Store and print rainfall */
int main()
{
int data[NMONTHS];
int month;
for ( month=0; month < NMONTHS; month++ )
{
scanf("%d", &data[month] );
}
...

rainio1.c
21

Example (cont): IORainfall-2 (v.1)


#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%d ", data[month] );
}
printf("\n");
/* Print from December to January */
for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%d ", data[month] );
}
printf("\n");
rainio1.c
return 0;
}

22

Example (cont): IORainfall-2 (v.1)


#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%d ", data[month] );
}
printf("\n");
/* Print from December to January */
for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%d ", data[month] );
}
printf("\n");
return 0;
}
rainio1.c
23

Example (cont): IORainfall-2 (v.2)


#include <stdio.h>
#define NMONTHS 12
...
/* Print from January to December */
for ( month=0; month < NMONTHS; month++ )
{
printf( "%5d , data[month] );
}
printf("\n");
/* Print from December to January */
for ( month = NMONTHS - 1; month >= 0; month-- )
{
printf( "%5d , data[month] );
}
printf("\n");
}

return 0;

rainio2.c
24

Handling Indices
Arrays have a fixed size
There is no built-in way of checking
if the supplied index is within range
We must check for valid indices
ourselves

25

Passing Arrays to Functions


The array is passed
as an array of unspecified size (int
array[])
OR
as a pointer (int *array)

Changes to the array within the


function affect the original array
26

Example (cont): IORainfall-1


(v.3)
#include <stdio.h>
#define NMONTHS 12
void loadRain ( int arrayPtr[] )
{
int month;

for (month=0; month < NMONTHS; month++)


{
scanf("%d", &arrayPtr[month]);
}
rainio3.c

27

Example (cont): IORainfall-2 (v.3)


void printRain ( const int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{
printf("%5d", arrayPtr[month]);
}
}

printf("\n");
rainio3.c

28

Example (cont): IORainfall-3 (v.3)


#include <stdio.h>
#define NMONTHS 12
void loadRain ( int arrayPtr[] );
void printRain ( const int arrayPtr[] );
/* Store and print rainfall */
int main()
{
int data[NMONTHS];
loadRain(data);
printRain(data);
}

return 0;
rainio3.c

29

Example: IORainfall -- v.3 (cont)


#include <stdio.h>
#define NMONTHS 12
void loadRain ( int arrayPtr[] );
void printRain ( const int arrayPtr[] );
/* Store and print rainfall */
int main()
{
int data[NMONTHS];
loadRain(data);
printRain(data);
return 0;
}
/* Read in rainfall for each month*/
void loadRain ( int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{ scanf("%d", &arrayPtr[month]); }
}
/* Print rainfall for each month*/
void printRain ( const int arrayPtr[] )
{
int month;
for (month=0; month < NMONTHS; month++)
{ printf("%5d", arrayPtr[month]); }
printf("\n");
}

rainio3.c
30

Topics
Two-dimensional arrays
Passing two-dimensional arrays to
functions

31

Two-dimensional Arrays
Each element of an array is like a single item
of a particular type
But an array itself is an item of a particular
type
So, an array element could be another
array
An array-of-arrays is called multidimensional because you need to specify
several ordinates to locate an actual element

32

Example: YearlyRainfall

year

month

0
1
2
3
4

0
30
25
35
30
30

1
40
25
45
40
35

2
75
80
90
70
30

3
95
75
80
70
90

4
130
115
100
90
150

5
220
270
205
180
230

6
210
200
135
180
305

7
185
165
140
210
295

8
135
85
170
145
60

9
80
5
75
35
95

10
40
10
60
85
80

11
45
0
95
80
30

Average Yearly Rainfall (in mm)

Problem: using the Yearly Rainfall


table
input month and year
output mean rainfall for that month

33

Example (cont): YearlyRainfall-1


#define
#define

NYEARS
NMONTHS

5
12

int lookup(int year, int month)


{
int table[NYEARS][NMONTHS] =
{
{30,40,75,95,130,220,210,185,135,80,40,45},
{25,25,80,75,115,270,200,165, 85, 5,10, 0},
{35,45,90,80,100,205,135,140,170,75,60,95},
{30,40,70,70, 90,180,180,210,145,35,85,80},
{30,35,30,90,150,230,305,295, 60,95,80,30}
};

if ((0 <=
(0 <=
{
return
}
else
{
return
}

year) && (year < NYEARS) &&


month) && (month < NMONTHS))
table[year][month];

-1;

yearly1.
c
34

Example (cont): YearlyRainfall-2


int main()
{
int
year;
int
month;
int
rainfall;
printf("Enter year and month: ");
scanf("%d %d", &year, &month);
rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;
yearly1.

c
35

Example (cont): YearlyRainfall-1


#define
#define

NYEARS
NMONTHS

5
12

int lookup(int year, int month)


{
int table[NYEARS][NMONTHS] =
{
{30,40,75,95,130,220,210,185,135,80,40,45},
{25,25,80,75,115,270,200,165, 85, 5,10, 0},
{35,45,90,80,100,205,135,140,170,75,60,95},
{30,40,70,70, 90,180,180,210,145,35,85,80},
{30,35,30,90,150,230,305,295, 60,95,80,30}
};

if ((0 <=
(0 <=
{
return
}
else
{
return
}

year) && (year < NYEARS) &&


month) && (month < NMONTHS))
table[year][month];

-1;

yearly1.
c
36

Example (cont) : YearlyRainfall-1


#define
#define

NYEARS
NMONTHS

5
12

int lookup(int year, int month)


{
int table[NYEARS][NMONTHS] =
{
{30,40,75,95,130,220,210,185,135,80,40,45},
{25,25,80,75,115,270,200,165, 85, 5,10, 0},
{35,45,90,80,100,205,135,140,170,75,60,95},
{30,40,70,70, 90,180,180,210,145,35,85,80},
{30,35,30,90,150,230,305,295, 60,95,80,30}
};

if ((0 <=
(0 <=
{
return
}
else
{
return
}

year) && (year < NYEARS) &&


month) && (month < NMONTHS))
table[year][month];

-1;

yearly1.
c
37

Example (cont): YearlyRainfall-2


int main()
{
int
year;
int
month;
int
rainfall;
printf("Enter year and month: ");
scanf("%d %d", &year, &month);
rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;

yearly1.
c

38

Example (cont): YearlyRainfall-2


int main()
{
int
year;
int
month;
int
rainfall;
printf("Enter year and month: ");
scanf("%d %d", &year, &month);
rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;

yearly1.
c

39

Example (cont): YearlyRainfall-2


int main()
{
int
year;
int
month;
int
rainfall;
printf("Enter year and month: ");
scanf("%d %d", &year, &month);
rainfall = lookup(year - 1, month - 1);

if (rainfall < 0)
{
printf("Year must be between 1 and %d,\n", NYEARS);
printf("and month must be between 1 and %d.\n", NMONTHS);
}
else
{
printf("Rainfall for year %d, month %d is %d mm.\n",
year, month, rainfall);
}
return 0;

yearly1.
c

40

Passing Two-Dimensional
Arrays to Functions
In the function definition, the size of
the array needs to be specified
Any changes to array elements
within the function affect the
``original array elements

41

Example 2: 2-D Array-1


#include <stdio.h>
#define
#define

NROWS
NCOLS

3
5

void inputEntry(float table[][NCOLS]);


void printTable(float table[NROWS][NCOLS]);
int main()
{
float table[NROWS][NCOLS] = {{0}};

twod2.c
42

Example 2 (cont): 2-D Array-1


#include <stdio.h>
#define
#define

NROWS
NCOLS

3
5

void inputEntry(float table[][NCOLS]);


void printTable(float table[NROWS][NCOLS]);
int main()
{
float table[NROWS][NCOLS] = {{0}};
printTable(table);

while (1)
{
inputEntry(table);
printTable(table);
}
return 0;

twod2.c
43

Example 2 (cont): 2-D Array-2


/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[NROWS][NCOLS] )
{
int row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
twod2.c
44

Example 2 (cont): 2-D Array-2


/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[][NCOLS] )
{
int
row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
twod2.c

45

Example 2 (cont): 2-D Array-2


/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[][NCOLS] )
{
int
row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
twod2.c
46

Example 2 (cont): 2-D Array-2


/* Reads in a location in the table and the value of
one item to be put in the table */
void inputEntry ( float table[][NCOLS] )
{
int
row, column;
printf("Enter row and column number: ");
scanf("%d %d", &row, &column);

if ((0 <= row && row < NROWS) &&


(0 <= column && column < NCOLS))
{
printf("Enter value: ");
scanf("%f", &table[row][column]);
}
else
{
printf("Invalid entry location. No change.\n");
}
twod2.c
47

Example 2 (cont): 2-D Array-3


/* Prints the table page-by-page, and each page
row-by-row */
void printTable ( float table[NROWS][NCOLS] )
{
int
row, column;
for (row=0; row < NROWS; row++)
{
for (column=0; column < NCOLS; column++)
{
printf("%10.2f", table[row][column]);
}
printf("\n");
}
}
twod2.c

48

Example 2 (cont): 2-D Array-3


/* Prints the table page-by-page, and each page
row-by-row */
void printTable ( float table[NROWS][NCOLS] )
{
int
row, column;
for (row=0; row < NROWS; row++)
{
for (column=0; column < NCOLS; column++)
{
printf("%10.2f", table[row][column]);
}
printf("\n");
}
}
twod2.c

49

QUESTIONS?

Array-Bounds Checking
C, unlike many languages, does NOT check array
bounds subscripts during:
Compilation (some C compilers will check literals)
Runtime (bounds are never checked)

If you access off the ends of any array, it will


calculate the address it expects the data to be at,
and then attempts to use it anyways
may get something
may get a memory exception (segmentation fault, bus
error, core dump error)

It is the programmers responsibility to ensure that


their programs are correctly written and debugged!
This does have some advantages but it does give you
all the rope you need to hang yourself!

Initializing Arrays
Initialization of arrays can be done by a
comma separated list following its definition.
For example:
int array [4] = { 100, 200, 300, 400 };

This is equivalent to:


int array [4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;

You can also let the compiler figure out the


array size for you:
int array[] = { 100, 200, 300, 400};

A Simple Example
#include <stdio.h>
int main() {
float expenses[12]={10.3, 9, 7.5, 4.3, 10.5, 7.5, 7.5, 8, 9.9,
10.2, 11.5, 7.8};
int count,month;
float total;
for (month=0, total=0.0; month < 12; month++)
{
total+=expenses[month];
}
for (count=0; count < 12; count++)
printf ("Month %d = %.2f K$\n", count+1,
expenses[count]);
printf("Total = %.2f K$, Average = %.2f K$\n", total,
total/12);
return 0;
}

Multidimensional Arrays
Arrays in C can have virtually as many
dimensions as you want.
Definition is accomplished by adding
additional subscripts when it is defined.
For example:
int a [4] [3] ;
defines a two dimensional array
a is an array of int[3];

In memory:

a[0][0]a[0][1]a[0]
[2]

a[0]

a[1]

a[2]

a[3]

Initializing Multidimensional
The
following initializes a[4][3]:
Arrays
int a[4] [3] = { {1, 2, 3} , { 4, 5, 6} , {7, 8, 9} ,
{10, 11, 12} };

Also can be done by:


int a[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12 };
is equivalent to
a[0][0]
a[0][1]
a[0][2]
a[1][0]
...
a[3][2]

=
=
=
=

1;
2;
3;
4;

= 12;

An Example
#include <stdio.h>
#include <stdlib.h>
int main () {
int random1[8][8];
int a, b;
for (a = 0; a < 8; a++)
for (b = 0; b < 8; b++)
random1[a][b] = rand()%2;
for (a = 0; a < 8; a++)
{
for (b = 0; b < 8; b++)
printf ("%c " , random1[a][b] ? 'x' :
'o');
printf("\n");
}
return 0;
}

The value of the array


name

#include <stdio.h>
int main(){
int i;
int a[3] = { 1, 2, 3 };
printf( "a ? %d\n", a);
printf( "a[0] ? %d\na[1] ?
%d\na[2]
? %d\n", a[0], a[1],
a[2]);
printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n", &a[0],
&a[1], &a[2]);
printf( "\na[0] <- 4 \n");
a[0] = 4;
printf( "a ? %d\n", a);
printf( "a[0] ? %d\na[1] ?
%d\na[2]
? %d\n", a[0], a[1],
a[2]);
printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n\n", &a[0],
&a[1], &a[2]);

for (i=0; i<3; i++) {


printf( "a[%d] <- ",i);
scanf( "%d", &a[i]);
}
printf( "a ? %d\n", a);
printf( "a[0] ? %d\na[1] ?
%d\na[2]
? %d\n", a[0],
a[1], a[2]);
printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n", &a[0],
&a[1], &a[2]);

When the array name is


used alone, its value is the
address of the array (a
pointer to its address).
&a has no meaning if used
in this program.

Arrays as Function
In this program, the array
addresses
(i.e., the values
Parameters
of the array names), are

passed to the function


inc_array().
This does not conflict with
the rule that parameters
are passed by values.
void inc_array(int a[ ], int
size)
{
int i;
for(i=0;i<size;i++)
{
a[i]++;
}
}

void inc_array(int a[ ],int size);


main()
{
int test[3]={1,2,3};
int ary[4]={1,2,3,4};
int i;
inc_array(test,3);
for(i=0;i<3;i++)
printf("%d\n",test[i]);
inc_array(ary,4);
for(i=0;i<4;i++)
printf("%d\n",ary[i]);
return 0;
}

An
Example
-Sorting
int main()
void mysort(int a[ ],int size)
{

int i;
int tab[10] =
{3,6,3,5,9,2,4,5,6,0};

int i,j,x;
for(i=0; i<size; i++)
{
for(j=i; j>0; j--)
{
if(a[ j ] < a[ j-1])
{ /* Change the order of
a[ j ] and a[ j-1] */
x=a[ j ];a[ j ]=a[ j-1]; a[j1]=x;
}
}
}

for(i=0;i<10;i++)
printf("%d ",tab[i]);
printf("\n");
mysort(tab,10);
for(i=0;i<10;i++)
printf("%d ",tab[i]);

printf("\n");
return 0;
}

Vous aimerez peut-être aussi