Array
Array
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
6
Declaring Array
double balance[10];
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
10
Accessing Array Elements
0 1 2 3 4
balance 1000.00 2.0 3.4 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] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Example: MonthlyRainfall
Problem: using month mean rainfall (in mm)
0 30
Rainfall Table 1 40
• input month 2 45
• output mean rainfall 3 95
4 130
for that month
5 220
6 210
7 185
8 135
9 80
10 40
11 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 };
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 };
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
int main()
{
int data[NMONTHS];
int month;
... rainio1.c
20
Example (cont): IORainfall-1
#include <stdio.h>
#define NMONTHS 12
int main()
{
int data[NMONTHS];
int 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");
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");
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
26
Example (cont): IORainfall-1 (v.3)
#include <stdio.h>
#define NMONTHS 12
27
Example (cont): IORainfall-2 (v.3)
printf("\n");
}
rainio3.c
28
Example (cont): IORainfall-3 (v.3)
#include <stdio.h>
#define NMONTHS 12
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]); } rainio3.c
printf("\n");
} 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 “multi-dimensional”
because you need to specify several ordinates to
locate an actual element
32
Example: YearlyRainfall
month
0 1 2 3 4 5 6 7 8 9 10 11
0 30 40 75 95 130 220 210 185 135 80 40 45
1 25 25 80 75 115 270 200 165 85 5 10 0
year
t year;
t month;
t rainfall;
(rainfall < 0)
se
turn 0; yearly1.c
35
Example (cont): YearlyRainfall-1
#define NYEARS 5
#define NMONTHS 12
t year;
t month;
t rainfall;
(rainfall < 0)
se
turn 0;
yearly1.c
38
Example (cont): YearlyRainfall-2
ain()
t year;
t month;
t rainfall;
(rainfall < 0)
se
turn 0;
yearly1.c
39
Example (cont): YearlyRainfall-2
ain()
t year;
t month;
t rainfall;
(rainfall < 0)
se
turn 0;
yearly1.c
40
Passing Two-Dimensional Arrays to
Functions
41
Example 2: 2-D Array-1
#include <stdio.h>
#define NROWS 3
#define NCOLS 5
int main()
{
float table[NROWS][NCOLS] = {{0}};
twod2.c
42
Example 2 (cont): 2-D Array-1
#include <stdio.h>
#define NROWS 3
#define NCOLS 5
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);
48
Example 2 (cont): 2-D Array-3
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 programmer’s 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]