1
Data Structure & Algorithms
Arrays
Array is a data structure which stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type. Instead of declaring individual va riables,
such as number0, number1, ..., and number99, you declare one array variable such as numbers
and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A
specific element in an array is accessed by an index. All arrays consist of contiguous memory
locations. The lowest address corresponds to the first element and the highest address to the
last element. The array is the most commonly used data storage structure; it’s built into most
programming languages. Basic operations in array are traversing, insertion, search, and deletion.
Index 0 1 2 3 4 5 6 7 8 9
Value 20 13 24 53 46 15 36 72 8 29
Element:
Every item stored in an array is termed as an element
Index:
Each memory location of an element in an array is denoted by a numerical index which is used
for identifying the element.
Length:
Array must have specific length that cannot be changed throughout the execution of program.
Algorithm
1. Begin
2. Set index = 0
3. Set Array[length]
4. Repeat steps 5 and 6 while index < length
5. Set Array[index] = ITEM
6. Set index = index+1
7. End
2
Data Structure & Algorithms
Implementation of Array Insertion in C++
There are three ways to insert data in Array these are as follows:
First Method:
int arr[4]; // array declaration
arr[0]= 5; // assign value to index 0
arr[1]= 10; // assign value to index 1
arr[2]= 15; // assign value to index 2
arr[3]= 20; // assign value to index 3
cout<<arr[0]<<arr[1]<<arr[2]<<arr[3]<<endl; // printing all values in Array
Second Method:
int ar2[3] = {4,5,6}; // array declaration & initialization
cout<<ar2[0]<<ar2[1]<<ar2[2]<<endl; // printing all values in Array
Third Method:
int arr2[5] ; // array declaration
for(int i =0; i<5; i++) // assign value to array using loop
{
cout<<"enter number :";
cin>>arr2[i];
}
for(int i =0; i<5; i++) // printing all values in Array using loop
cout<<arr2[i];