Skip to content

Array in Data Structure: From Zero to Hero

Arrays in data structures

In this article, you’ll learn the following:

Table of Contents:
 [hide]

So, Let’s get started!

What is array in data structure with example?

First thing first Array is a type of data structure.

Now, your question would be, what type?… Right?

Answer: Array is a type of Linear and Static data structure.

If you are wondering, what is linear and static means here.

Then, here you go!

Linear: A data structure is said to be linear if its data items (i.e., elements or values) form a sequence (order) or a linear list.

In linear data structure, each and every element is attached to its previous and next adjacent element.

Static: A data structure is said to be static if it contains finite (fixed) number of elements and it can’t grow or shrink after it has been created or declared. The elements can be modified, but memory space to store any data item can’t be reallocated at a later stage.

Now, Let’s move into the actual definition of array.

Array definition:

An array is a collection (group) of more than one but finite number of data items, where each data item is of same type and stored at contiguous memory locations.

📝 Note: Each data item is called an element of the array.

From the above definition of array, By “finite” I mean that there is a specific number of elements in the array. This number may be large or small, but it must be fixed and exist.

By “data item” I mean any value or variable.

By “same type” I mean that all the elements in the array must be of similar type. For example, an array may contain all integers or all float but may not contain both or mixture of two or more type.

Visual Example:

Elements validity in an array

By “contiguous” I mean that the elements of the array are located adjacent (next) to one another in a group and they all together form a sequence.

Visual Representation of Array:

As we already know, for identifying or accessing anything in the universe you have to give certain name to that particular thing or object… Right?

So,

Let’s say A is chosen the name for an array, then the elements of A are denoted by subscript notation A0, A1, A2,……An

Or,

By the parenthesis notation: A(0), A(1), A(2). . . . . A(n)

Or,

By the bracket notation: A[0], A[1], A[2]. . . . . A[n]

Example:

A linear array named A consisting of the roll numbers (which all are integers) of five students.

Array in data structures
Image: Array

How is each element of an array referenced?

In array, Each element is referenced respectively by an index set (values) consisting of n consecutive numbers.

The index value always starts from 0 and goes till total number of elements minus 1.

This type of indexing is known as zero-based numbering or zeroth-order indexing.

Here, All the elements of the array are arranged in such a way so that they maintain the order of zeroth, first, second, third, and so on…

And, whatever the type of the array you create, no matter how many variables are inside that array. The index of the first variable will always be 0.

📝 Note:

  • The index value or simply index of the first element of an array is called its Lower bound.
  • The index of the last element is called its Upper bound.
  • The address of the first element of an array is called its Base address.
    • So, In the above image, you can see that the base address of the array A is 100.

Now, one more question arises here… Why array index starts from zero ?… Right?

Why array index starts from zero ?

Have you ever thought why the array index starts from 0 instead of 1 ?

The answer is very straightforward…

Not only in C or C++, but in most of the programming languages array index starts from zero.

This is only because, The basic definition of index in any programming language is: How far is any element from the first element.

That is, when I talk about the fifth element (i.e., array_name[4] ) of the array it means that,

How many steps do I have to walk from the first element to reach the fifth element? So if you observe, you will find that we have to walk four(4) steps.

Then how many steps will have to be walk to reach the first element from the first element?
Obviously 0 step. Right.

And that’s why indexing starts from 0 in many programming languages.

Visual Example:

Let’s take the same array A which we have seen above, the first five elements of A are denoted by A[0], A[1]. . . . . A[4]

Why array index starts from zero ?

What is array length?

Length of an array basically indicates the total number of elements present in an array.

Length of an array is also called as size of the array.

Example:

As you can see in the above image, we are storing the roll number of five students.

So, the total number of elements in the above case is five.

And, that’s why the length of the array will be five.

Array Length = Array’s Last Index + 1

So, from the above image of array we can say: Array length = 4 + 1 = 5

What are the types of arrays?

Basically, There are two types of arrays:

  1. One-Dimensional Array
  2. Multi-Dimensional Array

1. One-Dimensional Array:

If only one subscript (i.e., index) is required to reference or describe (express / define) each element in an array, the array is termed as one-dimensional / single-dimensional array or simply an array.

Or,

In other words: If all the elements of an array are arranged linearly either in horizontal (row-wise) or vertical (column-wise) direction, it is called as one-dimensional array.

