Arrays in c++
Array is a collection of similar data elements. It has a sequential storage starting from location 0 to n. A single dimensional array is explained here.
Here is the
syntax of array
Declaration:
Datatype
variable_name[size];
Eg : int
a[10];
How to
get inputs for array?
You can
directly assign values as input.
a[5]={1,2,3,4,5};
using a for
loop, you can get it from the user,
eg:
int a[5];
for(i=0;i<n;i++)
{
cin>>a[i];
}
How to
access the elements?
Element starts from 0th location to
n.
Eg: a[0] is
the first element. a[1] is the next element. likewise, its going on.
Let us
create a c++ program to display ‘n’ number of elements in an array.
C++
Program to display the array elements:
#include
<iostream>
using
namespace std;
int main()
{
int x[10],n,i;
cout<<"Enter the n
value:"<<endl;
cin>>n;
cout<<"Enter the
elements:"<<endl;
for(i=0;i<n;i++)
{
cin>>x[i];
}
cout<<"The elements
are:"<<endl;
for(i=0;i<n;i++)
{
cout<<x[i]<<endl;
}
return 0;
}
Output:
Enter the n
value:
5
Enter the
elements:
45
56
67
78
89
The
elements are:
45
56
67
78
89
Next, the display
a particular array element are shown as follows.
#include
<iostream>
using
namespace std;
int main()
{
int x[5]= {1,2,3,4,5},i;
cout<<"The elements
are:"<<endl;
for(i=0;i<5;i++)
{
cout<<x[i]<<endl;
}
//print a particular element.
cout<<"The third element of the
array is:"<<x[2]<<endl;
//print a last element
cout<<"The last element of the
array is:"<<x[4]<<endl;
return 0;
}
Output:
The
elements are:
1
2
3
4
5
The third
element of the array is:3
The last
element of the array is:5
Hope, these c++ programs described the array and its elements. Try these programs. Keep coding!!!!
Comments
Post a Comment