Array
What are
Arrays?
The array is a fixed-size sequenced collection of variables belonging to the same data types. The values are stored in contiguous memory location. The syntax for declaring array is:
Data_type
Array_name[Array_size];
Here, Data_type is the type of data which we need to declare for the Arrays. Array_name is the name given to the array and Array_size is the size given to the array.
Every item stored in an array is termed as element. Each memory location of an element in an array is denoted by a numerical index which is used for identifying the element.
From the above figure,
Types of indexing in Array
Why do you
need Arrays for Building Specific Data Structure?
A program works with many variables which hold comparable forms of data. If we are not using arrays, the number of variables declared will increase. By using arrays, the number of variable reduces i.e., a single name is given for multiple values. Here in arrays, we deal with index values.
Example
Instead of storing the marks of the student scored in five subjects in separate variable, we can store it in array of the student_name[5].
John[5] = {60,66,72,68,80}
Here in the above example, the indices hold the subject name.
Collecting input data
in Arrays
Arrays are mainly used for making a collection of input data which arrive in random order. An excellent example can be counting of votes in an election. The program can be written to tally the votes of a four candidates in an election. The candidate names are nothing but the index of the array such as cand 0, cand 1, cand 2, cand 3, etc. The votes arrives once at a time, where a vote for Candidate i is denoted by the number i. So according to the example, the structure would be like:
int votes[4];
Advantages of using arrays: