C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements for the same data type.
single-dimension
Declaring Arrays:
To declare an array in C++, the programmer have to specifies the type of the elements and the number of elements ( array size) :
type arrayName [ arraySize ];
example :
initialization array
int score[5];
initialization array with assignment
int score[5] = {80,70, 90, 99, 100};
int score[] = {80,70, 90, 99, 100};
score[4] = 95;
it will assign the value to the array at the index 4 to 95 so the new values of array are {80,95, 90, 99, 100}
programmer can also get a value from array in any index
int myscore = score[4];
// myscore = 100
Example :
#include <iostream>
using namespace std;
int main ()
{
int arr[ 10 ]; // arr is an array of 10 integers
// initialize elements of array arr to 0
for ( int i = 0; i < 10; i++ )
{
arr[ i ] = i * 10 +i; // set element at location i to i * 10+i
}
// output each array element's value
for ( int j = 0; j < 10; j++ )
{
cout << "array at index "<<j <<" = "<< arr[ j ] << endl;
}
return 0;
}
Multi-dimensional arrays
example array 2 dimensional :
#include <iostream>
using namespace std;
int main ()
{
int arr[ 10 ][5]; // arr is an array of integers for 10 rows and 5 cols
// initialize elements of array arr to 0
for ( int i = 0; i < 10; i++ )
{
for(int j=0;j<5;j++){
arr[ i ][j] = i * 10 +j; // set element at location i to i * 10+i
}
}
// output each array element's value
cout<<"j ->\t0\t1\t2\t3\t4"<<endl;
cout<< "k|"<<endl;
for ( int j = 0; j < 10; j++ )
{
cout <<j<<"\t";
for(int k=0;k<5;k++){
cout << arr[ j ][k] <<"\t";
}
cout<<endl;
}
return 0;
}