So, from the above discussion, we can say that a one-dimensional array represents a linear structure.

The elements of a one-dimensional array will be accessed in sequential order. which means, Array will be accessed by the subscript of either a column or row index.

If the elements are arranged horizontally, we will use row index to access the elements.

And, If the elements are arranged vertically, we will use column index to access the elements.

Let’s see, How do you access one-dimensional array elements?

Syntax for declaring a one-dimensional array:

data_type array_name[size_of_the_array];

Or,

data_type array_name[ ] = {elements};

Don’t worry!… you’ll learn more about how to declare a one-dimensional array later in this article.

📝Note: If we put only one square bracket after the array_name then it is called as one-dimensional array.

We have already seen the image (visual-representation) of a one-dimensional array above.

2. Multi-Dimensional Array:

As the name indicates, A multi-dimensional array is an array having more than one dimension.

If an array occupies both horizontal rows as well as verticle columns to store the elements of the array like a table (tabular form), then it is called as two-dimensional array.

Similarly, for three-dimensional array we need one more direction either height or depth to store the elements of the array.

In simple words: Array of arrays is called a multi-dimensional array.

And, In this type of array, two or more subscript is required to reference each element of the array.

Syntax for declaring a multi-dimensional array:

data_type array_name[size1][size2][size3]……[sizeN]= {elements};

Here, size1, size2, size3 … up to sizeN describes the number of dimensions; in the case of a 2-D array, there are only two dimensions.

Multi-dimensional arrays are classified into two categories; namely Two-dimensional arrays (2-D Arrays) and Three-dimensional arrays (3-D Arrays).

Two-Dimensional Array:

  • It is the simplest form of a multi-dimensional array.
  • In this type of array, two indexes are required to describe each element, the first index represents a row, and the second index represents a column.
  • A two-dimensional array basically represents a matrix.
  • And, as we already know, a matrix is nothing but a tabular representation to store elements in rows and columns format.
  • A two-dimensional array can be accessed by using the value of row and column index.

So, you can think of a two-dimensional array is like a plane (flat) structure.

Syntax for declaring a two-dimensional array:

data_type array_name[number_of_rows] [number_of_columns];

Or,

data_type array_name[number_of_rows] [number_of_columns] = {elements};

So, from the above declaration syntaxes you can see that the first one is just defining how many rows and many columns an array contains and it does not initialize the elements at the time of declaration.

Whereas, the second form of declaration also contains the array elements and here we also initialize the elements of the array at the time of declaring it.

In a two-dimensional array, the total number of elements the array can hold is equal to number_of_rows multiplied by number_of_columns.

Let’s say we have an array A[3][2], this A can hold 6 elements. Which is basically equal to 3 * 2, Where 3 is the number of rows and 2 is the number of columns.

📝Note: If we put two square brackets after the array_name then it is called as two-dimensional array.

Two dimensional array in c/c++
Image: Two-Dimensional Array

Three-Dimensional Array:

  • A 3-D array is just an extension of 2-D array.
  • Here, we add one more dimension (which represents the depth or height of the table or matrix).
  • So, In this type of array, three indexes are required to define each element, the first index represents a row, the second index represents a column, and the third index represents the height of the matrix.
  • A three-dimensional array basically represents a cuboid like structure.
  • This type of array can be accessed by using the value of row, column and height index.
  • A three-dimensional array can be accessed by using the denotion: array_name[0][0][0] = 1st element, array_name[0][1][0] = 2nd element and so on…

So, you can think of a three-dimensional array is like a 3-D structure.

Syntax for declaring a three-dimensional array:

data_type array_name[number_of_rows] [number_of_columns] [number_of_tables];

Or,

data_type array_name[number_of_rows] [number_of_columns] [number_of_tables] = {elements};

In a three-dimensional array, the total number of elements the array can hold is equal to number_of_rows multiplied by number_of_columns multiplied by number_of_tables.

Let’s say we have an array B[3][4][5], this B can hold 60 elements. Which is basically equal to 3 * 4 * 5, Where 3 is the number of rows, 4 is the number of columns and 5 is the number of tables.

📝Note: If we put three square brackets after the array_name then it is called as three-dimensional array.

Three dimensional array in c/c++
Image: Three-Dimensional Array

