🎓 A1Learner
🔍
0 of 50 lessons completed

C Array Size and Loops

sizeof gives the size of a value in bytes. Arrays fixed their length in the code; sizeof measures a row so the loop fits any length.

Count the values

The whole row takes 16 bytes and one int takes 4, so the division gives 4. The print line shows 4.

#include <stdio.h>

int main() {
  int scores[4] = {10, 20, 30, 40};
  int count = (int)(sizeof(scores) / sizeof(scores[0]));
  printf("%d\n", count);
  return 0;
}

Walk the row with count

The loop ends at count instead of a fixed number. Each value prints in turn: 10, 20, 30, 40.

#include <stdio.h>

int main() {
  int scores[4] = {10, 20, 30, 40};
  int count = (int)(sizeof(scores) / sizeof(scores[0]));
  for (int i = 0; i < count; i++) {
    printf("%d\n", scores[i]);
  }
  return 0;
}

Size in bytes

Four ints at 4 bytes each take 16 bytes. The print line shows 16.

#include <stdio.h>

int main() {
  int scores[4] = {10, 20, 30, 40};
  printf("%d\n", (int)sizeof(scores));
  return 0;
}

Example

#include <stdio.h>

int main() {
  int scores[4] = {10, 20, 30, 40};
  int count = (int)(sizeof(scores) / sizeof(scores[0]));
  int total = 0;
  for (int i = 0; i < count; i++) {
    total = total + scores[i];
  }
  printf("%d\n", total / count);
  return 0;
}

Key points

  • sizeof(scores) tells how many bytes the whole row takes.
  • sizeof(scores[0]) tells how many bytes one value takes.
  • Dividing the whole size by the size of one value gives how many values the row holds.
  • Store that count in an int, and use it as the end of the loop.
  • The loop still works when the row is edited to hold a new length.
  • An int takes 4 bytes, so a row of four ints takes 16 bytes.

The four scores add to 100, and the count is 4. Dividing 100 by 4 gives 25, which the print line shows.

Note

sizeof gives a size in bytes, not a count of values.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does sizeof(scores) / sizeof(scores[0]) give for a row of four ints?