Saturday, 18 April 2020

C++ Array


Array:-       
               An Array is a collection of multiple values of same type at a contiguous memory locations. In an array we can collect the data. For example if we need to store a class data then we can use an array. If there are 26 students in mechanical branch and we have to store marks of these students then we can create an array of size 26 of same data type i.e int, float, double, char etc.

Declaring Array:-    An array can be declare as follow  :-
  
return type arrayname [aray size];

Int mech[26];

Here Data type :- int
         Array name:- mech
         Size:-26
Here we declare an array of name mech where data type is of integer (int ) and total size is 26.

Initialization of array:- Array can be initialize during declaration of array (without loop) as follow:-
  
Int mech[5]={20,40,50,70,80};

In an array data can be store through an index ,according this first element start from 0 to n-1 if the total size is n.
mech[0]= 20
mech[1]= 40
mech[2]= 50
mech[3]= 70
mech[4]= 80

Accessing array element:-

As we know array elements can be access through index.
If we need to input the data in an array ( int mech[5] ) then there is a loop  :-

for(i=0;i<=4;i++)
{
cin>>mech[i];
}

If we need to display the data in an array ( int mech[5] ) then there is another loop  :-

for(i=0;i<=4;i++)
{
cout>>mech[i];
}

In an array we can also input and output or display the data individually. For example

cin>>mech[2]

that mean we are going to input the value in 3rd element of array mech.

cout<<mech[4]

that mean we are displaying the data of 5th element.   


No comments:

Post a Comment