C++ Array

Array


  • Array is a collection of homogeneous elements having same data type and same size.
  • Elements of array are stored in consecutive memory locations.
  • Array Elements are referenced by a single name.
  • Array elements are processed using index of array elements.
  • Index is always integer value.
  • Array index starts from zero.

Types Of Array:


  • One Dimensional Array
  • Multi Dimensional Array

One Dimensional Array


Use one subscript to specify the of array.

Syntax


 Array_name[size];


Here, Type refers to data type.
Array_name specifies name of array.
[ ] brackets used to declare size of array.
size specifies the maximum number of values

Program to assign and display values in one dimensional array.



#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int a[4];
    a[0]=5;
    a[1]=6;
    a[2]=3;
    a[3]=9;
    cout<<"\n"<<a[0];
    cout<<"\n"<<a[1];
    cout<<"\n"<<a[2];
    cout<<"\n"<<a[3];
    getch();
}


Output


 a[0]=5
 a[1]=6
 a[2]=3
 a[3]=9

In above,
Declared array size 4
Array contains 4 values.
First element is a[0]
0,1,2,3 are index of array element.
last index of array element is one less than size of array.

Program to initialize one dimensional array and display with for loop.



#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int a[4]={8,4,9,6};
    int i;
    cout<<"\n Array Elements =";
    for(i=0;i<=3;i++){
         cout<<"\n"<<a[i];
    }
    getch();
}


Output


8
4
9
6

Program to read and display one dimensional array.



#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int a[4];
    int i;
    cout<<"\nEnter Array Elements =";
    for(i=0;i<=3;i++){
         cin>>a[i];
    }
    cout<<"\nArray Elements =";
    for(i=0;i<=3;i++){
         cout<<"\n"<<a[i];
    }
    getch();
}


Output


Enter Array Elements= 7
4
8
12
Array Elements =
7
4
8
12

Back To Top