Array Data Structure

In computer science array is an linear data structure that are store similar type of data element. When creating a array element, then the number of element is decide the size of an array. Memory of array are allocated in consecutive sequence. So we can access the array element by specific index. that are very easy to use and modify array element, their operation are tack constant time O(1).

Array Data Structure

Array are consist at least minimum one element, so there is not possible to create empty array in c and c++ programming language. That is very useful data structure, because that are used to implements strings and list data type. Size of element is depends which type of data it will stored. that means define data type of array is responsible to decide size of element in array. So we can easily find out total size of array multiply by number of element. Total size of array is allocated in form of bytes. When create an array after that their not possible to modify it size. So the role of array in programming language are used to create similar type of multiple variable.

Type of Arrays

Array is arrangement of similar type of element so we can define single and multidimensional array depending our requirement.

1D Array (Single Dimensional)

There is simplest form of array. There is have one dimensional size. Declaration array we are need 2 main values, first one its data type and second one is its size.

data_type array_name[size];

Data type is primitive and user defined data type c and c++ programming language. and name of array is user defined. and size is positive integer value.for example.

int data[12];//data is an array of 12 integers element.
float amounts[5];//amounts is an array of 5 elements

In this example there are define two different arrays. data is an array of integer and amounts is an array of float data type. Assign of array element is very simple.

int data[5]={1,2,3,4,5}; //assign array element
//array of 5 element
int element[]={1,2,3,4,5}; 

Note that when initialize and declare of array is in a single statement of 1D array. then size of array are not compulsory.

This case are normally used when array are have initial value. in other case we can assign individual array element in following manner.

int data[5]; 
//Assign array element
data[0]=10;//0 is index
data[1]=20;//1 is index
data[2]=30;//2 is index
data[3]=40;//3 is index
data[4]=50;//4 is index

Implement 1D Array

In this section we are learning about how to create static and dynamic array. static means there size is predefined and their size are fixed. dynamic allocation of array that means creating of array in run time. In this case user are decided to how many number of element in required of array. first view static allocation of array.

//C Program to Create array
#include<stdio.h>
int main(){
  /*When declaring and assigned element 
  of 1d array then size is not compulsory*/
  int data[]={1,2,3,4,5};//array of 5 elements
  
  //get size of 1d array
  int size=(sizeof(data))/sizeof(data[0]);
  
  int index=0;
  for(index;index<size;index++){
    //display element
    printf("  %d",data[index]); 
  }
}

Output

  1  2  3  4  5
C 1D Array

In this example there are not mention the size of array. but in this case compiler is capable to allocates the size of array of respective number of elements.

//C++ Basic array example
#include<iostream>
using namespace std;

int main(){
  //define array element
  int data[]={11,22,33,44};
  //get size of array
  int size=sizeof(data)/sizeof(data[0]);
  for(int index=0;index<size;index++){
    //dispaly array data element
    cout<<"  "<<data[index];
  }
}

Output

  11  22  33  44
//java Array Example 
public class Array{
  public static void main(String[] args) {
    //Create array of 5 integer elements
    int data[]={1,2,3,4,5}; //assigne element
    int size=data.length; //find length of array
    for(int index=0;index<size;index++){
      //Display array element
      System.out.print(" "+data[index]);
    }
  }
}

Output

 1 2 3 4 5
#Program for implement array in python
import array as data
#create a array
record=data.array("i",[1,2,3,4,5]); #i int data type
# i : signed int data type
# also used other data like
# f: float data type
# d: double data type
# b: signed char
# L: unsigned long
# I: unsigned int
# H: signed short int
print(type(record)) #display its type
print(record)#display array element

print("index 0 :",record[0]) #first index
print("index 1 :",record[-1]) #Last index

#update array index value
record[0]=90
print("index 0 :",record[0]) #first index

Output

<type 'array.array'>
array('i', [1, 2, 3, 4, 5])
('index 0 :', 1)
('index 1 :', 5)
('index 0 :', 90)
C 1D Array

View of this image array is an python modules and (i) is indicates that array will be storing the element of signed-integer.

//C# Simple program to Create array
//End display it's Elements
using System;
class Program{
  static void Main(string[] args){
    int []data={1,2,3,4,5};
    int size=data.Length;
    for(int index=0;index<size;index++){
      Console.Write(" "+data[index]);
    }
  }
}

Output

1 2 3 4 5

Dynamic allocation of array is depending of memory allocation of array element at run time. c and c++ programming language this memory is allocated on heap area.

//C Program to Create Dynamic array
#include<stdio.h>
#include<stdlib.h>
//Function Prototype
void create();
void get_data();
void set_data();
void free_data();

//global variables
int *data;//default NULL address
int size=0;

