User Menu

Login

Share with

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.

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:

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:

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:

Here is an example of running the program:Enter the values of two itemsItem 1: 45Item 4: 66You have Entered following valuesitem 1: 45item 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;

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.

#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

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

The algorithm works as follows:

1.Find the minimum value in the array

2.Swap it with the value in the first position

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.

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.

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.

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>

We know that computer keeps track of only the base address. So the address of anyspecified 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

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:

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:

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.