Arrays (1D & Contiguous Memory)
int numbers[5]; // declares space for 5 ints, values are garbage/undefined
int scores[5] = {90, 85, 77, 92, 88}; // declares AND initializes
int grades[] = {70, 80, 90}; // size (3) inferred automatically from the values
Array indexing starts at 0, exactly like Python and most other languages: scores[0] is the first element, scores[4] is the last element of a 5-element array.
int scores[5] = {90, 85, 77, 92, 88};
for (int i = 0; i < 5; i++) {
printf("%d\n", scores[i]);
}
C has no built-in way to ask an array how many elements it holds at runtime the way Python's len() does. Instead, calculate it using sizeof:
int size = sizeof(scores) / sizeof(scores[0]); // total bytes รท bytes per element
int scores[5] = {90, 85, 77, 92, 88};
scores[2] = 100; // replace the third element
scores[0] += 5; // add 5 to the first element
Unlike strings in many languages, arrays in C are always mutable โ you can freely change any element after creation, as long as you stay within the array's declared size.
A C array's size is fixed at creation and cannot grow. Worse, C does not automatically check whether an index is valid โ accessing scores[10] on a 5-element array doesn't raise a clean error like Python's IndexError. Instead, it reads or writes to whatever memory happens to sit next to your array, which can silently corrupt other data or crash your program unpredictably.
This is one of the most dangerous C mistakes precisely because it often doesn't crash immediately โ scores[10] on a 5-element array might "work" and print a garbage number instead of failing loudly, hiding the bug until it causes unpredictable behavior somewhere else entirely. Always keep loop conditions strictly less than the array's actual size.
Create an array of 6 exam scores, calculate their average using a loop, and print the result.
#include <stdio.h>
int main() {
int scores[6] = {88, 92, 79, 95, 84, 90};
int sum = 0;
for (int i = 0; i < 6; i++) {
sum += scores[i];
}
printf("Average: %.2f\n", (float)sum / 6);
return 0;
}