//create dynamic array
void create(int capacity){
  if(capacity<1){
    printf("Invalid size\n");
  }else{
    size=capacity;
    //Dynamic array
    data=(int*)malloc(sizeof(int)*size);
  }
}
void set_data(){
  if(size>0 && data!=NULL){
    int index=0;
    for(index;index<size;index++){
      //display element
      data[index]=size*(index+1);
    }
  }else{
    printf("\n No element");
  }
}
//display element
void get_data(){
  if(size>0 && data!=NULL){
    int index=0;
    for(index;index<size;index++){
      //display element
      printf("  %d",data[index]); 
    }
  }else{
    printf("\n No element");
  }
}
//free element of array
void free_data(){
  if(data!=NULL){
    free(data);
    data=NULL;
    size=0;
  }
}
int main(){
  create(4);
  set_data();
  get_data();
  free_data();
  get_data();
}

Output

  4  8  12  16
 No element
//C++ Create Dynamic array example
#include<iostream>
using namespace std;
class Array{
private:  
  //use pointer to store 
  //array base address
  int *element; 
  int size;
public:
  //Member function of class
  Array(int);
  void setValue();
  void getValue();
  void freeElement();
};
//create array
Array::Array(int size){
    // Assuming that size is  
    // Greater than 0
    this->size=size;
    element=new int [size];
    if(element==NULL){
      //Special case when not create
      //dynamic memory
      cout<<"Memory overflow"<<endl;
      
    }
}
void Array:: setValue(){
  if(size >0 && element!=NULL){
   cout<<"Dispaly Array Element"<<endl;
    //set array value
    for(int index=0;index<size;index++){
      element[index]=(index+1)*2; 
    }
  }else{
    cout<<"Empty Array"<<endl;
  }
}
void Array::getValue(){
  if(size >0 && element!=NULL){
    //get array value
    for(int index=0;index<size;index++){
      cout<<element[index]<<endl;
    }
  }else{
    cout<<"Empty Array"<<endl;
  }
}
void Array::freeElement(){
  if(element!=NULL){
    delete element; //remove element
    element=NULL; 
  }
}
int main(){
  
  Array record(7);
  record.setValue();
  record.getValue();

  Array info(5);
  info.setValue();
  info.getValue();

  //after that free array elements
  record.freeElement();
  info.freeElement();
  return 0;
}

Output

Dispaly Array Element
2
4
6
8
10
12
14
Dispaly Array Element
2
4
6
8
10
//java Create Dynamic Array 
public class MyArray{
  private int []data; 
  private int size;
  MyArray(int size){
    //Assume size is not less then 1
    this.size=size;
    this.data=new int[size];
  }
  public void getData(){
    if(size>0 && data!=null){
      System.out.print("\n Array Data ");
      for(int index=0;index<size;index++){
        System.out.print(" "+data[index]);
      }
    }
  }
  public void setData(){
    if(size>0 && data!=null){
      for(int index=0;index<size;index++){
        data[index]=(size)*(index+1);
      }
    }
  }
  public void freeArray(){
    if(data!=null) {
      data=null;
    }
  }
  public static void main(String[] args) {
    MyArray record=new MyArray(5);
    MyArray info=new MyArray(10);
    record.setData();
    info.setData();
    record.getData();
    info.getData();
    record.freeArray();
    info.freeArray();
  }
}
 Array Data  5 10 15 20 25
 Array Data  10 20 30 40 50 60 70 80 90 100
Java 1d dynamic array
#Program for implement dynamic array in python
import array as item #for array

class MyArray:
  def __init__(self,size):
    #set array element form 0 to given size
    #this array is store only integer value
    self.data=item.array("i",range(0,size)) #i for integer
  
  def printArray(self):
    print("\nArray Data")
    for i in self.data:
      print(i), #display array element

def main():
  size=3
  record=MyArray(size) 
  record.printArray()
  info=MyArray(size*2)
  info.printArray()
 

if __name__ == '__main__':
  main()

Output

Array Data
0 1 2
Array Data
0 1 2 3 4 5
Array implementation

In this scenario visualize the working of python array implementation, Here Myarray is user defined class and this program is import array is an module.

