Concept of Arrays in Data Structures

Last updated by Ashwin Ramachandran on Dec 22, 2024 at 02:16 PM
| Reading Time: 3 minutes

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
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:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

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:

IK courses Recommended

Master AI tools and techniques customized to your job roles that you can immediately start using for professional excellence.

Fast filling course!

Master ML, Deep Learning, and AI Agents with hands-on projects, live mentorship—plus FAANG+ interview prep.

Master Agentic AI, LangChain, RAG, and ML with FAANG+ mentorship, real-world projects, and interview preparation.

Learn to scale with LLMs and Generative AI that drive the most advanced applications and features.

Learn the latest in AI tech, integrations, and tools—applied GenAI skills that Tech Product Managers need to stay relevant.

Dive deep into cutting-edge NLP techniques and technologies and get hands-on experience on end-to-end projects.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

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:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

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

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary