CodeNest

Functions and arrays

Functions declare their return type and parameter types. Arrays have a fixed size and don't know their own length, so you pass it along:

int sum(int values[], int n) {
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += values[i];
    }
    return total;
}

int main(void) {
    int data[] = {1, 2, 3};
    printf("%d\n", sum(data, 3));
    return 0;
}

Try it

Implement sum so the program prints:

Sum: 15
C unavailable
Running C needs a server execution engine, which isn't configured on this deployment. You can still read the lesson and try the code locally.
Loading editor…

Press Ctrl/ + Enter or click Run to see the output here.