User Menu

Login



Share with

Array in C++ PDF Print E-mail

Array

array

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.

Arrays come in two flavors: one dimensional and dimensional arrays.

Declaring an Array

Just like any variable ,an array has to be declared before being used. Yet the difference this time is that you need to tell the compiler what kind of array you are defining. This is because, once more, the compiler wants to know how much space your array is going to occupy in the computer memory. This is because when you declare an array of items, the compiler puts each one of the items in an appropriate location. 
Like any other variable, the syntax of declaring an array is:

DataType ArrayName[size]

The array is first identified by its kind, which could be a char, an int, a float, etc; followed by its name. The name is then followed by square brackets that specify the size of the array.

Here are examples of declaring arrays:

int a[4];

float f[100];

double d[100];

int a[4]; declares a group or array of 4 values, each one being an integer.

arraymap

float f[100]; declares an array of 100 floating-point values.

double d[100]; declares an array of double-precision numbers. There are 100 of these items in the group.

Initializing an Array

Just like any variable can be initialized, an array also can be initialized. To accomplish this, for a one-dimensional array, the syntax used is:

DataType ArrayName[size] = { element1, element2, …, elementn};

Here are examples of declaring an initializing arrays:

int num[5] = {1,2,3,4,5};

If you have decided to initialize the array while you are declaring it, you can omit the size. Therefore, array can be declared as follows:

int num[] = {1,2,3,4,5};

Processing the Elements of an Array

After initializing an array, its elements are counted from left to right. Each element of the array, also called a member of the array, has a specific and constant position. The position of an item is also called its index. The first member of the array, the most left, has an index of 0. The second member of the array has an index of 1. Since each array has a number of items which can be specified as n, the last member of the array has an index of n-1

Based on this system of indexing, to locate a member of an array, use its index in the group. Imagine you declare and initialize an array as follows:

double weight[] = {20.2,24.5,34.7};

To locate the value of the 3rd member of the array, you would type weight[2]. In the same way, the 1st member of the array can be located with weight[0].

Once you can locate a member of the array, you can display its value. Here is an example:

#include <iostream.h>

int main()
{
 double weight[] = {20.2,24.5,34.7};

 cout << "2nd member = " << weight[1] << endl;
 cout << "3rd member = " << weight[2] << endl;
 return 0;
}

This would produce:

2nd member = 24.5
3rd member = 34.7

The Size of an Array

When declaring an array, we saw that you must specify the number of items that the array is made of. Here is an example:

float price[5];

Depending on how you want to deal with your array, you may sometimes need to increase or decrease its dimension. To do this, you would need to locate the declaration of the array and change its dimension. If the program is long and the array is declared in some unusual place, this could take some time.

The alternative is to define a constant prior to declaring the array and use that constant to hold the dimension of the array. Here is an example:

#include <iostream.h>

int main()
{
const int SIZE = 5;
int weight[SIZE] = {20,30,40,50,60};

    cout << "weight 1: " << weight[0] << endl;
    cout << "weight 2: " << weight[1] << endl;
    cout << "weight 3: " << weight[2] << endl;
    cout << "weight 4: " << weight[3] << endl;
    cout << "weight 5: " << weight[4] << endl;

return 0;
}
We knew the dimensions of the arrays we have used so far, because we could count the number of members of the array. Imagine you declare a large array, possibly made of 50 or 100 members, you wouldn't start counting the number of members. C++ provides the sizeof operator that can be used to get the dimension of an array. The syntax you would use is:

sizeof(NameofArray)

If we declare an array as follows:

int number[] = {1,2,3,4,5};

Instead of counting the number of members of this array  we can use the sizeof operator as follows:
int NumberOfElements = sizeof(Number)/sizeof(int);

Accessing Array Members

int items[5];

Each member of the array can be located using its index, as we have seen so far. In the same way, you can request the value of any member of the array using its index. In the following example, we declare an array of 5 integers and then we request the values of the 2nd and the 4th members:

#include <iostream.h>

int main()

{
    const int count = 5;

    int items[count];

    cout << "Enter the values of two items\n";
    cout << "Item 1: ";
    cin >> items[0];
    cout << "item 4: ";
    cin >> items[3];
    cout << "\nYou have Entered following values";
    cout << "\nItem 1: " << items[0] ;
    cout << "\nItem 4: " << items[3] ;
    return 0;
}

Here is an example of running the program:
Enter the values of two items
Item 1: 45
Item 4: 66
You have Entered following values
item 1: 45
item 4: 66

Operations on Arrays

We can add the values of two members of the array(Number[2]+Number[0]), you can subtract the value of one of the members from another member(member[1]-Number[4]). In the same way, you can perform multiplication, division, or remainder operations on members of an array.

Deletion from an Array

#include <iostream.h>

int main()

{
   int array[100], position, c, n;

    cout<<"Enter number of elements in array\n";

    cin>>n;


    for ( c = 0 ; c < n ; c++ )

    cin>>array[c];

cout<<"Enter the location where you wish to delete \n";
     cin>>position;


       if ( position >= n+1 )

         cout<<"Deletion not possible.\n";

         else

         {

          for ( c = position - 1 ; c < n - 1 ; c++ )

            array[c] = array[c+1];

          cout<<"Resultant array is\n";

          for( c = 0 ; c < n - 1 ; c++ )

           cout<<array[c]<<endl;

         }

 return 0;

}
Concatenation of two Linear Arrays

#include<iostream.h>
#define N 5
int main()
 {
 int a1[N],a2[N],a3[N+N];
 int i,j;
 cout<<"Enter Elements of First Array:";
 for(i=0;i<N;i++)
    cin>>a1[i];
 cout<<"Enter Elements of Second Array:";
 for(i=0;i<N;i++)
    cin>>a2[i];
 // Now we will Concatenate These two Arrays
 for(i=0;i<N;i++)
    a3[i]=a1[i];
 k=i;
 for(i=0;i<N;i++)
    a3[k++]=a2[i];
 cout<<"After Concatenation The third Array Contain:";
 for(i=0;i<N+N;i++)
    cout<<a3[i]<<endl;
return 0;
}

Merging of Two sorted Arrays

#include <iostream.h>

void merge(int [], int, int [], int, int []);
int main()
 {
  int a[100], b[100], m, n, c, sorted[200];
  cout<<"Input number of elements in first array\n";
  cin>>m;
  
  for (c = 0; c < m; c++)
    cin>>a[c];
    
  cout<<"Input number of elements in second array\n";
  cin>>n;
  
  for (c = 0; c < n; c++)
    cin>>b[c];
  merge(a, m, b, n, sorted);
  
   cout<<"Sorted array:\n";
   for (c = 0; c < m + n; c++)
    cout<<sorted[c];
   return 0;
}
void merge(int a[], int m, int b[], int n, int sorted[])
 {
  int i, j, k;
   j = k = 0;
   for (i = 0; i < m + n;)
   {
    if (j < m && k < n)
     {
      if (a[j] < b[k])
      {
        sorted[i] = a[j];
        j++;
      }
      else
      {
        sorted[i] = b[k];
        k++;
      }
      i++;
     }
    else if (j == m)
     {
      for (; i < m + n;)
       {
        sorted[i] = b[k];
        k++;
        i++;
      }
     }
    else {
      for (; i < m + n;)
      {
        sorted[i] = a[j];
        j++;
        i++;
      }
    }
  }
}

Linear Search

Another type of operation regularly performed on an array consists of looking for a value held by one of its members. For example, you can try to know if one of the members holds a particular value you are looking for. Here is an example:

#include <iostream.h>

int main()

{
    // Declare the members of the array


    int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};

    int find;

    int i, m = 8;

    cout << "Enter a number to search: ";

    cin >> find;

    for (i = 0;i < m; ++i)

        if(numbers[i]== find)

        cout << find << " Found" << endl;

 //Find whether the number typed is a member of the array
    if (i == m)

        cout << find << " Not Found" << endl;

  return 0;

}
This would produce:

Enter a number to search: 44

44 Found

Binary Search

Another type of search in an Array is Binary search. Binary search can work only on sorted array.

Binary Search

#include <iostream.h>

int main()