//C# Simple program to Create Dynamic array
using System;
class MyArray{
  //empty array
  public int[] data= new int[] {};
  public int size;
  public MyArray(int size){
    //Assuming that size is greater than 0
    //if Not then set 0
    //careful to handle unwanted exception
    if(size<0) size=0;
    this.size=size;
    
    this.data=new int[size];
  }
  //Set array elements
  public void setData(){
    if(size>0 && data.Length>0){
      for(int index=0;index<size;index++){
        data[index]=(1+index)*size;
      }
    }else{
      Console.WriteLine("\r\nEmpty Array");
    }
  }
  //Display array elements
  public void getData(){
    if(size>0 && data.Length>0){
      Console.WriteLine("Array Contain {0} Elements",size);
      for(int index=0;index<size;index++){
        Console.Write(" "+data[index]);
      }
    }else{
      //new line : Environment.NewLine
      //new line :\r\n windows
      //new line \n Unix
      Console.WriteLine("\r\nEmpty Array");
    }
  }
  public void freeArray(){
    //Not possible to delete array in c#
    //so set as an empty array
    data=new int[0] {};//set as an empty array
  }
}
class Program{
  
  static void Main(string[] args){
    //create object
    MyArray info=new MyArray(4);
    info.setData();
    info.getData();
    info.freeArray();
    info.getData();

    MyArray item=new MyArray(7);
    item.setData();
    item.getData();
    item.freeArray();
  }
}

Output

Array Contain 4 Elements
 4 8 12 16
Empty Array
Array Contain 7 Elements
 7 14 21 28 35 42 49

Muti-Dimensional Array

Multidimensional array is combination of row and column. there are normally used to represent data in matrix or table format.there is syntax of declaration as follows.

data_type array_name[size][size][size]..;

for example, created a simple 2D array of 3 rows and 5 column of integers.

int matrix[3][5];

There is very similar to one dimensional array. there are include one extra subscript and size. This array are capable to stores total (3X4)=12 elements. There is can possible to initialize the array elements in various way. there are given few examples.

int matrix[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};

In this example matrix array is contains 12 element. there are given in from of 1d array.

In this example matrix array is contains 12 element. there are given in the form of 1d array. but interesting that there is an 2d array, so we cannot used 2d array elements as form of 1d. for example matrix[10];this is printed of garbage value. should using of array element by particular dimension of array. another form of array initialization.

int matrix[3][4]={{1,2,3,4},
 {5,6,7,8},
 {9,10,11,12}
};

inner curly braces {} are used to define row in two dimensional array. and every element is separate by comma. And third method is simply assign the value of particular individual element by array index.

int matrix[3][4];
matrix[0][0]=1;
matrix[0][1]=2;
matrix[0][2]=3;
matrix[0][3]=4;
matrix[1][0]=5;
matrix[1][1]=6;
matrix[1][2]=7;
matrix[1][3]=8;
matrix[2][0]=9;
matrix[2][1]=10;
matrix[2][2]=11;
matrix[2][3]=12;

Element of array are used by its index value. first element of index is started of zero. And the name of array is provide the base address. so combination of base address and index get proper specific index element.

//C dynamic 2d array
#include<stdio.h>
#include<stdlib.h>
int **data;
void setData(int rows,int cols){
  if(data!=NULL){
    int i=0,j=0;
    for(i;i<rows;i++){
      for(j=0;j<cols;j++){
        //assign array element
        data[i][j]=(i+1)*(j+1);
      }
    }
  }
}
void printData(int rows,int cols){
  if(data!=NULL){
    int i=0,j=0;
    for(i;i<rows;i++){
      for(j=0;j<cols;j++){
        //print array element
        printf("  %d",data[i][j]);
      }
      printf("\n");
    }
  }
}
int main(){
  int rows=3;
  int cols=4;
  //Create rpw 
  data=(int**)malloc(sizeof(int)*rows);
  if(*data!=NULL){
    int index=0;
    for(index;index<rows;index++){
      
      //assign cols
      data[index]=(int*)malloc(sizeof(int)*cols);
      if(data[index]==NULL){
        printf("Memory overflow\n");
        break;
      }
    }
    //assuming that there is no 
    //memory overflow problem
    setData(rows,cols);
    printData(rows,cols);
  }else{
    printf("Memory overflow\n");
  }

  return 0;
}

Output

  1  2  3  4
  2  4  6  8
  3  6  9  12
//C++ Create 2d Dynamic Array
#include<iostream>
using namespace std;
class DynamicArray{
  int rows;
  int cols;
  int **data;
public:
  DynamicArray(int,int);
  void printData();
  void setData();
  void freeElement();

};
DynamicArray::DynamicArray(int rows,int cols){
  //set values
  this->rows=rows;
  this->cols=cols;
  data=new int*[rows];
  if(data!=NULL){
    for (int i = 0; i < rows; ++i){
      data[i]=new int[cols];
    }
  }
}
void DynamicArray::setData(){
  if(data!=NULL){
    for(int i=0;i<rows;i++){
      for(int j=0;j<cols;j++){
        //set values of array elements
        data[i][j]=(i+1)*(j+1);//set values
      }
    }
  }
}
void DynamicArray::printData(){
  if(data!=NULL){
    for(int i=0;i<rows;i++){
      for(int j=0;j<cols;j++){
        
        printf(" %d",data[i][j]);
      }
      printf("\n");
    }
  }
}
void DynamicArray::freeElement(){
  if(data!=NULL){
    int *temp=NULL;
    for(int index=0;index<rows;index++){
      temp=data[index];
      data[index]=NULL;
      delete []temp;
      temp=NULL;
    }
    
    delete []data;
    data=NULL;
  }
}
int main(){
  DynamicArray record(3,4);
  record.setData();
  record.printData();
  record.freeElement();
  return 0;
}

