How To Use Arrays in C++

 How To Use Arrays in C++

This Blog will go over One-Dimensional Arrays and Two-Dimensional Arrays, Arrays are a collection of elements that are the same data type that are stored in a special variable, each one of the elements that are a part of the collection can be individually referenced or used with the use of an index identifier. The user is the one to specify the size and contents of an array. Arrays are almost like lists, for example an array can be used to store a list of names of people attending a course or the amount of rainfall in a week.
Below is a visual example of an array:


2D Arrays are basically arrays within arrays, the data is structured in matrices or rows and columns, but the values are still stored linearly within the memory. 2D Arrays are useful for when you want to compartmentalize your data.


When specifying array values, it is important to note that arrays start at 0 so if you were to give your array a size of five and assign values to each array index you will have to stop at index 4 otherwise you will go over the memory capacity and you will receive an error.

Code Example:

        int myArray[5]; //Array size of 5
int my2DArray[3][3]; //Array size of 9 - 3 columns and 3 rows

        /*Values assigned to One Dimensional Array*/
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

         /*Values assigned to Two Dimensional Array*/
my2DArray[0][0] = 2;
my2DArray[0][1] = 4;
my2DArray[0][2] = 6;
my2DArray[1][0] = 8;
my2DArray[1][1] = 10;
my2DArray[1][2] = 12;
my2DArray[2][0] = 14;
my2DArray[2][1] = 16;
my2DArray[2][2] = 18;



OUTPUT:

                                        











Comments

Popular posts from this blog

How to Open a C++ Project on VS22 and get started

How To Write to File on C++