Array Operations
Defining an array
-
Without specifying the size of the array:
int arr[] = {1, 2, 3};
Here, we can leave the square brackets empty, although the array cannot be left empty in this case. It must have elements in it.
-
With specifying the size of the array:
int arr[3]; arr[0] = 1, arr[1] = 2, arr[2] = 3;
Accessing an array element
An element in an array can easily be accessed through its index number. An index number is a special type of number which allows us to access variables of arrays. Index number provides a method to access each element of an array in a program. This must be remembered that the index number starts from 0 and not one.
Example:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3};
cout << arr[1] << endl;
}
Output:
2
Changing an array element
An element in an array can be overwritten using its index number.
Example:
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3};
arr[2] = 8; // changing the element on index 2
cout << arr[2] << endl;
}
Output:
8