How do you create an array?

Creating an array just requires two simple steps:

  1. Declaration of array
  2. Initialization of array

1. Declaration of array:

So the first question that might be arising in your mind is, what does array declaration mean or what is array declaration. Right?

If YES!

Then, Let’s explore…

What is array declaration?

Array declaration simply means, telling the compiler/interpreter about the following:

  1. Data type of the elements of an array,
  2. Name of the array,
  3. The size of the array,
  4. The elements it contains (It is optional)

If you provides elements of the array at the time of declaration in the same line, you don’t need to initialize the elements of the array separately.

So,

How do you declare an array?

You can declare an array in c/c++ simply by using the following syntax:

Syntax:

data_type array_name[size_of_the_array];

Syntax for declaring one-dimensional array
Image: Syntax for declaring a one-dimensional array

Or,

data_type array_name[ ] = {elements};

Syntax for declaring one-dimensional array
Image: Syntax for declaring one-dimensional array

Here, data_type can be any built-in (primitive) data type such as: int, char, float, double etc.

And, array_name could be any valid variable name which you would like to give as a name of the array.

📝Note:

  • If you initialize the elements of an array at the time of declaring it, then specifying the size_of_the_array inside the square bracket is optional.
  • You can directly initialize the elements of an array at the time of declaring it and there is no need of specifying the size of the array inside the square bracket.

Because, the compiler or the interpreter will already know the size of the array when you declare the elements at the time of array declaration.

Basically, There are various ways in which we can declare an array. It can be done by specifying its type and size, by initializing it or both.

Array declaration by specifying its type and size:

// Array declaration by specifying size
int arr[5];

// Array declaration by defining macro
# define SIZE 10
float newArray[SIZE];

// Declaring an array of user specified size
int n = 20;
char arr_char[n];

Array declaration by specifying size and initializing elements:

// Array declaration by specifying size and initializing elements
int arr[5] = {2, 4, 6, 8, 10};    

char s[8] = {'a', 'e', 'i', 'o', 'u'}

/* In the above case Compiler creates an array of size 8,
initializes first 5 elements as specified by user
and rest three elements as 0
It is same as  "char s[] = {'a', 'e', 'i', 'o', 'u', 0, 0, 0}"  */

Array declaration by initializing elements:

// Array declaration by initializing elements
int odd_number[ ] = {3, 5, 7, 9, 11};

/* In the above case Compiler creates an array of size 5.
which is same as  "int odd_number[5] = {3, 5, 7, 9, 11}"  */

How do you access array elements?

Elements of an array can be accessed by using the index value, the index value must be an integer which starts with 0 and goes till size of array minus 1.

And, This is done simply by placing the index of the element within square brackets after the name of the array.

If you only use array name without passing any index value to it, it will give you the first element of the array. Which indicates, Name of the array is also a pointer to the first element of array.

Let’s understand with the help of some examples:

// Accessing the elements of an array

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[5] = {2, 4, 6, 8, 10};
 printf("The first element of the array is: %d", arr[0]);
 printf("The last element of the array is: %d", arr[4]);
}

Output:

The first element of the array is: 2

The last element of the array is: 10

Some Basic Operations on Array:

Following are some basic operations that can be performed on an array:

  • Traversing
  • Inserting
  • Deleting
  • Searching
  • Sorting
  • Updating

Traversing:

Accessing or printing each element of an array exactly once so that the data item of the array can be checked or used as part of some other operation or process (This accessing and processing is sometimes called “visiting” the array).

Visual example

📝 Note: Accessing or printing of elements always takes place one by one.

Algorithm for Traversing an Array:

  • Step 01: Start
  • Step 02: [Initialize counter variable. ] Set i = LB.
  • Step 03: Repeat for i = LB to UB.
  • Step 04: Apply process to arr[i].
  • Step 05: [End of loop. ]
  • Step 06: Stop

Variables used here:

  1. i : Loop counter or counter variable of the array.
  2. arr : Array name.
  3. LB : Lower bound.
  4. UB : Upper bound.

Flowchart for Traversing an Array:

flowchart for traversing an array

Implementation in C:

// writing a program in C to perform traverse operation on an array

