Labs ICT
โญ Pro Login

Arrays

A single variable holds one value. An array holds a whole list. Think of it as a row of lockers โ€” each one has a number (the index), and each one stores a value.

Declaring an Array

Specify the type, the name, and the size in square brackets. You can initialize values right away or assign them later.


#include 
int main() {
  int numbers[5] = {10, 20, 30, 40, 50};
  printf("First: %d\n", numbers[0]);
  printf("Third: %d\n", numbers[2]);
  return 0;
}
    
Try it Yourself โ†’

Zero-Based Indexing

In C, array indices start at 0. So the first element is array[0], the second is array[1], and the last is array[size - 1]. Going past the end is a common (and dangerous) mistake.


#include 
int main() {
  int scores[3] = {85, 92, 78};
  for (int i = 0; i < 3; i++) {
    printf("Score %d: %d\n", i + 1, scores[i]);
  }
  return 0;
}
    
Try it Yourself โ†’

Iterating with Loops

Loops and arrays are best friends. A for loop is perfect for walking through every element in order.


#include 
int main() {
  int temps[7] = {72, 75, 68, 80, 77, 73, 70};
  int sum = 0;
  for (int i = 0; i < 7; i++) {
    sum += temps[i];
  }
  printf("Average temp: %.1f\n", sum / 7.0);
  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is the index of the first element in a C array?