Concept of Arrays in Data Structures

Last updated by Ashwin Ramachandran on Dec 22, 2024 at 02:16 PM
Contents

In this article, we’ll cover the basics of the “array” data structure — learn what an array is in coding, learn about array operations, and implement some of them in C, C++, Java, and Python. Arrays are indispensable for technical interview prep for any engineering role in the software industry, whether for a software engineer, coding engineer, or software developer role.

This article focuses on:

  • What are Arrays in Data Structure?
  • Array Operations:
  • Implementation of Array Operations
  • Advantages and Disadvantages of Using Arrays
  • Examples of Interview Questions on Arrays
  • FAQs on the Array Data Structure

What Are Arrays in Data Structure?

Let us begin answering this question by understanding what an array is in math: It’s an arrangement of objects, numbers, or pictures in rows and columns. Similarly, as a data structure, an array is values of the same data type stored in rows and columns together. We’re aiming to store multiple elements of the same data type together in contiguous locations, so each element and its position is easily accessible individually.

An array is made up of elements, which represent values stored in the array. These elements are stored at contiguous locations, with each element’s location having a unique numerical index. This index can also be used to access the element associated with it. In fact, it can be used to access any other element in the array whose relative position with respect to this element is known. The size of an array is fixed in most languages.

Example: An array of type string containing a list of department names. The size of the array is 5 as it has 5 elements. The array indices in this example start from 0, which is the case for most programming languages. Languages like COBOL, R, MATLAB, Fortran, among others, have the default index of their array’s first element as 1.

Array size: 5 || First Index: 0 || Last Index: 4

Array Operations

We’ll now learn about some of the array operations and then perform them in different languages. The syntax for different languages is different, so we’ll focus on what the operation requires and is about and learn the syntax through an example later.

Declaring and Creating an Array

For creating an array, we first have to define an array variable of the desired data type. We also need to allocate the memory that will store the array elements; for this, we will need to either know or clearly determine the size of the array. In different languages, the syntax for array creation is different, but usually, there are two major ways we can declare an array:

Declaration by Initializing Array Elements Only

In this method, we initialize the values of all elements in the array, and we don’t give the size of the array explicitly. The size of the array is determined by the number of elements initialized in the array and, once determined, can’t be changed in the future.

Declaration by giving size and then Initializing Array Elements

In this method, we give the size of the array explicitly and then proceed to initialize the values of the array elements.

Accessing Array Elements

When accessing elements, we may need to access all/some elements or just one particular element at a time. There are different ways to achieve this based on the need.

Accessing/Traversing through all array elements

We can traverse through all array elements using a for loop run for all indices or using a foreach loop run for all elements in the array.

Accessing a Specific Array Element

A specific element can be accessed simply by using the array name along with the index of the element. The syntax is very similar to: arrayName[index] for most languages

Modifying an Array Element

We can modify the value of an element by simply accessing it and assigning it another value. The syntax for most languages will be close to: arrayName[index] = new_Value. We can also traverse through all elements and update the values of each of them as required.

Let us now look at what the code for these operations would look like in the four most common languages.

Implementation of Array Operations

In this article, we’ll implement array operations in C and C++.

Implementation of Array Operations in C

// Program to take 5 values from the user and store them in an array

// Print the elements stored in the array

#include <stdio.h>

int main() {

// Declaring array by simply initializing it

int arrayOdd[] = {1, 3, 5, 7, 9};

 

// Declaring array by giving size and then initializing

// individual values

int arrayEven[3];

arrayEven[0] = 2;

arrayEven[1] = 4;

arrayEven[2] = 6;

 

// Using for loop traversing through each element

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

printf(“Traversing arrayEven’s %d-th element %dn”, i, arrayEven[i]);

}

 

// Accessing a particular element and modifying the value of a

// particular element

printf(“Element arrayOdd[2] is %dn”, arrayOdd[2]);

arrayOdd[2] = 8;

printf(“Modified element arrayOdd[2] is %dn”, arrayOdd[2]);

 

return 0;

}

 

Output:

Traversing arrayEven’s 0-th element 2

Traversing arrayEven’s 1-th element 4

Traversing arrayEven’s 2-th element 6

Element arrayOdd[2] is 5

Modified element arrayOdd[2] is 8

Implementation of Array Operations in C++

#include <iostream>

using namespace std;

int main()