void main()
{
    int i, size;
    int arr[]={1, -9, 17, 4, -3};
    size=sizeof(arr)/sizeof(arr[0]);
    printf("The array elements are: ");
    for(i=0;i<size;i++)
        printf("\narr[%d]= %d", i, arr[i]);
}

If you compile and run the above program, it will produce the following result: 

Output:

The array elements are:
a[0]= 1
a[1]= -9
a[2]= 17
a[3]= 4
a[4]= -3


Implementation in C++:

// writing a program in C++ to perform traverse operation on an array
 
#include <iostream>
using namespace std;
int main()
{
    int i, size;
    int arr[]={53, 99, -11, 5, 102};    //declaring and initializing array
    size=sizeof(arr)/sizeof(arr[0]);
    cout << "The array elements are: ";
    for(i=0;i<size;i++)
        cout<< "\n" << "arr[" << i << "]= " << arr[i];
    return 0;
}

If you compile and run the above program, it will produce the following result: 

Output:

The array elements are:
a[0]= 1
a[1]= -9
a[2]= 17
a[3]= 4
a[4]= -3


Inserting:

Adding one or more elements at specified index/indices to an array is called insertion.

How do you insert an element in an array at a given position?

Let’s see how you can insert an element in an array at a given position step-by-step:

Variables we are using here:

  1. arr : Name of the array.
  2. size : Size of the array (i.e., total number of elements in the array)
  3. i : Loop counter or counter variable for the for loop.
  4. x : The data element to be insert.
  5. pos : The position where we wish to insert the element.

The following algorithm inserts a data element x into a given position pos (position specified by the programmer) in a linear array arr.

Algorithm to Insert an element in an Array:

  • Step 01: Start
  • Step 02: [Reset size of the array. ] set size = size + 1
  • Step 03: [Initialize counter variable. ] Set i = size - 1
  • Step 04: Repeat Step 05 and 06 for i = size -1 to i >= pos -1
  • Step 05: [Move ith element forward. ] set arr[i+1] = arr[i]
  • Step 06: [Decrease counter. ] Set i = i - 1
  • Step 07: [End of step 04 loop. ]
  • Step 08: [Insert element. ] Set arr[pos-1] = x
  • Step 09: Stop

Visual Representation:

 Insert an element in an Array
Image: Insert an element in an Array

Flowchart to Insert an element in an Array:

Flowchart to Insert an element in an Array

Implementation in C:

// writing a program in C to insert an element in an array

void main()
{
     int i, size, x, pos;
     int a[]={2, 4, 6, 8, 12};
     size=sizeof(a)/sizeof(a[0]);
     printf("The array elements before insertion operation:\n");
     for(i=0;i<size;i++)
        printf("%d\n", a[i]);
     printf("Enter the element to insert: ");
     scanf("%d", &x);
     printf("Enter the position where you want to insert the element: ");
     scanf("%d", &pos);
     size = size + 1;
     printf("The array elements after insertion operation:\n");
     for(i=size-1;i>=pos-1;i--)
        a[i+1]=a[i];
     a[pos-1]=x;
     for(i=0;i<size;i++)
        printf("%d\n", a[i]);
}

Output:

The array elements before insertion operation:
2
4
6
8
12
Enter the element to insert: 10
Enter the position where you want to insert the element: 5
The array elements after insertion operation:
2
4
6
8
10
12


Implementation in C++:

// writing a program in C++ to insert an element in an array
 
#include <iostream>
using namespace std;
int main()
{
     int i, size, x, pos;
     int arr[]={2, 4, 6, 8, 12};
     size=sizeof(arr)/sizeof(arr[0]);
     cout << "The array elements before insertion operation:\n";
     for(i=0;i<size;i++)
        cout << "arr[" << i << "] = " << arr[i] << "\n";
     cout << "Enter the element to be insert: ";
     cin >> x;
     cout << "Enter the position where you want to insert the element: ";
     cin >> pos;
     size = size + 1;
     cout << "The array elements after insertion operation: ";
     for(i=size-1;i>=pos-1;i--)
        arr[i+1]=arr[i];
     arr[pos-1]=x;
     for(i=0;i<size;i++)
        cout << "\narr[" << i << "] = " << arr[i];
     return 0;
}

If you compile and run the above program, it will produce the following result:

Output:

