INTRODUCTION OF ARRAYS
An array is a very popular and useful data structure used to store data elements in successive memory locations. More than one element is stored ia an sequence ,so it is also called a composite data structure.
An array is a linear and homogeneous data structure . An array permits homogeneous data.It means that similar types of elements are stored contiguously in the memory and that too under one variable name.It can be combined with a non-homogeneous structure, and a complex data structure can be created. We know that an array of structure objects can also be useful.An array can be declared of any standard or custom data type .The array of character (strings) type works somewhat differently from an array of integers,floating numbers.
Consider the following example .A variable A having data type integer is initially assigned some value and later on its value is changed .Later assigned value to the variable can be displayed.
void main ()
{
int a=2;
a=4;
cout<<a;
}
OUTPUT =4
In the above example , the value of A printed is 4. 2 is assigned to A before assigning 4 to it .When we assign 4 to A then the value stored in A is replaced with the new value .Hence,ordinary variables are capable of storing one value at a time.This fact is the same for all the data types.This can be obtained with the help of arrays.
An array variable allows the storing of more similar data type element /values at a time .
Declaration of a one-dimensional array can be done with data type first, followed by the variable name and at least the size is enclosed in square brackets.
int a[5] ;
It tells the compiler that A is an integer type of an array and can store five integers.The compiler reserves 2 bytes of memory for each integer array element, i.e 10 bytes are reserved for storing five integers in the memory .
In the same way,an array of different data types is declared as follows:
char ch[10];
float real[10];
long num [5];
When we declare a variable , for example:
int x;
the variable x is declared and the memory locations of two bytes is allocated to them and later a single value can be stored in it.
x=4;
Every variable has a name ,a value its memory locations.Hence from the above we can say that only one value can be assigned /stored to a variable
- An array is a group of contiguous or related data items that share a common name.
- used when programs have to handle large amount of data
- each value is stored at a specific position
- position is called a index or superscript.Base index=0
- The ability to use a single name to represent a collection of items and refer to an item by specifying the item number enables us to develop concise and efficient programs .For example ,a loop with index as the control variable can be used to read the entire array , perform calculations, and print out the results.