DATA STRUCTURE AND ALGORITHM (Array)

 ARRAY


An Array is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. 



arrays
Array



Array declaration by specifying size:

// Array declaration by specifying size

int array1[20];


// We can also declare an array of user specified size

int n = 20;

int array2[n];


Array declaration by initializing elements:

// Array declaration by initializing elements

int array[] = { 10, 20, 30, 40 }


Array declaration by specifying size and initializing elements:

// Array declaration by specifying size and initializing
// elements

int array[6] = { 10, 20, 30, 40 }




Advantages of an Array in C++: 

  1. Random access of elements using array index.
  2. Use of less line of code as it creates a single array of multiple elements.
  3. Easy access to all the elements.
  4. Traversal through the array becomes easy using a single loop.
  5. Sorting becomes easy as it can be accomplished by writing less line of code.

Disadvantages of an Array in C++: 

  1. Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  2. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.


A sample C++ program:


#include <iostream>
using namespace std;
 
int main()
{
    int arr[5];
    arr[0] = 15;
    arr[2] = -1;
 
    // this is same as arr[1] = 12
    arr[5 / 4] = 12;
    arr[3] = arr[0];
 
    cout << arr[0] << " " << arr[1] << " " << arr[2] << " "
         << arr[3];
 
    return 0;
}


Output:

15 12 -1 15


Connect with the Author:




Comments

Popular posts from this blog

DATA STRUCTURE AND ALGORITHM (Pointer)

DATA STRUCTURE AND ALGORITHM (Structure)