The array elements before insertion operation:
arr[0] = 2
arr[1] = 4
arr[2] = 6
arr[3] = 8
arr[4] = 12
Enter the element to be insert: 786
Enter the position where you want to insert the element: 1
The array elements after insertion operation:
arr[0] = 786
arr[1] = 2
arr[2] = 4
arr[3] = 6
arr[4] = 8
arr[5] = 12

Read more: Insert an element in an Array: Program, Algorithm and Flowchart


Deleting:

Removing one or more existing elements from specified position of an array.

How do you delete an element from an array in C/C++?

Let’s see how you can delete an element from a specific position of an array step-by-step:

Variables we are using here:

  1. a : Name of the array.
  2. size : Size of the array (i.e., total number of elements in the array)
  3. i : Loop counter or counter variable for the for loop.
  4. pos : The position from where we wish to delete the element.

The following algorithm deletes a data element from a specific position pos (position specified by the programmer) of a linear array ‘a‘.

Algorithm to Delete an element from an Array:

  • Step 01: Start
  • Step 02: [Initialize counter variable. ] Set i = pos - 1
  • Step 03: Repeat Step 04 and 05 for i = pos - 1 to i < size
  • Step 04: [Move ith element backward (left). ] set a[i] = a[i+1]
  • Step 05: [Increase counter. ] Set i = i + 1
  • Step 06: [End of step 03 loop. ]
  • Step 07: [Reset size of the array. ] set size = size - 1
  • Step 08: Stop

Visual Representation:

Delete an element from an Array
Image: Delete an element from an Array

Implementation in C:

// writing a program in C to delete an element from an array

void main()
{
     int i, size, x, pos;
     int a[]={2, 4, 6, 8, 12};
     size=sizeof(a)/sizeof(a[0]);
     printf("The array elements before deletion operation:\n");
     for(i=0;i<size;i++)
        printf("%d\n", a[i]);
     printf("Enter the position from where you want to delete the element: ");
     scanf("%d", &pos);
     size = size - 1;
     printf("The array elements after deletion operation:\n");
     for(i=pos-1;i<size;i++)
        a[i]=a[i+1];
     for(i=0;i<size;i++)
        printf("%d\n", a[i]);
}

Output:

The array elements before deletion operation:
2
4
6
8
12
Enter the position from where you want to delete the element: 3
The array elements after deletion operation:
2
4
8
12


Implementation in C++:

// writing a program in C++ to delete an element from an array
 
#include <iostream>
using namespace std;
int main()
{
     int i, size, x, pos;
     int a[]={-1, 87, -68, 10, 8};
     size=sizeof(a)/sizeof(a[0]);
     cout << "The array elements before deletion operation:\n";
     for(i=0;i<size;i++)
        cout << "a[" << i << "] = " << a[i] << "\n";
     cout << "Enter the position from where you wish to delete the element: ";
     cin >> pos;
     cout << "The array elements after deletion operation: ";
     for(i=pos-1;i<size;i++)
        a[i]=a[i+1];
     size = size - 1;
     for(i=0;i<size;i++)
        cout << "\na[" << i << "] = " << a[i];
     return 0;
}

If you compile and run the above program, it will produce the following result:

Output:

The array elements before deletion operation:
a[0] = -1
a[1] = 87
a[2] = -68
a[3] = 10
a[4] = 8
Enter the position from where you wish to delete the element: 2
The array elements after deletion operation:
a[0] = -1
a[1] = -68
a[2] = 10
a[3] = 8

Read more: Delete an element from an Array: Program and Algorithm


Searching:

The process of finding an element or the location of an element within the array is called Searching.

Or,

In other words – It is the process of finding a desired element or the location of the desired element with a given key value, or finding the locations of all such elements which satisfy one or more conditions.

How do you search for an element in an array?

Let’s see how you can search an element in an array step-by-step:

Variables we are using here:

  1. a : Name of the array.
  2. n: Size of the array (i.e., Total number of elements in the array).
  3. i : Loop counter or counter variable for the for loop.
  4. x : The data element to be search.

The following algorithm search a data element x in a linear array a.

Algorithm to Search an element in an Array:

  • Step 01: Start
  • Step 02: [Initialize counter variable. ] Set i = 0
  • Step 03: Repeat Step 04 and 05 for i = 0 to  i < n
  • Step 04: if a[i] = x, then jump to step 07
  • Step 05: [Increase counter. ] Set i = i + 1
  • Step 06: [End of step 03 loop. ]
  • Step 07: Print x found at i + 1 position and go to step 09
  • Step 08: Print x not found (if a[i] != x, after all the iteration of the above for loop. )
  • Step 09: Stop