{    // Declare the members of the array

    int numbers[] = {12, 17, 23, 45, 50, 71, 80, 93};

    int find;

    int mid,low=0,high=7;

    cout << "Enter a number to search: ";

    cin >> find;

      while(low<=high)

         {

          mid= (low+high)/2;

             if( find==numbers[mid])

               {

                cout<<"Element Found";

                break;

               }

             else if( find >numbers[mid]


                low=mid+1;

             else

                high=mid-1;

           }

           if(low>high)

            cout<<"Element not Found";

     return 0;

}
This would produce:

Enter a number to search: 23

Element Found

Bubble Sort

Bubble Sort

The basic idea of Bubble sort is to compare two adjoining values and exchanged then if are not in proper order.

// Example of Bubble Sort

#include <iostream.h>

int main()

{   // The members of the array

    int numbers[] = {43, 36, 25, 89, 20, 52, 75, 10};

    int minimum = numbers[0];

    int a = 8,temp;

    // Compare the members

    for (int i = 0; i < 7; ++i)

       for(int j=i+1;j<7;j++)   

         if (number[i] > number[j])

         {

         temp=number[i];

         number[i]=number[j];

         number[j]=temp;

          }

       cout << "After Sorting The Array elements are ";

        for(i=0;i<7;i++)

         cout<<number[i]<<endl;

      return 0;

}
This would produce:

10,20,25,36,43,52,75,89.

Selection Sort

Selection Sort

The algorithm works as follows:

  1. 1.Find the minimum value in the array
  2. 2.Swap it with the value in the first position
  3. 3.Repeat the steps above for the remainder of the array (starting at the second position and advancing each time)

Effectively, the array is divided into two parts: the sublist of items already sorted, which is built up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Here is an example of this sort algorithm sorting five elements:
64 25 12 22 11
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64

// Example of Selection Sort

#include<iostream.h>
#define n 10
int main()
{
int a[n];
int i,j,k,temp;
int iMin;
 cout<<"Enter Array Elements "<<endl;
 for(k=0;k<n;k++)
   cin>>a[k];
 for (j = 0; j < n-1; j++)
   { /* find the min element in the unsorted a[j .. n-1] 
       assume the min is the first element */
    iMin = j;
  // test against elements after j to find the smallest 
     for ( i = j+1; i < n; i++)
        {
  // if this element is less, then it is the new minimum  
        if (a[i] < a[iMin])
        iMin = i;
        }
// iMin is the index of the minimum element. Swap it with the current position 
    if ( iMin != j )
    {   temp=a[j];
        a[j]=a[iMin];
        a[iMin]=temp;  
   }
}
   cout<<"After Selection Sort Array Elements are "<<endl;
     for(k=0;k<n;k++)
       cout<<a[k]<<endl;
 return 0;
}

Insertion Sort

Insertion Sort

Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array (or list) is built one entry at a time.

How it works:

In insertion sort,elements are entered into the array 1-by-1.

When the first element is entered, it is placed at the 1st position in the array.

When a new element is entered, it is compared to our already entered element and is decided whether to place before or after it in the array.

Now when the third element is entered is entered, it is compared with the greater element of the 2 already existing elements. If smaller, then it is swapped. If not, then the array can be considered sorted.

If swapped, then is compared with the smaller element of the 2 already existing elements and swapped again with it if it is even smaller.

Similarly, all the the numbers to be placed in the array are entered 1-by-1 and placed into the correct position right when they’re entered.

Example:

The following table shows the steps for sorting the sequence 5 7 0 3 4 2 6 1. On the left side the sorted part of the sequence is shown. For each iteration, the number of positions the inserted element has moved is shown in brackets. Altogether this amounts to 17 steps.
 
5     7     0     3     4     2     6     1         (0)
5     7     0     3     4     2     6     1         (0)
0     5     7     3     4     2     6     1         (2)
0     3     5     7     4     2     6     1         (2)
0     3     4     5     7     2     6     1         (2)
0     2     3     4     5     7     6     1         (4)
0     2     3     4     5     6     7     1         (1)
0     1     2     3     4     5     6     7         (6)

#include<iostream.h>
int main()

{
    double arr[8],temp;

    cout<<"Insertion sort Demonstration."<<endl<<endl;

    for (int i=0;i<8;i++)

    {

       cout<<"Enter element number "<<i+1<<": ";

       cin>>arr[i];   
//Runs until the new number has been placed in its correct place

       
     while(j>0 && arr[j]<arr[j-1])

     {

      //Swap if the elements are out of order.

       temp=arr[j];

       arr[j]=arr[j-1];

       arr[j-1]=temp;

       j--;    //decrease array index

     }

    }

   cout<<endl<<"Array After Sorting = ";

    for(i=0;i<8;i++)

     cout<<arr[i]<<endl;

return 0;


}

Arrays and Functions

An array can be passed to a function as argument. An array can also be returned by a function. To declare and define that a function takes an array as argument, declare the function as you would do for any regular function and, in its parentheses, specify that the argument is an array. Here is an example:

You don't have to specify the dimension of the array. This means that you can leave the square brackets empty:

#include <iostream.h>

int main()

{

void Display(char items[]);

const int NumberOfItems = 5;

char items[NumberOfItems] = {'A','B','C','D','E'};

Display(items); //The compiler only needs the name of the array to process it

return 0;

}

void Display(char items[])

{
    for(int i = 0; i < 5; ++i)

    cout << "\nItmem " << i + 1 << ": " << items[i];

    cout << endl;

}

When we call a function that has an array as argument, the compiler only needs the name of the array to process it.

Two-Dimensional Arrays

A 2-dimensional array is an array of arrays. In other words, it is an array where each member of the array is also an array.

2DARRAYMAP

Declaring and Initializing a 2-Dimensional Array

Two-dimensional array is made of rows and columns. Each column represents one category of data that everyone of the rows shares with the other rows. To declare it, use double pair of a opening and closing square brackets.

Data_Type NameOfArray[ROWS][COLUMNS];

int TwoDArray[5][5];

This declarations creates 5 rows and each row contains 5 elements.

You can initialize an array the same way you would proceed the a one-dimensional array: simply provide a list of values in the curly brackets.

A multidimensional array is represented as an algebraic matrix as MxN. This means that the array is made of M rows and N columns. Total number of elements of a multidimensional array can be calculated by multiply the number of rows by the number of columns. Therefore a 2x3 array contains 2*3=6 elements.

Based on this, when initializing a 2-dimensional array, make sure you provide a number of values that is less than or equal to the total number of elements.

Here is an example:

double age[2][3] = {12,14,16,17,18,19};

To locate a member of the array, this time, each must be identified by its double index. The first member is indexed at [0][0]. The second is at [0][1]. For a 2x3 array as this one, the 5th member is at [1][1]. You can use this same approach to display the values of the members of the array. Here is an example:
#include <iostream.h>

int main()

{ // A 2-Dimensional array

int TwoDArray[2][3] = {1,2,3,4,5,6};

// Display the array

    cout << "Elements of the array";

cout<<"\nTwoDArray [0][0]" << ": " << TwoDArray[0][0];
cout<< "\nTwoDArray [0][1]" << ": " << TwoDArray[0][1];
cout<< "\nTwoDArray [0][2]" << ": " << TwoDArray[0][2];
cout<< "\nTwoDArray [1][0]" << ": " << TwoDArray[1][0];
cout<< "\nTwoDArray [1][1]" << ": " << TwoDArray[1][1];
cout<< "\nTwoDArray [1][2]" << ": " << TwoDArray[1][2];
    cout << endl;

    return 0;

}
Output:
Elements of the array

TwoDArray [0][0]: 1

TwoDArray [0][1]: 2

TwoDArray [0][2]: 3

TwoDArray [1][0]: 4

TwoDArray [1][1]: 5

TwoDArray [1][2]: 6

C++ also allows you to include each row in its own pair of curly brackets. You must separate each row from the next with a comma. Here is an example:

int items[2][3] = { { 1,2,3},{4,5,6}  };

Representation of 2D array in memory

Let’s assume Arr is an two dimensional 2 X 2 array .The array may be stored in memory one of the following way :-

1. Column by column i.e column major order
2. Row by row i.e row major order. 

Both representations of the above array.

Column Major Order-Column fixed for each row 

Column Major Order-Column fixed for each row 

columnmajor

Row major Order-Row fixed for each column  
rowmajor

We know that computer keeps track of only the base address. So the address of any specified location of an array , for example Arr[j,k] of a 2 d array Arr[m,n] can be calculated by using the following formula :

Column major order

Address(Arr[j][k])= base(Arr)+w[m(k-1)+(j-1)]

Row major order

Address(Arr[j][k])=base(Arr)+w[n(j-1)+(k-1)]

For example Arr[25][4] is an array with base value 200,w=4 for this array. The address of Arr[12][3] can be calculated using

Row-major order as 
Address(Arr[12][3] )= 200+4[4(12-1)+(3-1)]
=200+4[4*11+2]
=200+4[44+2]
=200+4[46]
=200+184
=384
Column-major order as
Address(Arr[12][3] )= 200+4[25(3-1)+(12-1)]
=200+4[25*2+11]
=200+4[50+11]
=200+4[61]
=200+244
=444

Processing a 2-Dimensional Array

To process a 2D array, we should know how many columns the array contains. We can use two for loops to process the array. Here is an example:

#include <iostream.h>
int main()
{
    // A 2-Dimensional array
    int items[2][3] = {
                { 1,2,3},
                { 4,5,6}
                      };

    // Display all elements
    cout << "Elements of the array";
    for(int i = 0; i < 2; ++i)
       for(int j = 0; j < 3; ++j)
        cout << "\nItems[" << i << "][" << j << "]: " << items[i][j];
    cout << endl;
  return 0;
}

Finding Sum and Difference of two N X M Arrays

#include <iostream.h>
#define N 3
#define M 3
int main()
{
    int a1[N][M],a2[N][M],s[N][M],d[N][M];
    int sum=0,i,j;
     cout<<"Enter Elelemts of First Array";
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         cin>>a1[i][j];
    cout<<"Enter Elelemts of Second Array";
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         cin>>a2[i][j];
    // Mow we will find sum and difference
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         {
         s[i][j] =a1[i][j]+a2[i][j];
         d[i][j] =a1[i][j]-a2[i][j];
        }
    cout<<"Sum of a1 and a2 is";
     for(i=0;i<N;i++)
       {
        for(j=0;j<M;j++)
          cout<<s[i][j];
       cout<<endl;
       }    
    cout<<"Difference of a1 and a2 is";
     for(i=0;i<N;i++)
       {
        for(j=0;j<M;j++)
          cout<<d[i][j];
       cout<<endl;
       }    
   return 0;
}
Interchanging ROWS and COLUMN of a N X M Arrays
#include <iostream.h>
#define N 3
#define M 3
int main()
{
    int a1[N][M],a2[N][M];
    int i,j;
    cout<<"Enter Elements Array";
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
         cin>>a1[i][j];
       // Mow we will Interchange row and columns elements
    for(i=0;i<N;i++)
       for(j=0;j<M;j++)
          a2[j][i] =a1[i][j];
    cout<<"Original Array is";
     for(i=0;i<N;i++)
       { 
        for(j=0;j<M;j++)
           cout<<a1[i][j];
       cout<<endl;
       }    
    cout<<"After interchanging row and columns ";
      for(i=0;i<N;i++)
        {
         for(j=0;j<M;j++)
           cout<<a2[i][j];
        cout<<endl;
           }    
    return 0;
}
2D Array and String

Because strings are in fact sequences of characters, we can represent them also as plain arrays of char elements.

For example, the following array:

char Ayan[20];

is an array that can store up to 20 elements of type char. In this array, we can store sequences of characters up to 20 characters long. But we can also store shorter sequences. For example, Ayan could store at some point in a program either the sequence "Hello" or the sequence "Happy Diwali", since both are shorter than 20 characters.

Therefore, since the array of characters can store shorter sequences than its total length, a special character is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\0' (backslash, zero).

Our array of 20 elements of type char, called Ayan, can be represented storing the characters sequences "Hello" and "Happy Diwali" as:

stringwithnull 

Notice how after the valid content a null character ('\0') has been included in order to indicate the end of the sequence.

Initialization of null-terminated character sequences
If we want to initialize an array of characters with some predetermined sequence of characters we can do it just like any other array:

char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; 

In this case we would have declared an array of 6 elements of type char initialized with the characters that form the word "Hello" plus a null character '\0' at the end.

Arrays of char elements have an additional method to initialize their values: using string literals. String literals enclosed between double quotes always have a null character ('\0') automatically appended at the end by the compiler. Therefore we can initialize the array of char elements called Ayan with a null-terminated sequence of characters by either one of these two methods:

char Ayan[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

char Ayan[] = "Hello"; 

In both cases the array of characters Ayan is declared with a size of 6 elements of type char: the 5 characters that compose the word "Hello" plus a final null character ('\0') which specifies the end of the sequence and that, in the second case, when using double quotes (") it is appended automatically.

Using null-terminated sequences of characters

Null-terminated sequences of characters are the natural way of treating strings in C++.For example, cin and cout support null-terminated sequences as valid containers for sequences of characters, so they can be used directly to extract strings of characters from cin or to insert them into cout. For example:

// null-terminated sequences of characters
#include <iostream.h>
int main ()
{
  char yourname[] = "Please, enter your first name: ";
  char message [] = "Hello, ";
  char name [80];
  cout << yourname;
  cin >> name;
  cout << message << name << "!";
  return 0;
}

Please, enter your first name: Sanjeev
Hello, Sanjeev!

As you can see, we have declared three arrays of char elements. The first two were initialized with string literal constants, while the third one was left uninitialized. In the first two arrays the size was implicitly defined by the length of the literal constant they were initialized to. While for name we have explicitly specified that it has a size of 80 chars.

scroll back to top