ARRAY
ARRAY
Fundamentals
Arrays
Introduction to an Array
Define Array: An array is a fixed-size sequenced collection of elements of the same
data type.
For e.g. an array can be used to represent a list of numbers, or a list of names.
Types of Arrays:
1. One-dimensional arrays.
2. Two-dimensional arrays.
3. Multidimensional arrays.
Characteristics of an array
1. An array holds elements that have the same data type
2. Array elements are stored in subsequent memory locations
3. Two-dimensional array elements are stored row by row in subsequent memory
locations.
4. Array name represents the address of the starting element
5. Array size should be mentioned in the declaration.
One dimensional array: Declaration,
initialization and accessing
Declaration Syntax:
datatype array_name[size];
• data type: it defines the datatype, like int,float,char,double etc.
• array_name: it is the name of array.
• size: It represents the size of the array.
• E.g. int number[5];
• The computer reserves five storage location as follows:
number[0]
number[1]
number[2]
number[3]
number[4]
One dimensional array: Declaration,
initialization and accessing
Initialization Syntax:
1. Compile time:
datatype arrayname[size]={List of value};
e.g. int number[5]={10,20,30,40,50};
The computer reserves and stores five numbers as follows:
10 number[0]
20 number[1]
30 number[2]
40 number[3]
50 number[4]
One dimensional array: Declaration,
initialization and accessing
• float total [5]={4.5,2.5,0.2};
Above syntax will initialize first three elements to 4.5, 2.5 and 0.2 and remaining two
elements to zero.
• char name[]={‘J’, ’O’, ‘H’, ‘N’, ’\0’};
Above syntax will declare name to be an array of five characters, initialized with
“JOHN ” and ending with NULL character.
• char name[]=“JOHN”;
Above syntax will assign string literal directly.
• int number[3]={11,67,85,45,90};
Above syntax will produce compile time error as we have more initializers than
declared size.
One dimensional array: Declaration,
initialization and accessing
2. Run time initialization:
• To insert element at specific position
scanf("%d", &arr[3]); / / will insert element at index 3, i.e. 4th position
• int table[2][3]={{1,2},{3}}
In the above syntax first two elements of row1 is initialized to {1,2} and first
element of row2 is initialized with 3 and all other elements are initialized with 0.
• int table[ ][3]={{0,0,0},{1,1,1}};
When the array is fully initialized we can skip the size of first dimension.
Two-dimensional array: Declaration, initialization and accessing
• Initialization of array(run time):
1. To insert element at specific position
scanf("%d", &arr[0][0]); / / will insert element at row index 0 and column index 0