Function with Array in C

Level 4180 keystrokes

Defines a function that takes an array and its size as parameters.

C code

// In a parameter, int arr[] means int *arr: only a pointer is passed
// so the function cannot know the length and receives it as size
1int sumArray(int arr[], int size) {
// Running total starts at 0
2 int sum = 0;
// Visit indexes 0 to size - 1
3 for (int i = 0; i < size; i++) {
// Add each element to the total
4 sum += arr[i];
5 }
// Return the finished sum
6 return sum;
7}
// Array of 5 numbers to add up
8int nums[] = {1, 2, 3, 4, 5};
// Pass the array and its length; 1+2+3+4+5 prints Sum: 15
9printf("Sum: %d", sumArray(nums, 5));

Output

Sum: 15
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ,× 7
  • ;× 7
  • (× 4
  • )× 4
  • =× 4
  • [× 3
  • ]× 3
  • {× 3
  • }× 3
  • +× 3

More C examples at level 4

← C typing practice