Array
Arrays follow contiguous memory allocation ( a classical memory allocation model that assigns a process consecutive memory block ). They are used to store multiple values in a single variable.
Value in the square bracket specifies the number of elements in the array.
Way to Define a array.
For strings
string fruits[3] = {"Banana", "Mango, "Apple"};
For number
int Num[3] = {10, 56, 12};
Access the elements of a array
Elements of a array are accessed by referring to the index numbers.
Example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fruits[3] = {"Banana", "Mango", "Apple"};
cout << fruits[0];
return 0;
}
Output:
Banana
Change an array element
This is also done by referring to index numbers
Example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fruits[3] = {"Banana", "Mango", "Apple"};
fruits[0] = "Orange";
cout << fruits[0];
return 0;
}
Output:
Orange
Loops and Arrays
Array elements can be looped.
Example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fruits[3] = {"Banana", "Mango", "Apple"};
for(int i = 0; i < 4; i++) {
cout << fruits[i] << "\n";
}
return 0;
}
Output:
Banana
Mango
Apple
Note: Array's size doesn't have to be defined inside the square bracket. But if it is not defined it will only be as big as the elements that are inserted into it.
In the following code 3 is the arrays maximum size. However if the size is specified the array will occupy that much space even if space is left empty.
Example:
string fruits[] = {"Banana", "Mango", "Apple"};