Output

 1 2 3 4
 2 4 6 8
 3 6 9 12
//C# Create 2D Array
using System;

class MultiArray{
  private int[,]data;
  public MultiArray(int rows,int cols){
    //Create 2d Array
    data=new int[rows,cols];
  }
  
  public void setValue(){

    int rows= data.GetLength(0);//get number of rows
    int cols= data.GetLength(1);//get number of cols
    for(int r=0;r<rows;r++){

      for(int c=0;c<cols;c++){
        data[r,c]=(r+1)*(c+1);//set value
      }
    }
    
  }
  public void printArray(){

    int rows= data.GetLength(0);//get number of rows
    int cols= data.GetLength(1);//get number of cols
    for(int r=0;r<rows;r++){

      for(int c=0;c<cols;c++){
        Console.Write(" {0}",data[r,c]);
      }
      //new line
      Console.Write("\n");//use \r\n in this not work
    }
  }
}
class Program{
  static void Main(string[] args){
    MultiArray twoDimensional=new MultiArray(3,4);
    twoDimensional.setValue();
    twoDimensional.printArray();
  }
}

Output

 1 2 3 4
 2 4 6 8
 3 6 9 12
//Java implemented 2D array
public class MutiArray{
  private int [][]data; 
  MutiArray(int rows,int cols){
    data=new int[rows][cols];

  }
  public void setData(){
    //get length of 2d array
    int rowSize=data.length; //get row size
    int colSize=data[0].length; //get col size
    
    for(int rows=0;rows<rowSize;rows++){
      for(int cols=0;cols<colSize;cols++){
        //set value to array
        data[rows][cols]=(cols+1)*(rows+1);
      }
    }
  }
  public void printArray(){
    //get length of 2d array
    int rowSize=data.length; //get row size
    int colSize=data[0].length; //get col size
      System.out.print("\n Array of rows "+rowSize+" cols "+colSize+"\n");
    for(int rows=0;rows<rowSize;rows++){
      for(int cols=0;cols<colSize;cols++){
        //set value to array
        System.out.print("  "+data[rows][cols]);
      }
      System.out.print("\n");
    }
  }
  public void freeArray(){
    if(data!=null){
      data=null;
    }
  }
  public static void main(String[] args) {
    MutiArray record=new MutiArray(4,5);
    record.setData();
    record.printArray();
    record.freeArray();
  }
}

Output

 Array of rows 4 cols 5
  1  2  3  4  5
  2  4  6  8  10
  3  6  9  12  15
  4  8  12  16  20
Java 2d Array implementation

In this given example data is an array variable which are pointed to an array. and this array is stores the address of other reference of array. so we are capable to used of data variable of element of reference array.

#Python implement 2d array
import array as data
rows, cols = 4, 5
index=1
array2d = [data.array('i', (range(0,cols))) for j in range(rows)]
print(array2d)
print("Array Data display using for loop")
#display array element using for loop
for rowData in array2d:
  for info in rowData:
    print("  {0}".format(info)),
  print("\n") 

print("Array Data display using while loop")
#display array element using while loop
#first get length of rows and cols
rowNum=len(array2d)
colNum=len(array2d[0])
rows=0
#display
while(rows<rowNum):
  cols=0
  while (cols<colNum):
    print("  {0}".format(array2d[rows][cols])),
    cols+=1
  print("\n")  
  rows+=1
[array('i', [0, 1, 2, 3, 4]), array('i', [0, 1, 2, 3, 4]), array('i', [0, 1, 2, 3, 4]), array('i', [0, 1, 2, 3, 4])]
Array Data display using for loop
  0   1   2   3   4

  0   1   2   3   4

  0   1   2   3   4

  0   1   2   3   4

Array Data display using while loop
  0   1   2   3   4

  0   1   2   3   4

  0   1   2   3   4

  0   1   2   3   4
2d Array implementation

Python array module is not used to store the references. to first created a list which are store the references of array. this are show in above image.

Application

There are various applications of array data structures. Array are used to implement string data type in most of programming languages. And stack and queue data structure can be implemented by help of array. array is a combination of key and value pair, hash table are also internally used array.



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved