C++ Arrays C-PLUS-PLUS

C++ Arrays  

C++ Arrays

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces.

string cars[4] = {"TATA", "BMW", "Ford", "Tesla"};

To create an array of three integers, you could write:

int myNum[3] = {3, 6, 9};

 

Access the Elements of an Array

You access an array element by referring to the index number. This statement accesses the value of the first element in cars.

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  string cars[4] = {"Tesla", "BMW", "Ford", "TATA"};
  cout << cars[0];
  return 0;
}
 

Output:

Tesla

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries