Suppose a class contains 50 students, and we want to store their roll numbers, we need 50 separate variables for storing the roll numbers, as shown below:
Now to store roll numbers into these variables, we need another 50 statements, like
Imagine writing 100 statements, just to store roll numbers of students. On the other hand, if we have a single variable that can represent all these 50 variables, it would be very useful to us. Such a variable is called an Array.
An array represents a group of elements of the same type. It can store a group of elements. So we can store a group of int values or a group of float values or a group of strings in the array. But we cannot store some int values and some float values in one array.
Def: Array helps to create a number of memory locations which occupy contiguous memory locations, store similar type of values and share the same name.
The advantage of using arrays is that they simplify programming by replacing a lot of statements by just one or two statements. (In C/C++ , by default arrays are created on static memory unless pointers are used to create them.)
Array helps us to create a number of memory locations which occupy continuous memory, store similar type of values and share the same name.
Declaration of array
While declaring an array we have to mention the following.
• Data type of the array
• Name of the array
• Size of the array i.e. Total number of memory locations.
datatype arrayname [size];
• Memory locations equal to the specified size are created in the memory.
• All the memory locations occupy continuous memory.
• All memory locations store similar type of values, same as that of the array. That is if data type of the array is “int” then all the memory locations can store “int” values and if data type of the array is “float” then all the memory location can store “float” values. And so on.
• Memory locations created in the memory are numbered sequentially starting from 0(zero) i.e. the first memory location is numbered 0(zero) , the second one is numbered 1(one) and so on. The last memory location is numbered one less then the size of the array.
All memory locations share the same name, same as that of the array.