Lecture 8
Lecture 8
Arrays
Lecture-8
Outline
• Introduction
• Arrays
• Declaring Arrays
• Using Arrays
• Multiple-Subscripted Arrays
2
Introduction
• Arrays
– An arrays is a structure of related data items
which are placed next to each other in the
memory.
3
Name of array
Arrays (Note that all
elements of this
• Array array have the
same name, c)
– Group of consecutive memory locations
– Same name and type c[0] -45
c[1] 6
c[2] 0
5
Declaring Arrays
• When declaring arrays, specify
– Name
– Type of array
– Number of elements
arrayType arrayName[ numberOfElements ];
– Examples:
int c[ 10 ];
float myArray[ 3284 ];
7
Using Arrays
• Character arrays
– String “first” is really a static array of characters
int main(void) {
double grades[SIZE] ; // array declaration
int i ;
for (i = 0; i < SIZE; ++i) // loop to read the five grades into the array
{
printf ("Enter the %d element of array : ", i ) ;
scanf ( "%lf", &grades[i] ) ;
}
printf("\n");
for (i = 0; i < SIZE; ++i) // loop to display five grades stored in the array
printf ("The %d th element of array is %f\n", i, grades[i]) ;
system("pause");
return 0;
} 10
Example 3
/* Reads data into two arrays and subtracts their corresponding elements, storing the result in
another array. */
#include<stdio.h>
#define SIZE 5
int main(void) {
int first[SIZE], second[SIZE], diff[SIZE], i;
• Not specifying the size will allow the function to be called with
any size of array.
• However, the function needs to know the size of the actual array
in order to process it correctly. The solution is to add an extra
parameter indicating the size or actual number of elements in the
array.
void print_array(double a[], int size){//. . . }
14
Array as actual argument in function call
• To pass an array as actual argument to functions, we just give the array name
without the brackets.
• Since functions that take array usually also need to know the size of the array
or at least the number of elements in the array, the complete call to the
print_array function might be:
print_array(a, SIZE);
• Note that passing array as argument to functions is pass by reference not pass
by value. Thus, no copy of the array is made in the memory area of the
function. Instead, the function receives the address of the array and
manipulates it indirectly.
• How does the function receive the address when we did not use & operator
and the function did not declare a pointer variable?
• The truth is, array variables are in fact pointer variables, but which are 15
declared differently.
Multiple-Subscripted Arrays
• Multiple subscripted arrays
– Tables with rows and columns (m by n array)
– Like matrices: specify row, then column
– Example:
int a[3][4];
Column subscript
Array name
Row subscript
16
Multiple-Subscripted Arrays
• Initialization
1 2
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
3 4
– Initializers are grouped by row in braces
• Referencing elements
– Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
17