Visual Representation:

Implementation in C:

// writing a program in C to search an element in an array

#define MAX 50
int main()
{
     int i, n, x;
     int a[MAX];
     printf("Enter the size of the array: ");
     scanf("%d", &n);
     printf("Enter %d elements:\n", n);
     for(i=0;i<n;i++)
        scanf("%d", &a[i]);
     printf("Enter the element to search: ");
     scanf("%d", &x);
     for(i=0;i<n;i++)
     {
         if(a[i]==x)
            {printf("%d found at %d position.", x, i+1);
             return 0;}
     }
     printf("%d not found", x);
     return 0;
}

If you compile and run the above program, it will produce the following result:

Output:

# searching an element which is present in the array

Enter the size of the array: 6
Enter 6 elements:
99
87
52
16
35
62
Enter the element to search: 35
35 found at 5 position.

# searching an element which is not present in the array

Enter the size of the array: 5
Enter 5 elements:
10
20
30
40
50
Enter the element to search: 25
25 not found


Implementation in C++:

// writing a program in C++ to search an element in an array
 
#include <iostream>
#define MAX 50
using namespace std;
int main()
{
     int i, n, x;
     int a[MAX];
     cout << "Enter the size of the array: ";
     cin >> n;
     cout << "Enter " << n << " elements:\n";
     for(i=0;i<n;i++)
        cin >> a[i];
     cout << "Enter the element to search: ";
     cin >> x;
     for(i=0;i<n;i++)
     {
 
        if(a[i]==x)
            {cout << x << " found at " << i+1 << " position.";
            return 0;}
     }
     cout << x << " not found";
     return 0;
}

If you compile and run the above program, it will produce the following result:

Output:

# searching an element which is present in the array
 
Enter the size of the array: 5
Enter 5 elements:
11
22
33
-512
99
Enter the element to search: -512
-512 found at 4 position.

Read more: Search an element in an Array: {Linear Search} – Program and Algorithm


Sorting:

The process of arranging the elements of an array in some logical order (e.g., alphabetically according to some NAME key, or in numerical order according to some NUMBER key, such as social security number or account number) is known as sorting.

How do you sort the elements of an array in C/C++?

Let’s see how you can sort the elements of an array step-by-step:

Variables we are using here:

  1. arr : Name of the array.
  2. n: Size of the array (i.e., Total number of elements in the array).
  3. i, j : Loop counter or counter variable for the for loop.
  4. x : A temporary variable for swaping two values.

The following algorithm sort the elements of an array in ascending order.

Algorithm to Sort the elements of an Array:

  • Step 01: Start
  • Step 02: Repeat Step 03 to 07 for i = 0  to i < n
  • Step 03: Repeat Step 04 and 05 for j = i + 1  to j < n
  • Step 04: Check a statement using the if keyword, If arr[i] > arr[j], Swap arr[i] and arr[j].
  • Step 05: [Increase counter. ] Set j = j + 1
  • Step 06: [End of step 03 loop. ]
  • Step 07: [Increase counter. ] Set i = i + 1
  • Step 08: [End of step 02 loop. ]
  • Step 09: Stop

Implementation in C:

// writing a program to perform sort operation on an array in C

