Functions and arrays

Write functions and work with arrays and strings.

C
#include <stdio.h>
#include <string.h>

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

int main(void) {
  int marks[] = {72, 95, 60, 88};
  int n = sizeof(marks) / sizeof(marks[0]);
  printf("%d\n", sum(marks, n));

  char name[20] = "Kavin";
  printf("%zu\n", strlen(name));
  return 0;
}
Output
315
5

When passed to a function, an array becomes a pointer to its first element, so the function cannot tell its length. Always pass the length too.

A C string is a char array ending in a zero byte. C does not check array bounds, so writing past the end corrupts memory without any warning.

โ† Conditions and loopsPointers โ†’