Home » Blog » Array Data Structure – Now in a simplified version

# Array Data Structure – Now in a simplified version

• C, Game Dev, Python, Web Dev

We’ll examine the array data structure in today’s article. Now that we’ve made things simple for you to comprehend, let’s get into the meat of the matter.

## What is an array data structure?

Let’s start with the most fundamental question: What is an array? The solution is straightforward. A group of homogeneous elements stored in contiguous memory regions is referred to as an array.

The array in the above example is made up of integer data types, with memory addresses 1,2,3,…,7 at the top and element memory locations at the bottom.

## Properties of array data structure

• The elements of an array are stored in adjacent memory locations
• The elements have to be homogeneous data types. That is the elements of an array should be of the same data type.
• After creation, its length is fixed.

## Advantages of using Array data structure

• The elements of an array can be accessed easily and in a random manner

## Arrays in Python

In python unlike other languages Arrays are not frequently used because Python has a built-in data type called “Lists” that is very similar to arrays. So you may get the question now why do we need arrays in python. So to explain this we’ll take a situation where we need to find the product of a list of elements say [10,6,8,7] so the code will be:

``````li = [10,6,8,7]
prod = li*2
print(prod)``````

Line 2 will throw an error as we can’t perform ‘int’ operations on ‘list’. To make this run we have to use a for loop and append the products in the new list that is:

``````li = [10,6,8,7]
prod = []
for i in range (len(li)):
prod.append(i*2)
print(prod)``````

To simplify the same we can rather use arrays.

``````from numpy import array
arr = array([10,6,8,7])
prod = arr*2
print(prod)``````

here we’re using the “array” function from the NumPy module.

## Installing NumPy in the windows system

We can install NumPy (if not installed already) with the command

``py -m pip install numpy``

## Installing Numpy in macOS/Linux

We can install NumPy (if not installed already) with the command

``python3 -m pip install numpy``

## Another way of using arrays

We can also use array by importing the array module

``````from array import *
arr = array("i",[1,2,3])
for i in a:
print(i)``````

Here the “i” in line 2 means the type code i.e., the data type of the array we defined. As we’ve seen earlier arrays are of the same data type it’s important to use the signs. More examples of the datatypes are:

• i – int
• f – float
• d – double
• c – code (or Unicode)
• d – double
• L – long
• u – character

## Array Functions

there are various array functions some of which we’ll be seeing are

### type code

To get the type code of the array we can use

``````from array import *
arr = array("i",[1,2,3])
print(a.typecode)``````

### count

To count the occurrence of an element in an array we could use

``````from array import *
arr = array("i",[1,2,3,2,3,4,3,5])
print(a.count(2))``````

### length

To find the length of an array we’re using

``````from array import *
arr = array("i",[1,2,3])
print(len(a))``````

### Adding and removing elements in an array

To add elements in an array we can simply use the append() method

``````from array import *
arr = array("i",[1,2,3])
arr.append(4)
print(arr)``````

append() adds elements towards the last of the array.

And to remove we’ll be using remove() and pop()

``````from array import *
arr = array("i",[1,2,3,4,3])
arr.remove(3)
print(arr)``````

As you might’ve noticed, remove() deletes the first occurrence of the element that we passed

``````from array import *
arr = array("i",[1,2,3])
arr.pop()
print(arr)``````

As we know from list functions using the pop() method we can also assign it to a variable

``````from array import *
arr = array("i",[1,2,3])
elem = arr.pop()
print(arr)
print(a)``````

pop() removes the last element of the array we can also assign the poped element to a variable

## Other Array functions

### index()

Used to find the index of the first occurrence of an element

``````from array import *
arr = array("i",[1,2,3])
print(arr.index(2))``````

### reverse()

Used to reverse the given array.

``````from array import *
arr = array("i",[1,2,3])
arr.reverse()
print(arr)``````

also, the above code can be rewritten with logic by using

``````from array import *
arr1 = array("i",[1,2,3])
print(arr1[::-1])``````

### buffer_info()

Used to find the memory address and the length of the given array

``````from array import *
arr = array("i",[1,2,3])
print(arr.buffer_info())``````

### extend()

To add another array to the end of the main array we can use extend.

``````from array import *
arr1 = array("i",[1,2,3])
arr2 = array("i",[4,5,6])
arr1.extend(arr2)
print(arr1)``````

Note the point that only the same kinds of arrays can be extended as we know that arrays are made of the same type

### itemsize()

Used to find the number of bites of the array

``````from array import *
arr = array("i",[1,2,3])
print (arr.itemsize)``````

### fromlist()

Used to append a list in an array. The output type is an array

``````from array import *
arr1 = array("i",[1,2,3])
li =[4,5,6]
arr1.fromlist(li)
print(arr1)``````

Even here we have to use the same kind of array or python throws an error

## tolist()

This is used to convert an array into a list.

``````from array import *
arr1 = array("i",[1,2,3])
li = arr1.tolist()
print(li,type(li))``````

