C Tutorial

C Arrays

An array is a fixed list of values of one type. Index from 0. Do not walk off the end.

A list under one name

An array holds several values of the same type in one variable. Four quiz scores do not needscore0, score1, score2, and score3. They belong in one array named scores.

Every slot has an index. The first slot is 0, not 1. The last slot of a four-element array is 3. That off-by-one rule is the source of most array bugs. The length is fixed: you pick it when you declare the array.

Declare and initialize

Write the type, the name, then the length in square brackets. The length is a compile-time constant: a literal or a const int. You cannot ask the user for a size and then use that number as the array length in portable C17.

Example

#include <stdio.h>

int main(void) {
  int scores[4] = {88, 91, 74, 95};
  printf("%d\n", scores[0]);
  printf("%d\n", scores[3]);
  return 0;
}

The braces list the starting values in order. If you give fewer values than the length, the rest become zero. If you write int scores[4]; with no braces, the slots are uninitialized — do not print them until you assign values.

Index from zero

Read a slot with name[index]. Assign to a slot the same way. Changing scores[1] does not copy the array; it overwrites that one integer.

IndexValue in the example
088
191
274
395

There is no scores[4]. The compiler will often let you write it. The program then reads memory that is not part of the array. Do not do that. Stay in 0 through length - 1.

Loop through the slots

A for loop with an index is the usual way to visit every element. Keep the loop conditioni < length, not i <= length.

Example

#include <stdio.h>

int main(void) {
  const int count = 5;
  double temps[5] = {16.0, 18.5, 21.0, 19.5, 17.0};
  double total = 0.0;

  for (int i = 0; i < count; i++) {
    total = total + temps[i];
  }

  printf("average: %.1f\n", total / count);
  temps[2] = 22.0;
  printf("midday: %.1f\n", temps[2]);
  return 0;
}

Compile this at /c/try. Change one temperature and run again. The loop bound stayscount so you do not walk off the end.

Size is known at compile time

The compiler must see the length when it builds the program. That is why a raw array cannot grow. You cannot push a fifth score onto a four-slot array. You declare a bigger array, or you allocate memory later withmalloc.

Example

#include <stdio.h>

int main(void) {
  int seats[3] = {12, 8, 15};
  int n = sizeof(seats) / sizeof(seats[0]);
  printf("slots: %d\n", n);
  for (int i = 0; i < n; i++) {
    printf("%d\n", seats[i]);
  }
  return 0;
}

sizeof(seats) is the whole array in bytes. Divide by the size of one element and you get the count. Prefer a const int you wrote yourself. sizeof is easy to misuse once the array is passed into a function — that story comes with pointers.

Stay inside the array

Walking off the end is undefined behavior. The program might print a leftover number, appear to work, or crash later. gcc will not reliably stop you. Count the slots. Loop with i < n.

For this chapter, a raw array is enough: one type, a fixed length, index from zero. Next: two indexes at once — a table stored as int grid[2][3].

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C editor at /c/try. Change one measurement and check whether the result still has the right unit.

Statistics

A class mean

The arithmetic mean is the sum divided by the count. Five marks 72, 81, 64, 90, 77 average 76.8. One extreme mark pulls that number; the median would tell a different story.

An array holds the list. Index 0 is the first script. Walk with a for loop. Dividing by 5.0 keeps the mean from truncating to 76.

mean = (Σ xᵢ) / n

Example

#include <stdio.h>

int main(void) {
  int marks[] = {72, 81, 64, 90, 77};
  int i;
  int sum = 0;
  for (i = 0; i < 5; i++) {
    sum += marks[i];
  }
  printf("mean = %.1f\n", sum / 5.0);
  return 0;
}

Physics

Hottest of five samples

A logger stores temperatures in time order. Finding the maximum is one pass: start with the first reading, replace it whenever a later one is larger. These five values peak at 19.1 °C.

Do not read celsius[5]. The last legal index is 4. Walking off the end is undefined behaviour, not a friendly error.

Example

#include <stdio.h>

int main(void) {
  double celsius[] = {18.2, 18.5, 19.0, 18.8, 19.1};
  int i;
  double max = celsius[0];
  for (i = 1; i < 5; i++) {
    if (celsius[i] > max) {
      max = celsius[i];
    }
  }
  printf("hottest = %.1f C\n", max);
  return 0;
}

FAQ: C Arrays

Common questions about this page.

What is the StudyGrid C tutorial?

The StudyGrid C tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, pointers, structs, files, and the standard library. Each chapter has copy-and-run examples.

Should I run c arrays examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c arrays in this C C lesson (C Arrays).

Is the C editor the same as Try Python, Try HTML, or Try C++?

No. Try C compiles with gcc at /c/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. Try C++ stays at /cpp/try. C lessons never open those editors.

Do I need to install a compiler to learn C?

No. Open a chapter, click Try it in C, and compile in the browser. You can also download a .c file and compile locally with gcc.

Where should I start the C tutorial?

Start at C Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After pointers, open C Examples, then files and bitwise. Use Next at the bottom of each chapter.

Is the C tutorial free?

Yes. The C workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.