How to Access and Modify Elements of an Array in C++


C++


In this article, we show how to access and modify elements of an array in C++.

We showed previously how to create an array in C++, in which we went over how to declare and initialize an array.

Now we will show how to access the elements so that you can output the elements. We will also show how you can modify any of the elements of the array, so that you can change some of all of their values.

How to Access Elements of an Array

We now show to access element of an array in C++.

So we will create a basic array that has 5 elements.

We will then show how to access the elements of the array.

This is shown in the code below.



So we'll now go over the code above.

So we create an array, named test_scores, which has 5 elements.

We are able to access each of the elements by specifying the name of the array followed by the index number of each element of the array.

Being that we created an array of 5 elements, it has 5 elements.

The first element of an array starts at an index location of 0.

So this array with 5 elements has elements with an index location of 0 to 4.

test_scores[0] allows us to access the first element.

test_scores[1] allows us to access the second element.

test_scores[2] allows us to access the third element.

test_scores[3] allows us to access the fourth element.

test_scores[4] allows us to access the fifth element.

So this is one way to access each individual element of an array.

If you want to iterate through all elements of an array in C++, you can use a for loop.

This is shown below.



So here we have a for loop and iterates through each element of the array.

This is way we can access every element of an array.

This is especially good for large arrays.

In the example above, this gives us the following output shown below.



How to Modify an Element of an Array

So now we go over how to modify an element of an array in C++.

So we create a basic array and then we modify values within this array.



In order to modify a value of an array, you reference the array element by the array name and index location and then use the equals operator to set the value to what you want it to change to.

We change both elements of the above 2-item array.

The line, test_scores[0]= 82;, changes the first element to 82. Previously, the value was 75.

The line, test_scores[1]= 94;, changes the second element to 94. Previously, the value was 88.

When we run the program, we get the following ouput shown below.



So you can see that we successfully modified the values of the elements in the array.

And this is how to access and modify elements of an array in C++.


Related Resources

How to Write Contents to a File in C++

How to Append Contents to a File in C++

HTML Comment Box is loading comments...