Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

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

  2. 2

    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.

  3. 3

    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
Back

3/12

  1. 1. Creating an Array
  2. 2. Reading Elements
  3. 3. Changing Elements
  4. 4. Looping over an Array
  5. 5. Past the End
  6. 6. The Size of an Array
  7. 7. Sum and Average
  8. 8. Counting
  9. 9. The Largest Value
  10. 10. Filling an Array
  11. 11. Two-Dimensional Arrays
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.