Menu
Coddy logo textTech

Modifying Elements

Part of the Fundamentals section of Coddy's C journey — lesson 55 of 63.

In C, you can modify elements of an array after they've been initialized.

Create an integer array with 5 elements:

int numbers[5] = {10, 20, 30, 40, 50};

To modify an element, use the array name with the index in square brackets:

// Change the third element (index 2) to 35
numbers[2] = 35;

After executing the above code, the array will contain:

[10, 20, 35, 40, 50]

You can also use variables as indices:

int index = 4;
numbers[index] = 55;  // Changes the fifth element (index 4) to 55

Now the array contains:

[10, 20, 35, 40, 55]

challenge icon

Challenge

Easy

Write a function named updateScore that takes:

  • An integer array representing the scores of 5 players
  • A player number (1 to 5)
  • A new score value

The function should update the score of the specified player and then print all scores in the format: "Scores: [score1, score2, score3, score4, score5]"

Remember that arrays in C are 0-indexed, so player 1 corresponds to index 0.

Cheat sheet

To modify array elements in C, use the array name with the index in square brackets:

int numbers[5] = {10, 20, 30, 40, 50};
numbers[2] = 35;  // Changes third element (index 2) to 35

You can also use variables as indices:

int index = 4;
numbers[index] = 55;  // Changes fifth element (index 4) to 55

Try it yourself

#include <stdio.h>

void updateScore(int scores[], int playerNumber, int newScore) {
    // Write your code here
    
}

int main() {
    int scores[5];
    
    // Read the current scores
    for (int i = 0; i < 5; i++) {
        scanf("%d", &scores[i]);
    }
    
    // Read the player number and new score
    int playerNumber, newScore;
    scanf("%d %d", &playerNumber, &newScore);
    
    // Call the updateScore function
    updateScore(scores, playerNumber, newScore);
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals