Loading....
Coupon Accepted Successfully!

 

Types of Arrays

  • Arrays are of different types.
  • They are
    • One dimensional array
    • Two dimensional array
    • Multi dimensional array

One dimensional Array

  • This array type is the simplest format among the arrays
  • The array is given a name and its elements are referred to by their subscript or index.
  • An array must be defined before it can be used to store the information.
  • General format for one dimensional array
Type array_name[size];
Where
Type - datatype
Array_name - name of the array
Size - index value
  • For example
int students[50];
Note: - Single dimensional array is also called as one dimensional array. Array element should always be an integer value.

Program

#include<iostream.h>

void main()

{

double price[20], sum, avg, prod;

sum = avg = 0;

prod =1;

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

{

cout <<"enter price for the item"<<i+1<<":";

cin >>price[i];

sum+=price[i];

prod+=price[i];

}

avg=sum/20;

cout<<"sum"<<sum<<endl;

cout<<"product="<<prod<<endl;

cout<<"average="<<avg<<endl;

}

Two dimensional Arrays

  • Two dimensional are a little complicated to use than one dimensional array.
  • It is defined in the same manner as one dimensional array except that a separate pair of square brackets is required for each subscript.
  • A 2D array can be used to store multiple numbers.
  • It is mainly used in matrix calculation.
  • The general format is

Type array_name [row][column];

  • For example

int student[10][20];

Array representation is shown below:
 

0

1

2

3

0

[0][0]

[0][1]

[0][2]

[0][3]

1

[1][0]

[1][1]

[1][2]

[1][3]

2

[2][0]

[2][1]

[2][2]

[2][3]

3

[3][0]

[3][1]

[3][2]

[3][3]

4

[4][0]

[4][1]

[4][2]

[4][3]

  • Initializing an array in two dimension

int x[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
Where a[0][0]=1, a[1][1]=2 and so on...

Program

#include<iostream.h>

Void main()

{

int n[5][5];

int row,col;

for(row=0;row<5;row++)

{

for(col=0;col<5;col++)

{

cout<<"enter the value of row["<<row+1<<"]col["<<col+1<<"]";cin>>n[row][col];

}

}

cout<<" the given array values are "<<endl;

for(row=0;row<5;row++)

for(col=0;col<5;col++)

cout<<"the value of row["<<row+1<<"]col["<<col+1<<"]"<<n[row][col]<<endl1;

}

Multidimensional Array

  • C++ allows storing more than two elements in the array.

  • This type of array is called as multidimensional array.

  • The general format of multidimensional array is

Type array_name[a][a1][a2]............a[n];

  • For example

int matrix[10][10][10];

  • Hence it stores the value in the 3 X 3 matrix format.
Note: A matrix with one row(column) may be viewed as a vector and similarly a vector may be viewed as a matrix with one row(column)




Test Your Skills Now!
Take a Quiz now
Reviewer Name