C++ tutorial- Arrays


Arrays in C++ Programming Language

Array is a collection of many values of the same type. The array can be one or multi-dimensional array. Programmers mostly use one and two-dimensional arrays.

One-Dimensional Array

-Declaring one-dimensional array

To declare a one-dimensional array in C++, you must write down the data type followed by the name of the array and plain brackets [].
Example
      int i[];

To specify the size of array, you need to set it in plain brackets [] as below.
      int i[5];
 

-Initializing array

To assign values to the array, you can write those values as below.
      int i[]= {1, 2, 3, 4, 5};//The array got values
or

    int i[5];
      i[0]=1;
      i[1]=2;
      i[2]=3;
      i[3]=4;
      i[4]=5;
 
Note: The start index of the array is 0 and the last index is equal to its size subtracted by 1.

-Accessing elements of an array

You can access the elements of array by specifying their indexes.

Example:

   int i[5];
      i[0]=1; //assign values to the array
      i[1]=2;
      i[2]=3;
      i[3]=4;
      i[4]=5;
      int j;
      for(j=0;j<5;j++) cout<<i[j]<<"\t";//accessing values from the array
    
   }
}

Two-Dimensional Array

Two-dimensional array store values in the form of table. The first dimension of the array is row and the second dimension is column. To create and use a two-dimensional array, you will need to specify the number of rows and columns in plain brackets []. The table below is an example of how values are stored in a two-dimensional array.

Index 

0

1

2

0


1

2

3

1


4

5

6

2


7

8

9


Example:

int x[5][5];
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
  if(i==j) x[i][j]=0;
  else if(i>j) x[i][j]=-1;
  else x[i][j]=1;
}
for(int i=0;i<5;i++){
for(int j=0;j<5;j++)
  cout<<x[i][j]<<"\t";
  cout<<"\n";
}

two dimensioanl array


Comments

Troy comment

 Troy

for more C++, C exercises,
please visit http://ccphplusplus.blogspot.com/


2015-05-26



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.