Arrays
Arrays
1
ARRAY
Many applications require processing of multiple data
items that have common characteristics
In mathematics, we often express such groups of data items
in indexed form:
x1, x2, x3, …, xn
Array is a data structure which can represent a
collection of data items which have the same data type
(float/int/char/…)
2
EXAMPLE: PRINTING NUMBERS IN
REVERSE
4 numbers
3 numbers
int a, b, c, d;
int a, b, c; scanf(“%d”, &a);
scanf(“%d”, &a); scanf(“%d”, &b);
scanf(“%d”, &b); scanf(“%d”, &c);
scanf(“%d”, &c); scanf(“%d”, &d);
printf(“%d ”, c); printf(“%d ”, d);
printf(“%d ”, b); printf(“%d ”, c);
printf(“%d \n”, a); printf(“%d ”, b);
printf(“%d \n”, a);
3
THE PROBLEM
Suppose we have 10 numbers to handle
Or 20
Or 100
Where do we store the numbers ? Use 100 variables ??
How to tackle this problem?
Solution:
Use arrays
4
PRINTING IN REVERSE USING ARRAYS
int main()
{
int n, A[100], i;
printf(“How many numbers to read?” );
scanf(“%d”, &n); Expected value of n is between 1 to 100
Execute the loop starting from 0 to n-1 with
for (i = 0; i < n; ++i) step size 1
scanf(“%d”, &A[i]); Store n numbers in A[0]…A[n-1]
for (i = n 1; i >= 0; i) Execute the loop starting from n-1 to 0 with
step size 1
printf(“%d ”, A[i]);
printf(“\n”);
return 0;
}
5
USING ARRAYS
All the data items constituting the group
share the same name
int x[10];
Individual elements are accessed by
specifying the index
X is a 10-element one 6
dimensional array
A FIRST EXAMPLE
int main()
{ “data refers to a block of 10
int i; integer variables, data[0], data[1],
int data[10]; …, data[9]
for (i=0; i<10; i++)
data[i]= i;
i=0;
while (i<10)
{
printf("Data[%d] = %d\n", i, data[i]);
i++;
}
return 0;
} 7
THE RESULT
Array size should be a constant
int main()
Output
{
int i; Data[0] = 0
int data[10]; Data[1] = 1
for (i=0; i<10; i++) Data[2] = 2
data[i]= i; Data[3] = 3
i=0;
Data[4] = 4
while (i<10)
{ Data[5] = 5
Like variables, the arrays used in a program must be
declared before they are used
General syntax:
storageclass type arrayname [size];
storageclass refers to the storage class of the array.
type specifies the type of element that will be
contained in the array (int, float, char, etc.)
size is an integer constant which indicates the
maximum number of elements that can be stored
inside the array
Examples: marks is an array that can store a
maximum of 5 integers
10
ACCESSING ARRAY ELEMENTS
A particular element of the array can be
accessed by specifying two things:
Name of the array
Index (relative position) of the element in the array
In C, the index of an array starts from zero
Example:
An array is defined as int x[10];
The first element of the array x can be accessed as x[0],
fourth element as x[3], tenth element as x[9], etc.
11
CONTD.
The array index must evaluate to an integer between 0 and
n1 where n is the maximum number of elements possible in
the array
a[x+2] = 25;
b[3*xy] = a[10x] + 5;
Remember that each array element is a variable in itself, and
can be used anywhere a variable can be used (in expressions,
assignments, conditions,…)
12
HOW IS AN ARRAY STORED IN
MEMORY?
Starting from a given memory location, the
successive array elements are allocated space
in consecutive memory locations
Array a
x: starting address of the array in memory
k: number of bytes allocated per array element
a[i] is allocated memory location at address x + i*k
13
STORAGE Output
&Data[0] = 3221224480
&Data[1] = 3221224484
15
HOW TO READ THE ELEMENTS OF
AN ARRAY?
By reading them one element at a time
for (j=0; j<25; j++)
scanf (“%f”, &a[j]);
The ampersand (&) is necessary
The elements can be entered all in one
line or in different lines
16
A WARNING
In C, while accessing array elements,
array bounds are not checked
Example:
int marks[5];
:
:
marks[8] = 75;
The above assignment would not necessarily cause an
error
Rather, it may result in unpredictable program
results
17
READING INTO AN ARRAY
#define MAX_SIZE 100
int main()
{
int i, size; Output
float marks[MAX_SIZE];
float total; 4
scanf("%d",&size); 2.5
for (i=0, total=0; i<size; i++)
{ 3.5
scanf("%f",&marks[i]);
4.5
total = total + marks[i];
} 5
printf("Total = %f \n Avg = %f\n", total, total/size);
return 0;
Total = 15.500000
} Avg = 3.875000
18
HOW TO PRINT THE ELEMENTS OF
AN ARRAY?
By printing them one element at a time
for (j=0; j<25; j++)
printf (“\n %f”, a[j]);
The elements are printed one per line
printf (“\n”);
for (j=0; j<25; j++)
printf (“ %f”, a[j]);
The elements are printed all in one line (starting with
a new line)
19
HOW TO COPY THE ELEMENTS OF ONE
ARRAY TO ANOTHER?
By copying individual elements
for (j=0; j<25; j++)
a[j] = b[j];
The element assignments will follow the rules of assignment
expressions
Destination array must have sufficient size
20
EXAMPLE 1: FIND THE MINIMUM OF A SET OF 10
NUMBERS
#define size 10
int main()
{
int a[size], i, min;
min = a[0];
for (i=1; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min); 21
return 0;
}
EXAMPLE 2: COMPUTING GPA
24
int main() {
int A[100], n, k, i, mid, low, high;
scanf(“%d %d”, &n, &k);
for (i=0; i<n; ++i) scanf(“%d”, &A[i]);
low = 0; high = n – 1; mid = low + (high – low)/2;
while (high >= low) {
printf(“low = %d, high = %d, mid = %d, A[%d] = %d\n”, low, high,
mid, mid, A[mid]);
if (A[mid] == k) {
printf(“%d is found\n”, k);
break;
}
if (k < A[mid]) high = mid – 1;
else low = mid + 1;
mid = low + (high – low)/2;
}
if (high < low) printf(“%d is not found\n”, k);
return 0; 25
}
Sample Input Output
n
k
A[]
8 21
9 11 14 17 19 20 23 27
low = 0, high = 7, mid = 3, A[3] = 17
low = 4, high = 7, mid = 5, A[5] = 20
low = 6, high = 7, mid = 6, A[6] = 23
21 is not found
8 14
9 11 14 17 19 20 23 27
low = 0, high = 7, mid = 3, A[3] = 17
low = 0, high = 2, mid = 1, A[1] = 11
low = 2, high = 2, mid = 2, A[2] = 1426
14 is found
THINGS YOU CANNOT DO WITH
ARRAYS
You cannot
use = to assign one array variable to another
a = b; /* a and b are arrays */
use == to directly compare array variables
if (a = = b) ………..
directly scanf or printf arrays*
printf (“……”, a);
*Note:You can use scanf and printf on
some character arrays
27
PASSING ARRAYS TO FUNCTIONS
Array element can be passed to functions as
ordinary arguments
IsFactor (x[i], x[0])
sin (x[5])
28
PASSING ENTIRE ARRAY TO A
FUNCTION
An array name can be used as an argument to a
function
Permits the entire array to be passed to the
function
The way it is passed differs from that for ordinary
variables
Rules:
The array name must appear by itself as
argument, without brackets or subscripts
The corresponding formal argument is written in
the same manner 29
Declared by writing the array name with a pair
of empty brackets
WHOLE ARRAY AS PARAMETERS
#define ASIZE 5
float average (int B[ ]) Only Array Name/address passed.
{ [ ] mentioned to indicate that
int i, total=0; is an array.
for (i=0; i<ASIZE; i++)
total = total + B[i];
return ((float) total / (float) ASIZE);
}
void main ( ) {
int x[ASIZE] = {10, 20, 30, 40, 50};
float x_avg;
x_avg = average (x) ;
} 30
void main () {
int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3];
VectorSum (x, y, z, 3) ;
PrintVector (z, 3) ; 32
}
THE ACTUAL MECHANISM
When an array is passed to a function, the
values of the array elements are not passed to
the function
The array name is interpreted as the address
of the first array element
The formal argument therefore becomes a
pointer to the first array element
When an array element is accessed inside the
function, the address is calculated using the
formula stated before
Changes made inside the function are thus
also reflected in the calling program 33
CONTD.
Passing parameters in this way is called
callbyreference
Basically what does it mean?
If a function changes the values of array
elements, then these changes will be made
to the original array that is passed to the
function
This does not apply when an individual
element is passed as an argument
34
TWO DIMENSIONAL ARRAYS
We have seen that an array variable can store a
list of values
Many applications require us to store a table of
values
36
DECLARING 2D ARRAYS
General form:
storageclass type array_name [row_size][column_size];
Examples:
int marks[4][5];
float sales[12][25];
double matrix[100][100];
37
INITIALIZING 2D ARRAYS
int a[2][3] = {1,2,3,4,5,6};
int a[2][3] = {{1,2,3}, {4,5,6}};
int a[][3] = {{1,2,3}, {4,5,6}};
All of the above will give the 2x3 array
1 2 3
4 5 6
38
ACCESSING ELEMENTS OF A 2D
ARRAY
Similar to that for 1d array, but use two indices
First indicates row, second indicates column
Both the indices should be expressions which evaluate
to integer values (within range of the sizes mentioned
in the array declaration)
Examples:
x[m][n] = 0;
c[i][k] += a[i][j] * b[j][k];
a = sqrt (a[j*3][k]);
39
EXAMPLE
int a[3][5];
40
HOW A 2D ARRAY IS STORED IN
MEMORY?
Starting from a given memory location, the elements are
stored rowwise in consecutive memory locations (rowmajor
order)
• x: starting address of the array in memory
• c: number of columns
• k: number of bytes allocated per array element
a[i][j] is allocated memory location at
address x + (i * c + j) * k
a[0][0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]
43
HOW TO PRINT THE ELEMENTS OF
A 2D ARRAY?
By printing them one element at a time
for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
printf (“\n %f”, a[i][j]);
The elements are printed one per line
for (i=0; i<nrow; i++)
for (j=0; j<ncol; j++)
printf (“%f”, a[i][j]);
The elements are all printed on the same line
44
CONTD.
for (i=0; i<nrow; i++)
{
printf (“\n”);
for (j=0; j<ncol; j++)
printf (“%f ”, a[i][j]);
}
The elements are printed nicely in matrix form
45
EXAMPLE: MATRIX ADDITION
int main()
{ for (p=0; p<m; p++)
int a[100][100], b[100][100], for (q=0; q<n; q++)
c[100][100], p, q, m, n; c[p][q] = a[p][q] + b[p][q];
A multidimensional array can be written as
storageclass datatype array_name [expression1]
[expression2] … [expression n] ;
49
MULTIDIMENSIONAL ARRAYS
Examples:
int t[10][20][30] = {
{ /* table 1 */
{1, 2, 3, 4}, /* row 1 */
{5, 6, 7, 8}, /* row 2 */
{9, 10, 11, 12} /* row 3 */
},
{ /* table 2 */
{21, 22, 23, 24}, /* row 1 */
{25, 26, 27, 28}, /* row 2 */
{29, 30, 31, 32} /* row 3 */
}
}
This is an array of 10 tables, each having 20 rows and 30 50
columns. The rest of the elements will be assigned to 0.
Arrays in Multifile programs
file1.c file2.c
int c[] = {1,2,3}; /* External extern int c[] ;/* External array
array definition */ declaration */
Array sizes are not specified in file1.c as the arrays are initialised
Array sizes are not specified in file2.c as they have already been specified.
51
END
52
MORE ON ARRAY ADDRESSES
int main()
{
int a[3][5];
printf("a = %u\n", a);
Output
printf("&a[0][0] = %u\n", &a[0][0]);
printf("&a[2][3] = %u\n", &a[2][3]); a = 3221224480
printf("a[2]+3 = %u\n", a[2]+3); &a[0][0] = 3221224480
printf("*(a+2)+3 = %u\n", *(a+2)+3); &a[2][3] = 3221224532
a[2]+3 = 3221224532
printf("*(a+2) = %u\n", *(a+2)); *(a+2)+3 = 3221224532
printf("a[2] = %u\n", a[2]); *(a+2) = 3221224520
printf("&a[2][0] = %u\n", &a[2][0]); a[2] = 3221224520
&a[2][0] = 3221224520
printf("(a+2) = %u\n", (a+2)); (a+2) = 3221224520
printf("&a[2] = %u\n", &a[2]); &a[2] = 3221224520
53
return 0;
}