Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

How to access the elements of an array by index number in C++

Onyejiaku Theophilus Chidalu

Overview

An array in C++ is used to store multiple elements of the same data type. These values of the same data types in an array are its elements.

Array declaration

To declare an array in C++, we write the data type, the name of the array with a bracket [] specifying the number of elements it contains.

For example:

string names[3];

In the code above, we declared an array that holds three string elements. We can now use an array literal with a comma-separated list inside curly braces to insert the elements into the array.

For example:

string names[3] = {"Theo", "Ben", "Dalu"};

Another example:

int mynumbers[5] = {1, 10, 5, 6, 95}

Accessing array elements

We can easily access the elements of a given array by referring to their index number. Remember that in C++, the first element of a given object has its index position or number as 0.

For example, the string Theo has its first character T as index 0 while its second character h has its index number or position as 1 and so on.

In the code below, we will create an array with three elements and refer to each array element using their index numbers.

Example

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

int main() {

  // creating an array
  string names[3] = {"Theo", "Ben", "Dalu"};

  // accessing the first element of the array
  cout << names[0]<<endl;
  
  // accessing the second element of the array
  cout << names[1];
  return 0;
}




Accessing the elements of an array using their index numbers

Explanation

  • Line 8: We create an array names having 3 string elements.
  • Line 11: We print the first element of the array using its index number in a square bracket [0].
  • Line 14: We print the second element of the array using its index number in a square bracket [1].

RELATED TAGS

c++
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring