C++ one dimensional Array

The one dimensional array is the simplest form of the array. And is used for the multiple values in a single variable.

Declaration syntax:   data-type  array-name[ ];

e.g:      int student[ ];

giving memory: After declaration of array we have to create it into the memory so the ‘new’ keyword is used for this.

Syntax:            array-name = new data-type[size];

e.g       student = new int[20];

in the above example we have array with the name of student and the size is 20. That means we can store 20 values in this array. And the computer reserves 20 locations for the array. And ‘new’ operator is used to assign memory to these 20 locations.

Representation of the array values and can be assigned as follows:

student[0]=1001

student[1]=1002

student[2]=1003

student[3]=1004

.

.

.

student[19]=1020

 

 

Initialization:

 

a.      Compile time: the initialization is the same as we initialize the variables, but the difference only we gives the list of values. As follows:

Declaration syntax:   data-type array-name[size]={list of values};

e.g:  int student[5]={1,2,3};

in the above example the values 1,2,3 are initialized to array starting from 0. And the rest of locations are initialized to 0 automatically.

 

b.      Run time: we can assign the values with the loop.

For e.g:

Initialize the values of array:

e.g:

for(i=0;i<=10;i++)

{

If(i>5)

number[i]  = 6;

else

number[i] = 8;

}

 

 

To print the values:

e.g:

for(i=0;i<=10;i++)

{

cout<<I;

}

Leave a Reply

Your email address will not be published. Required fields are marked *