Arrays in C++ work much like Arrays in Java. They are 0 indexed (meaning their index values start at 0). The following are all ways we can create an integer array in C++

computer science

Description

How to create arrays in C++

 

Arrays in C++ work much like Arrays in Java. They are 0 indexed (meaning their index values start at 0). The following are all ways we can create an integer array in C++

 

int x[10]; //creates an integer array of 10 elements. None of these elements are initialized

 

int x[]={3,4,5}; //creates an integer array of 3 elements with x[0]=3,x[1]=4, x[2]=5. Note that we don't have to specify the size

 

You can also create arrays of doubles and any of your other types you have encountered thus far.

 

A 2 dimensional array can be created as follows

int x[2][4]; //a 2D array of 8 elements (2 in one direction, 4 in the other)

 

You can create a 3D array in the same way.

Finding the value at a given index in C++

Same as java!

cout<<x[3]; //will give you the 3rd index, 4th value of the x array.

 

Do not overrun the end of your array by putting an index value that's bigger than the length of the array. In C++ this could lead to a segmentation fault or, the program may run but do something funny. The result of overrunning the end of an array is undetermined.

Using For Loops To Cycle through an array

The following code initializes all the elements of an array to 0. This should be review. Note that we put the length of the array as the bounds of the for loop

int x[10];

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

{

     x[10]=0;

}

 

Instruction Files

Related Questions in computer science category