Array in C++

Array is continous, homogenous data structure identifed by single identifier. Array is used when there is large data set for processing. Array occupied continous memory locations that make its access more efficient. It is good alternative for huge no of variables.

Structure of Array

Arrays used index value to access memory locations. Array index in C++ starts from 0. Array provides both acessing mechanisms as.

  • Sequential

  • Random

Array Declaration

Array declaration involves specification of data type, name and size of array.

Syntax

data_type identifier [ size ] ;

Where:

  • Data_type may be any standard or user defined data type.
  • Identifier is valid name of array which must follow the variable naming rules.
  • Size is a non negative integer value.

Example

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	
	// Declaration of Array.
	int arr[5];  // 5 is size of array.
	
	// Index of first element is 0.
	arr[0] = 10; // assigning value to first element.
	
	cout<<"Value At First Index : "<<arr[0];
	
	return 0;
}

Array Initialization

Array initialization is the process of specifying array name, type, size and values. Similar to variable Initialization, array Initialization also specify set of values to entire array elements.

Syntax

data_type identifier [ size ] = { values };

Example

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	
	// Initialization of Array.
	int arr[5] = { 10,20,30,40,50 };  // 5 is size of array.
	
	// Index of first element is 0.
	// assigning value to first element.
	cout<<"Value At First Index : "<<arr[0];
	
	return 0;
}

Types of Arrays

There are two type of arrays used in C++.

  1. Linear/one dimensional
  2. Multi dimensional

Linear array

Such type of array in which single script is used is called linear or single dimensional array. This array is declared using single size/subsript enclosed in square brackets. These arrays may also be of any data type.

Example

Some examples of linear arrays in C++ are as follows.

int ar[10];
float arrF[5];

Muti Dimensional Array:

Such type of arrays in which more than on scripts are used as index of elements are called multi-dimensional arrays. 2D array is the most common type of multi-dimensional array used in algorithms.

Example

Some examples of multi dimensional arrays having more than one scripts are as follows.

int ar[5][6];  // 2D array
float arrF[3][2][2];  // 3D array

 

Comments
Login to TRACK of Comments.