The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

C++ Arrays

Introduction to Arrays
Suppose you want to store the marks of 100 students of a class and then find the average. Would you declare 100 variables for that ? Definitely not. So, here comes a data structure called array which provides an utility to store a collection of elements of same data type in contiguous memory location.
Consider the declaration below :

int marks [5];

In the above statement, we have declared an array named marks which can store 5 values of type int. Each of the values can be accessed using an index in the array.
Suppose there are 5 values stored in the array marks as show below :

7562934988

Value stored at index 0 of array marks is 75 i.e marks [ 0 ] = 75. Remember array index starts from 0.
Similarly, marks [ 2 ] = 93. The array marks can be initialized with 5 values in a single statement :

int marks [ ] = { 75, 62, 93, 49, 88 };

We see that size of the array is not specified in the above statement. Since, we have initialized the array with 5 values, an array of size 5 is automatically created. We can explicitly specify the size of the array. In that case, if we specify the size as 5, we can initialize with 5 elements only. Consider the following program which takes marks of 5 students in an array and then find the sum and average of all marks :

#include<iostream>
using namespace std;

int main() {
   int marks[5]; // declare an array to store 5 values
   int i; // array index 
   int sum = 0;
   float average;
   cout << "Enter the marks of 5 students :- " << endl;

   // read marks of 5 students
   for ( i = 0; i < 5 ; i++ ) {
      cout << "Marks of student " << i << " : ";
      cin >> marks[i]; // input marks of student 'i' in index 'i' of the array 
   }

   // compute sum and average
   for ( i = 0; i < 5 ; i++ ) {
      sum += marks[i]; // add the value in each index of the array 
   }
   average = (float)sum / 5;

   cout << "Sum : " << sum << endl;
   cout << "Average : " << average << endl;
   return 0;
}
Run this program in your system to take input at run-time  

Passing array to function
Arrays are by default passed by reference. Consider the following program in which we implement four functions ( insert, delete, search and display ) :

#include<iostream>
using namespace std;

/* Displays the array */
void displayArray(int arr[], int size) {
   int i;
   for ( i = 0; i < size; i++ ) {
      cout << arr[i] << " ";
   }
}

/* delete the element at index 'pos' 
   Variable 'size' is passed by reference as the size of the array is changed
   Array 'arr' is passed by reference by default   
*/
void deleteElement(int arr[], int &size, int pos) {
   if ( size == 0 ) { // check for empty array
      cout << "\nArray is empty ... ";
      return;
   }
   if ( pos >= size ) {
      cout << "\nInvalid Position ...";
      return;
   }
   int i;
   // delete the element at index 'pos'
   for ( i = pos; i < size-1; i++ ) {
      // shift all elements by 1 position towards left starting from 'pos'
      arr[i] = arr[i+1];
   }
   size--; // update array size 
}

/* Insert the element 'k' at index 'pos' 
   Variable 'size' is passed by reference as the size of the array is changed
*/
void insertElement(int arr[], int &size, int k, int pos) {
   if ( size == 5 ) { // Array has no space to insert more elements
      cout << "\nArray has no space ... ";
      return;
   }
   if ( pos >= size ) {
      cout << "\nInvalid Position ...";
      return;
   }
   int i;
   // insert the element 'k' at index 'pos'
   for ( i = size-1; i > pos; i-- ) {
      // shift all elements by 1 position towards right till 'pos'
      arr[i] = arr[i-1];
   }
   arr[pos] = k; // insert the element
   size++; // update size
}

/* Search an element 'val' in the array
   Return the position (index) if element is found else return -1 
*/
int searchElement(int arr[], int size, int val) {
   int pos = -1, i;
   for ( i = 0; i < size; i++ ) {
      if (arr[i] == val) { // compare each array element with 'var'
         pos = i; // element found
         break; // break out of loop
      }
   }
   return pos;
}

int main() {
   int arr[5] = { 56, 43, 12, 9, 39 }; // declare and initialize the array
   int size = 5;
   cout << "\nOriginal Array : ";
   displayArray(arr, size);
   deleteElement(arr, size, 2); // delete the element at index 2 of the array
   cout << "\nAfter Deletion : ";
   displayArray(arr, size);
   insertElement(arr, size, 99, 2); // insert element 99 at index 2
   cout << "\nAfter Insertion: ";
   displayArray(arr, size);
   int element = 99;
   int pos = searchElement(arr, size, element); // search element '99'
   if (pos != -1) {
      cout << "\nElement " << element << " is found at position : " << pos;
   }
   else {
      cout << "\nElement not found ... " << pos;
   }
   cout << endl;
   return 0;
}

Sorting is another popular operation on array elements. Please refer to the sorting algorithm section to understand how different sort techniques work.

Dynamic Memory Allocation
Till now we have seen static memory allocation by declaring an array of specific size. In this method, we must know the size of array in advance. We can allocate memory by specifying the size at runtime using new operator. Any memory dynamically allocated using new operator must be freed using delete operator. Otherwise there would be memory leak . Memory leak is a situation in which memory is held up without any use. Also, dynamic allocation is done using memory from system heap instead of stack. See the following program to understand the use of new and delete operators :

#include<iostream>
using namespace std;

int main() {
   int *arr, n = 7, i;
   arr = new int[n]; // dynamically allocate an array of size 'n'
   for ( i = 0; i < n; i++ ) { // fill up the array indices with some values 
      arr[i] = (i + 1) * 10;
   }
   // display the array
   cout << "Array elements : ";
   for ( i = 0; i < n; i++ ) {
      cout << arr[i] <<" ";
   }
   delete arr; // deallocate the memory to prevent memory leak
   cout << endl;
   return 0;
}


Pointer to an array
We have seen that a pointer variable stores the address of another variable. A pointer variable can point to an array as well. Consider the following statements :

int marks [ ] = { 75, 62, 93, 49, 88 };
int *ptr = marks; // ptr points to first index of the array
int *ptr = &marks[0]; // This statement is same as the above one

We declared a pointer variable ptr which points to the first element of the array. Since array elements are stored in contiguous memory locations, all the elements can be accessed using ptr. Moreover, a pointer variable can point to any index of the array. Following program demonstrates the use of pointer to an array :

#include<iostream>
using namespace std;

int main() {
   int arr[5] = { 4, 7, 6, 9, 3 };
   int *ptr = arr; // ptr holds the address of first element in arr[]
   // different ways of accessing array elements
   cout << "Value at index 0 is " << arr[0] << endl;
   cout << "Value at index 1 is " << 1[arr] << endl;
   cout << "Value at index 2 is " << *(ptr + 2) << endl;
   cout << "Value at index 3 is " << *(3 + ptr) << endl;
   int *i = &arr[3]; // 'i' points to index 3 of the array
   cout << "Value at 'i' is " << *i << endl;
   i++; // 'i' now points to index 4 of the array
   cout << "Now Value at 'i' is " << *i << endl;
   return 0;
}

Back | Next