#define MAX 50
void main()
{
    int i, j, n, a[MAX], x;
    printf("Enter the size of the array: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for(i=0;i<n;i++)
       scanf("%d", &a[i]);

    for (i = 0; i < n; i++)
    {

        for (j = i + 1; j < n; j++)
        {

            if (a[i] > a[j])
            {

                x =  a[i];
                a[i] = a[j];
                a[j] = x;

             }

        }

    }

    printf("The numbers arranged in ascending order are given below \n");
    for (i = 0; i < n; i++)
        printf("%d\n", a[i]);

}

If you compile and run the above program, it will produce the following result:

Output:

# sorting the elements of an array

Enter the size of the array: 7
Enter 7 elements:
963
4597
8457
1256984
14
201
246587
The numbers arranged in ascending order are given below
14
201
963
4597
8457
246587
1256984

Implementation in C++:

// writing a program to perform sort operation on an array in C++
 
#include <iostream>
#define MAX 50
using namespace std;
int main()
{
    int i, j, n, arr[MAX],x;
    cout << "Enter the size of the array: " ;
    cin >> n;
 
    cout << "Enter " << n << " elements:\n" ;
    for(i=0;i<n;i++)
       cin >> arr[i];
 
    for (i = 0; i < n; i++)
    {
 
        for (j = i + 1; j < n; j++)
        {
 
            if (arr[i] > arr[j])
            {
 
                x =  arr[i];
                arr[i] = arr[j];
                arr[j] = x;
 
             }
 
        }
 
    }
 
    cout << "\nThe numbers arranged in ascending order are given below: \n" ;
    for (i = 0; i < n; i++)
        cout << arr[i] << "\n" ;
    return 0;
 
}

If you compile and run the above program, it will produce the following result:

Output:

Enter the size of the array: 4
Enter 4 elements:
7
10
9
2
 
The numbers arranged in ascending order are given below:
2
7
9
10

Read more: Sort the elements of an Array in Ascending Order: Program & Algorithm


Updating:

The process of updating (modifying/changing) an existing element of an array at a specified index with another element is called updating an array.

How do you update an element in an array in C/C++?

Let’s see how you can update an element of a specific position of an array step-by-step:

Variables we are using here:

  1. a : Name of the array.
  2. size : Size of the array (i.e., total number of elements in the array)
  3. i : Loop counter or counter variable for the for loop.
  4. pos : The position where you wish to update the element.
  5. x : The updated element.

The following algorithm updates a data element at a specific position pos (position specified by the programmer) of a linear array ‘a‘.

Algorithm to Update an element in an Array:

  • Step 01: Start
  • Step 02: Set a[pos-1] = x
  • Step 03: Stop

Visual Representation:

Implementation in C:

// writing a program in C to update an element in an array

void main()
{
     int i, size, x, pos;
     int a[]={1, 3, 5, 7, 9};
     size=sizeof(a)/sizeof(a[0]);
     printf("The array elements before updation operation:\n");
     for(i=0;i<size;i++)
        printf("%d\n", a[i]);
     printf("The position where you want to update the element: ");
     scanf("%d", &pos);
     printf("The new element: ");
     scanf("%d", &x);
     a[pos-1]=x;
     printf("The array elements after updation operation:\n");
     for(i=0;i<size;i++)
        printf("%d\n", a[i]);
}

If you compile and run the above program, it will produce the following result:

Output:

The array elements before updation operation:
1
3
5
7
9
The position where you want to update the element: 2
The new element: 84
The array elements after updation operation:
1
84
5
7
9


Implementation in C++:

// writing a program in C++ to update an element in an array
 
#include <iostream>
using namespace std;
int main()
{
     int i, size, x, pos;
     int a[]={1, 3, 5, 7, 9};
     size=sizeof(a)/sizeof(a[0]);
     cout <<  "The array elements before update operation are:" ;
     for(i=0;i<size;i++)
        cout << "\n" << "a[" << i << "]= " << a[i];
     cout << "\nThe position where you wish to update the element: ";
     cin >> pos;
     cout << "The new element: ";
     cin >> x;
     a[pos-1]=x;
     cout << "The array elements after update operation are:";
     for(i=0;i<size;i++)
        cout << "\n" << "a[" << i << "]= " << a[i];
}

If you compile and run the above program, it will produce the following result:

Output:

The array elements before update operation are:
a[0]= 1
a[1]= 3
a[2]= 5
a[3]= 7
a[4]= 9
The position where you wish to update the element: 3
The new element: -10
The array elements after update operation are:
a[0]= 1
a[1]= 3
a[2]= -10
a[3]= 7
a[4]= 9

Read more: Update an element in an Array: Program and Algorithm


Advantages of Array:

  • Arrays store multiple data items (values) of the same type and can be represent and maintain using a single variable name.
  • In an array, accessing an element is very easy by using the index number. You can access any element of an array randomly by using the index number.
  • Name of an array represents the address of the first block of that array (i.e., the base address). And, If you know the base address of an array, you can obtain the address of any element of that array.
  • Arrays allocate memory in contiguous memory locations for all its elements.
  • Since we have to either specify the size of the array or to initialize the elements of the array or both at the time of declaration of an array and that’s why the memory of an array is predefined. Hence there is no chance of extra memory being allocated in case of arrays. This avoids memory overflow or shortage of memory or there is no extra memory loss.
  • 2D (Two-dimensional) arrays are used to represent matrices.
  • Other data structures like Linked lists, stacks, queues, trees, graphs etc can be implemented using arrays.
  • It allows to strore the elements in any dimension, Array supports multidimensional array.
  • Iterating the arrays using their index is faster compared to any other methods like linked list etc.
    • For this reason, Traverse and search operation in an array is quite easy and fast.
  • Its only the arrray, that provide a facility to jump over any index.

Disadvantages of Array:

  • As we have already discussed above, An array is a static data structure. You can’t alter/modify the size of an array at the execution time or run time of your program.
    • once you declared the size of the array it cannot be modified. The memory which is allocated to it can’t be increased or decreased. It means, the number of elements to be stored in an array should be known in advance.
  • Array is homogeneous. Which means, you can store only one type of value in the array. For example, if an array is of type “int“, it can only store integer elements and cannot allow the elements of other types such as float, char, boolean and so on…
  • Before initializing the elements to an array, all the values of the array are garbage values by default.
  • There is a possibility of wastage of memory space.
    • If elements inserted in an array are lesser than its allocated size and if the size requirement is less to store the elements. For example, Let’s suppose you declared an array of size 20 but later found out that you only needed to store 12 elements to store the marks of 12 students of your class who got more than 80%, so its a complete wastage of 8 elements storage space. Because when you declared array with size 20, memory space to store 20 element was already blocked on disk.
  • Insertion and deletion operations in an array is quite slow and difficult to implement.
    1. As array elements are stored at contiguous memory locations and the shifting operation is costly (i.e., time consuming). So, when inserting into an array, the insertion process requires moving each element from its initial location to the next available location. The shift cost increases linearly with the length of the array.
    2. The deletion process involves copying every preceding element one position back to fill up the gap left behind by the deleted element. Deleting items from an array is very expensive because of this reason.
    3. To overcome the above two problems, linked lists are implemented which provide random access of elements.
  • In C language, the compiler does not perform index bound checking on arrays. So, if any code is written that is outside the range of index values of an array and if you try to access an element using an index that doesn’t lie in the range of indexes of an array, the compiler does not perform index bound checking or signal any error. But at the time of access to the data the compiler shows a run time error, rather than an index out of bounds error and gives garbage value. While in C++ the compiler immediately gives an error when you compile the program.
  • Arrays have limited functionality compared to other data structures. They are good only for simple tasks. For complex problems, better solutions should be found.

Why do we need arrays?

Why do we need an array in data structures?

Let’s try to understand with the help of an example.

Think about a situation, when you need to calculate the average marks of all the students of your class in a particular subject.

It is obvious that your class have at least 10-15 students or maybe more. Right?

And, If you wish to find the average and had declared all the variables (here, variables are the marks of each student) individually, it would become a heptic task and very difficult to do any operation and also to maintain it.

Because, If you declare each variable individually then the number of variables will increases and if the number of variables increases then for storing each variable different memory location is required, as a result of it the efficiency of the program will be decreases.

And, If more number of student joins, then it is more difficult to declare a lot of variables and keep track of it.

But, If you use an array, the number of variables reduces, and you can maintain multiple variable names using a single name.

And, here you have to write less amount of code.

Now, you might be wondering that how you can maintain all those variables using a single name? Right?…

It’s only because, Here the type of each variable may be either of int or float type. So, If you consider the type of marks as float then you can give the type of your array as float.

And, you can access all those marks by simply putting the index values of the array.

So, To overcome the above discussed problem, Arrays comes into the picture.


Conclusion:

Congratulation!… 🎉 If you reached upto here.

In this article, you learned what is Array in data structure with example, you also became familiar with the different types of arrays, How to create them, Some basic operations on array and How to access the elements of the array with their syntaxes and lots of examples.

So,

I really hope that you liked my article and got a lot of value from it.

Now, It’s your turn!

If you have any question, feel free to ask in the comment section below right now.

And, and, and…

Don’t forget to share this article to your lovely friends.

Sharing is Caring! 💗


Share this Post

Leave a Reply

Your email address will not be published.