Changing Elements

You can also change an element of an array. Write the array's name and the index in square brackets, just like when you read an element, and assign a new value with =, as you would to a variable:

int scores[] = {80, 92, 75, 60, 88};
scores[2] = 79;
printf("%d %d %d\n", scores[1], scores[2], scores[3]);

This prints:

92 79 60

The element at index 2 now has the value 79, and the old 75 is gone. Nothing was inserted or moved: the array still has five elements, and the others stayed the same.

Make sure you don't write == instead of =. The statement scores[2] == 79; only compares the two values and changes nothing. You don't get any error message: the program runs, and the element just keeps its old value.

An element behaves like a variable of its type, so +=, -=, ++ and -- work with it too. In a game, three players start with three lives each:

int lives[] = {3, 3, 3};
lives[0]--;
lives[2] += 2;
printf("%d %d %d\n", lives[0], lives[1], lives[2]);

This prints:

2 3 5

lives[0]--; took one life from the first player, and lives[2] += 2; gave the third player two extra lives. The second player still has three.

Instructions

Ben has answered a bonus question. Below the output line, write a statement that adds 5 to Ben's points, the second element, with +=.

The judges have found a mistake in Cyril's points: he should have 25. Below that, write a statement that changes the third element to 25.

Then print the points again in the same way, for example by copying the output line. Now the output shows them before and after the changes:

12 7 30
12 12 25

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/12