{

// Declaring array by simply initializing array

int arrayOdd[]= {1,3,5,7,9};

int arrayNum[3]={1,2,3};

 

// Declaring array by giving size and then initializing

// individual values

int arrayEven[3];

arrayEven[0]=2;

arrayEven[1]=4;

arrayEven[2]=6;

// Using for-each accessing all elements

for(int i:arrayOdd)

{cout<<i<<” “;}

cout<<“n”;

// Using for loop traversing through each element

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

{

cout<<“Traversing arrayEven’s “<<i<<“-th element “<<arrayEven[i]<<“n”;

}

// Accessing a particular element and modifying the value of a

// particular element

cout<<“Element arrayOdd[2] is “<<arrayOdd[2]<<“n”;
arrayOdd[2]=8;

cout<<“Modified element arrayOdd[2] is “<<arrayOdd[2]<<“n”;

return 0;

}

Output:

1 3 5 7 9

Traversing arrayEven’s 0-th element 2

Traversing arrayEven’s 1-th element 4

Traversing arrayEven’s 2-th element 6

Element arrayOdd[2] is 5

Modified element arrayOdd[2] is 8

Implementation of Array Operations in Java

class Main {

public static void main(String[] args)

{

// Declaring array by simply initializing array

int[] arrayOdd = {1,3,5,7,9};

// Declaring array by giving size and then initializing

// individual values

int arrayEven[] = new int[3];

arrayEven[0] = 2;

arrayEven[1] = 4;

arrayEven[2] = 6;

// Using for-each accessing all elements

for(int i:arrayOdd)

{System.out.print(i+” “);}

System.out.println(“”);

// Using for loop traversing through each element

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

{

System.out.print(“Traversing arrayEven’s “+i+”-th element “+arrayEven[i]+”n”);

}

// Accessing a particular element and modifying the value of a

// particular element

System.out.print(“Element arrayOdd[2] is “+arrayOdd[2]+”n”);

arrayOdd[2]=8;

System.out.print(“Modified element arrayOdd[2] is “+arrayOdd[2]+”n”);

}

}

Output:

1 3 5 7 9

Traversing arrayEven’s 0-th element 2

Traversing arrayEven’s 1-th element 4

Traversing arrayEven’s 2-th element 6

Element arrayOdd[2] is 5

Modified element arrayOdd[2] is 8

Implementation of Array Operations in Python

import array as Arr

#Creating an array in python

arrayOdd = Arr.array(‘i’, [1,3,5,7,9])

arrayEven = [2,4,6]

#Using for-each accessing all elements

for i in arrayOdd:

print(i, end=” “)

print()

#Using for loop traversing through each element

for i in range (0, 3):

print(“Traversing “, “arrayEven’s “, i, “-th “, “element “, arrayEven[i], sep = “”)

#Accessing a particular element and modifying the value of a particular element

print(“Element”, “arrayOdd[2]”, “is”,arrayOdd[2], sep=” “)

arrayOdd[2]=8

print(“Modified”,”element”, arrayOdd[2], “is”,arrayOdd[2], sep=” “)

Output:

1 3 5 7 9

Traversing arrayEven’s 0-th element 2

Traversing arrayEven’s 1-th element 4

Traversing arrayEven’s 2-th element 6

Element arrayOdd[2] is 5

Modified element 8 is 8

Advantages and Disadvantages of Using Arrays

The importance of arrays in coding can’t be overstated. Many data structures that don’t have some of these disadvantages of arrays (such as linked list, stack, queue, heap) either use arrays in some form or require a good understanding of arrays.

Examples of Interview Questions on Arrays

Write a program in C and C++ in which you:

  • Create an array of structures
  • Write a program for array insertion
  • Suggest alternate data structures which will be better for insertion, explain why and implement them in the language of your choice.

For more tech interview questions and problems, check out the following pages: Interview Questions, Problems, Learn.

FAQs on the Array Data Structure

Question 1: Why is the memory allocation and utilization in arrays not efficient?

Answer: Since the size of an array is fixed once decided, over-allocation leads to space wastage, and under-allocation can only be handled by creating another bigger array as the array size can’t be modified. Hence, we say that the memory allocation and utilization in arrays isn’t efficient.

Question 2: What makes quick random access of elements possible in arrays?

Answer: Quick random access is made possible in arrays due to three characteristics of arrays: One: A unique index (usually 0,1,2, …) is associated with each element (all of the same type). Two: The elements are stored in contiguous memory locations. Three: The array name represents the address of the first array element. This means that when we write arrayName[index], we are providing the starting address of the array with the array name. We also know the data type of the elements stored, so we know the memory each element takes. With this, we can easily get where the element with a particular index lies. For example, if A is an array of type char, and the address of A[0] is, say, 2048, then we can easily calculate the address of A[5] to be 2053, since each element is of type char, and char takes only 1 byte of data.

Are You Ready to Nail Your Next Coding Interview?

If you’re looking for guidance and help with getting your prep started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

———-

Article contributed Tanya Shrivastava

Last updated on: December 22, 2024
Author
Ashwin Ramachandran
Head of Engineering @ Interview Kickstart. Enjoys cutting through the noise and finding patterns.
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC