C++ - Arrays
Arrays are used to store multiple values in a single variable. In C++, all elements of an array must be of same datatype.
Create an Array
It starts with defining the datatype of the array, name of the array followed by size of the array enclosed in square brackets [ ].
Initialize an Array
An array can be initialized by separating it's elements by comma , and enclosing with curly brackets { }.
Please note the following points while working with Arrays:
- Array can be initialized later using index, if it not initialized at the time of declaration.
- If a variable is used for the size of array, then the variable must not be unassigned before declaring the array.
Syntax
//declaring an array of size 3. int MyArray [3]; //array of size 'n'. //'n' must have assigned value before declaration. float MyArray [n]; //declaring and initializing an array of size 3. int MyArray [3] = {10,20,30};
Access element of an Array
An element of an array can be accessed with it's index number. In C++, the index number of an array starts with 0 as shown in the figure below:
The example below describes how to access elements of an array using its index number.
#include <iostream> #include <string> using namespace std; int main (){ //creating an array with 5 elements string weekday[5] = {"MON", "TUE", "WED", "THU", "FRI"}; //accessing the element with index number 4 cout<<weekday[4]; return 0; }
The output of the above code will be:
FRI
Modify elements of an Array
Any element of an array can be changed using its index number and assigning a new value.
#include <iostream> #include <string> using namespace std; int main (){ //creating an array with 5 elements string weekday[5] = {"MON", "TUE", "WED", "THU", "FRI"}; //modifying elements weekday[0] = "MON_new"; weekday[3] = "THU_new"; //displaying the result cout<<weekday[0]<<"\n"; cout<<weekday[3]; return 0; }
The output of the above code will be:
MON_new THU_new
Loop over an Array
With for loop or while loop, we can access each elements of an array.
For Loop over an Array
In the example below, for loop is used to access all elements of the given array.
#include <iostream> #include <string> using namespace std; int main (){ string weekday[5] = {"MON", "TUE", "WED", "THU", "FRI"}; //using for loop to access all //elements of the array for(int i = 0; i < 5; i++) { cout<<weekday[i]<<"\n"; } return 0; }
The output of the above code will be:
MON TUE WED THU FRI
While Loop over an Array
Similarly, while loop is also be used to access elements of the array.
#include <iostream> using namespace std; int main (){ int numbers[5] = {10, 20, 30, 40, 50}; int i = 0; //using while loop to access all //elements of the array while(i < 5) { cout<<numbers[i]<<"\n"; i++; } return 0; }
The output of the above code will be:
10 20 30 40 50