×

Introduction to Arrays

What exactly is an array?

A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which each data piece may be retrieved simply by its index number alone.

For example, if we want to keep a student's grades in five subjects, we don't need to establish distinct variables for each topic. We may instead build an array that stores the data items in contiguous memory regions.

Array marks[5] denotes the marks scored by a student in 5 different subjects, where each subject marks are located at a specific location in the array, i.e. marks[0] denotes the marks scored in the first subject, marks[1] denotes the marks scored in the second subject, and so on and so forth.

The objective is to group together goods of the same category. This makes calculating the position of each element easy by simply adding an offset to a base value, such as the memory address of the array's first member (generally denoted by the name of the array. Index 0 is the starting point, and the offset is the difference between the two indices.

Use of an Array Is Necessary –

In most circumstances, programming requires the storage of a huge amount of data of a comparable type. We need to establish a lot of variables to store such a large amount of data. While writing the scripts, it would be quite difficult to remember all of the variable names. It is preferable to create an array and store all of the items in it.

The following example demonstrates how arrays may be utilised in code-writing:

We've given a student's grades in five distinct disciplines in the example below. The goal is to find the average of a student's grades.

Without the use of an array –

#include<stdio.h>
void main()
{
            int sub1 = 41, sub2 = 54, sub3 = 50, sub4 = 74, sub5 = 72;
            float average = (sub1 + sub2 + sub3 + sub4 + sub5)/5;
            printf(average);
}

While array is being used –

#include<stdio.h>
void main()
{
            int subject[5]={41,54,50,74,72};
            float average = ( subject[0] + subject[1] + subject[2] + subject[3] + subject[4])/5;
            printf(average);
}

Complexities of Array Operations

Time Complexity

AlgorithmAverage caseWorst case
AccessO (1)O (1)
SearchO (n)O (n)
InsertionO (n)O (n)
DeletionO (n)O (n)

The worst case space complexity of an array is O (n).

What Are the Different Array Types?

Arrays can be divided into two categories:

  • Arrays in One Dimension:   
Data Structure - Arrays

A 1d array may be thought of as a row with elements stored one after the other.

  • Arrays with Multiple Dimensions:

There are two types of multi-dimensional arrays. They are as follows:

  • Arrays in Two Dimensions:
Data Structure - Arrays

You may think of it as a table with items in each cell.

  • Arrays in Three Dimensions:

You may think of it as a cuboid built up of smaller cuboids, each of which can hold an element.

The size of the array

In the C programming language, an array has a fixed size, which means that once the size is set, it cannot be modified, i.e. it cannot be shrunk or expanded. The rationale for this was because while expanding, we can't always be sure (it's not always feasible) that we'll obtain the following memory address as free. The shrinking won't work since the array is RAM statically allocated when it's defined, and the compiler is the only one who can remove it.

In Arrays, there are several types of indexing.

  • 0 (Zero Based Indexing) - The array's initial member corresponds to index 0.
  • 1 (One Based Indexing) - The array's first member corresponds to index 1.
  • n (n Based Indexing) – An array's base index can be customised to meet specific needs.
Data Structure - Arrays

Getting to an Array's Elements –

The following information is required to access any element of an array:

  • The array's starting address.
  • In bytes, the size of an element.
  • Array is the type of indexing that follows.

The following formula may be used to compute the address of any element in a 1D array:

A[i] = base address + size * (i – first index)

Array to Function Passing –

As previously stated, the address of the array's first element is represented by the array's name. The base address may be used to traverse the items of an array.

The following example shows how to provide an array to a function.

The programme below defines the total function, which takes an array as an input. This function computes the sum of all the array's items.

#include<stdio.h>
int total(int[]);
void main()
{
    int array[5] = {0,1,2,3,4};
    int sum = total(array);
    printf(“%d”,sum);
}
int total(int array[])
{
    int sum=0;
    int index;
    for(index=0; index<5; index++)
    {
        sum = sum + array[index];
    }
    return sum;
}

Defined 2D Array

An array of arrays is a common definition for a two-dimensional array. A matrix is another name for a two-dimensional array. A matrix looks like a table with rows and columns’.

Array's Benefits -

  • Arrays use a single identifier to represent numerous data components of the same kind.
  • Using the index number to retrieve or find an element in an array is simple.
  • The index of an array may be simply incremented by one to traverse it.
  • For all of its data items, arrays reserve memory in contiguous memory regions.
  • Memory overflow is avoided by using arrays.
  • There is no extra memory loss because the array memory is present.
  • 2D arrays are a good way to display tabular data.

Arrays have certain drawbacks.

Disadvantages of utilising arrays include the inability to adjust the size of the array after it has been declared due to static memory allocation. Here because the pieces are stored in successive memory regions, insertions and deletions are complex, and the shifting operation is also expensive.

Array-based applications.

  • Data elements of the same data type are stored in an array.
  • It's used to solve matrices problems.
  • In a computer, it's used as a lookup table.
  • Arrays are also used to implement database records.
  • Assists with the implementation of the sorting algorithm.
  • Variables of the same type can be stored under the same name.
  • CPU scheduling may be done with arrays.
  • Stacks, Queues, Heaps, Hash tables, and other data structures are implemented using this class.

Related Topics

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree. Implementation /* creating a program that...

4 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Operations on 1D-Arrays

One Dimensional Array Operations Basic Methods The fundamental operations enabled by an array are listed below. Traverse prints each element of the array one by one.Insert a new element at the specified index.Delete...

8 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Tree in Data Structure

Tree A tree is a non-linear data structure by which hierarchical data is displayed. As we know that there are many trees in the forest, similarly the data structure also contains...

3 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Selection Sort

In each iteration of the selection sort algorithm, the smallest item from an unsorted list is chosen and placed at the top of the unsorted list. Algorithm of Selection Sorting In order...

3 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

5 minutes read.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.