The output type of the li is a list.

Now let’s talk about arrays in C

## Arrays in C

Even in C arrays are similar to what we’ve seen in python They have the same properties and they are of fixed size. Now we’ll see more about how to declare arrays and how to use them in programs

## Declaring an array

In C we need to give the data type of the elements to be stored in the given array. Let’s take an example if we need to store 2,3,25,67 and 190 in an array named num which can be declared by

``````#include <stdio.h>

int main()
{
int arr={1,2,3,4,5}; // Example for declaring an array
return 0;
}``````

From the above example, we can infer that to create an array we need to give the data type that is int in this case and the name of the array which is num, and the size of the same which is 5 and we’ll be giving the array we need within a curly brackets

## Indexing in array

In C we can easily access arrays with their indices. This is the reason why arrays are used in C and many other programming languages. Let’s see an example below

``````#include <stdio.h>

int main()
{
int arr={1,2,3,4,5};
printf("%d",arr); //arr prints the element at index 0 which is 1 here
return 0;
}``````

Similarly, we can print any element we want.

## Traversing through an array

To traverse through an array we can use the simple for loop.

``````#include <stdio.h>

int main()
{
int arr={1,2,3,4,5};
for (int i=0;i<5;i++) {
printf("%d\n",arr[i]); // \n means to go to the next line
}
return 0;
}``````

The above code prints the elements of the array we declared as arr.

Now we shall see a program to add each element of an array by 2

``````#include <stdio.h>

int main()
{
int arr={1,2,3,4,5};
for (int i=0;i<5;i++) {
arr[i]=arr[i]+2;
}
printf("new array is");
for (int i=0;i<5;i++) {
printf("%d\n",arr[i]);
}
return 0;
}``````

In the above code, I am first declaring an array arr and then using for loop and indexing to add each element by 2. I am using for loop again to print the new element of arr.

## Passing array in a user-defined function

We can pass an array into a function in the following ways:

### sized

If you know the size of the array you are passing we can use this method.

``````#include <stdio.h>

void printArray(int arr) {

for (int i=0; i < 10; i++) {
printf("%d\n ", arr[i]);
}
return 0;
}

void main() {
int arr = {1,2,3,4,5,6,7,8,9,10};
printArray(arr);
return 0;
}``````

### unsized

If the size of an array is unknown then this method comes in handy for you

``````#include <stdio.h>

void printArray(int arr[]) {

for (int i=0; i < 10; i++) {
printf("%d\n ", arr[i]);
}
return 0;
}

void main() {
int arr = {1,2,3,4,5,6,7,8,9,10};
printArray(arr);
return 0;
}``````

### Pointers

We can also pass function parameters as pointer array

``````#include <stdio.h>

void printArray(int *arr) { // the *arr refers to the memory location of the array arr

for (int i=0; i < 10; i++) {
printf("%d\n ", arr[i]);
}
return 0;
}

void main() {
int arr = {1,2,3,4,5,6,7,8,9,10};
printArray(arr);
return 0;
}``````

now let’s do another example about passing an array in a function

``````#include<stdio.h>

void reverseArray(int arr[], int start, int end) {
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}

void printArray(int *arr, int size) {

for (int i=0; i < size; i++) {
printf("%d\n ", arr[i]);
}
}

int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr);
printArray(arr, n);
reverseArray(arr, 0, n-1);
printf("Reversed array is \n");
printArray(arr, n);
return 0;
}
``````

The above code is about reversing a given array. When we pass any array it’ll reverse the array and print that array.

## Returning an Array

Yes, it is possible to return an array from a function and use it in the main program let’s see an example of this case. We’ll be writing a program to get an array as input from the user and display the same

``````#include <stdio.h>
int *getarray(int *a)
{

printf("Enter the elements in an array : ");
for(int i=0;i<5;i++)
{
scanf("%d", &a[i]);
}
return a;
}
int main()
{
int *n;
int a;
n=getarray(a);
printf("\nElements of array are :");
for(int i=0;i<5;i++)
{
printf("%d", n[i]);
}
return 0;
} ``````

## Pointer and pointer to an array

A pointer is a variable that points to the memory location of another variable, an array in our case

``````#include <stdio.h>
int main()
{
int var = 10;
printf("var: %d\n", var);

return 0;
}``````

Notice the use of ‘&’ before ‘var’? The ‘&’ points to the variable var’s memory location. Now let’s see an example of array pointers and how to use them.

``````#include <stdio.h>
int main() {
int x = {1, 2, 3, 4, 5};
int* ptr;
ptr = &x;
printf("*ptr = %d \n", *ptr);
printf("*(ptr+1) = %d \n", *(ptr+1));
printf("*(ptr-1) = %d", *(ptr-1));
return 0;
}``````

That’s it for today. And if you are on your way to becoming a Linux Geek, you might find our site really helpful. Hit this link for more Linux related posts Check it out, it’s Simply the Best Code.