Professional Documents
Culture Documents
Arrays In C
By Mohit Arora
It is used to store series of values of the same type, sequentially The whole array bears a single name, and the individual items, or elements, are accessed by using an integer index
e.g int debts[10];//int is the datatype //debts is name of array //and 20 is the number of elements //contained in an array
/* /* /* /*
of of of of
Above [] brackets identifies a as an array We can access individual elements by writing its index number or subscript in square brackets along with the array name. cont.
.
. .
X = debts[2];
/*this will transfer the value at index 2 of debts array, i.e. 1 to the variable X*/
5
8
Initialization of An Array
Array Initialization;
#define NUM = 8; /*constant, a good prog. practice*/
Initialization cont.
What if we dont initialize an array;
/* no_data.c -- uninitialized array */ #include <stdio.h> #define SIZE 4 int main(void) { int no_data[SIZE]; /* uninitialized array */ int i; printf("%2s%14s\n", "i", "no_data[i]"); for (i = 0; i < SIZE; i++) printf("%2d%14d\n", i, no_data[i]); return 0; } Like ordinary variables if we dont initialize the array elements they can have any value already present at that memory location. The output is; i no_data[i] 0 16 1 4204937 2 4219854 3 2147348480 Which are values present already in those memory location
Initialization cont.
/* some_data.c -- partially initialized array */ #include <stdio.h> #define SIZE 4 int main(void) { int some_data[SIZE] = {1492, 1066}; int i; printf("%2s%14s\n", "i", "some_data[i]"); for (i = 0; i < SIZE; i++) printf("%2d%14d\n", i, some_data[i]); return 0; } This time the output looks like this: i some_data[i] 0 1492 1 1066 2 0 3 0 Which means partial initialization, also set the other memory locations to 0;
Initialization cont
Another way;
const int days[] = {31,28,31,30,31,30,31,31,30,31}; //compiler sets the number of items to 10 automatically
Designated Initialization;
int arr[6] = {0,0,0,0,0,212}; // traditional syntax int arr[6] = {[5] = 212}; // initialize arr[5] to 212
if we want to initialize just one element of array, former is the traditional way, and later is the new C99 method.
We can use loops for assigning values to array in addition to assignment at initialization
Array Bounds
C compiler wont check the boundary of your array, so its the programmer responsibility. Reason! To make C faster. How to avoid!
Use a symbolic constant for length of Array index, Remember that indexing starts at 0 in C.
int n = 5; int m = 8; float a1[5]; float a2[5*2 + 1]; float a4[-4]; float a5[0]; // yes // yes // no, size must be > 0 // no, size must be > 0
float a6[2.5];
float a7[(int)2.5]; float a8[n]; float a9[m];
Multidimensional Arrays
Declaration;
int box[2][2]; int box[2][2][2]; //uptil 26 in Bloodshed DevC
Initialization;
Int box[2][2] = { {1, 2}, {3, 4} }; //two col and rows Int box[2][2][2] = { { {1,2}, {3, 4} }, { {5,6}, {7, 8} } };