ARRAYS
Limitation of fundamental datatypes
Variable of fundamental datatypes can store only one value at any given time.
Inefficient to handle large amount of data. To handle large amount of data, we need powerful derived datatype like arrays.
Array
An array is a fixed size sequence collection of elements of the same data type.
example : int a[5]; char c[4]; float f[10];
Some examples where concept of arrays can be used.
List of employees in an organization
List of students in a class.
List of subjects in a semester
List of marks of 5 subjects.
How the Compiler recognizes an Array?
Just like variables and functions array have to be declared before their usage. Declaration of array;
int main(void) { float a[365]; char b[12]; int c[50]; int debts[10]; ... } /* /* /* /* array array array array of of of of 365 floats */ 12 chars */ 50 ints */ 10 ints */
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.
How to Access the Elements of Array
Array Index The index of an Array starts at index 0 ,continue till one less than debts[0] the size of the array. Example int debts[10] debts[1] debts[2] . . . debts[8] Array Data 1 2 1 . . . 5 8
debts[9]
Input and output array element
scanf(%d,&a[0]);
printf(%d,a[3]);
Array Initialization
int arr[8] = {1,2,4,6,8,16,32,64}; float f[3]={2.34,4.56,6.78};
Another way
int counter[ ]={1,1,1,1};
char name[ ]={'J','H','O','N','\0'};
char name[ ]=JOHN;
Partial intialization
int number[5]={10,20};
char city[5]={'B'};
Array element manipulations
a=number[0]+10;
number[4]=number[0]+number[2];
number[2]=x[5]+y[10];
value[6]=number[i]*3; The subsscripts of an array can be integer constants,integer variables like i,or expressions that yield integers.
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.
// yes // yes
float a1[5]; float a2[5*2 + 1];
float a3[sizeof(int) + 1]; // yes
float a4[-4];
float a5[0]; float a6[2.5]; float a7[(int)2.5];
// no, size must be > 0
// no, size must be > 0 // no, size must be an integer // yes, typecast float to int constant
Two dimensional array
int a[3][4];
Rows=3, columns=4
Total elements = 12
(3*4)