DEV Community

Sabin Sim
Sabin Sim

Posted on

34. C# (Arrays in C)

using System;

class Program
{
    static void Main()
    {
        // 1) Declare + allocate array (check default values)
        int[] numbers = new int[3];

        Console.WriteLine("Default values:");
        Console.WriteLine(numbers[0]);
        Console.WriteLine(numbers[1]);
        Console.WriteLine(numbers[2]);
        Console.WriteLine();

        // 2) Update values
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;

        Console.WriteLine("After updating values:");
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine(numbers[i]);
        }
        Console.WriteLine();

        // 3) Index from End (^)
        int[] numbers2 = { 10, 20, 30, 40, 50 };

        Console.WriteLine("Access from the end:");
        Console.WriteLine(numbers2[^1]); // 50
        Console.WriteLine(numbers2[^2]); // 40
        Console.WriteLine();

        // 4) Calculate sum
        int sum = 0;

        for (int i = 0; i < numbers2.Length; i++)
        {
            sum += numbers2[i];
        }

        Console.WriteLine("Sum:");
        Console.WriteLine(sum);

        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

0. The Real Goal of This Lesson

An array is an index-based structure that stores multiple values of the same type under one variable name.

If this is not clear:

  • index errors feel random
  • Length becomes confusing
  • for loops with arrays become fragile

This lesson is not about syntax.

It is about understanding the structure of indexed storage.


1. What Is an Array?

A normal variable is one box:

int number = 10;
Enter fullscreen mode Exit fullscreen mode

An array is multiple boxes handled as one structure:

int[] numbers = new int[3];
Enter fullscreen mode Exit fullscreen mode

Meaning:

  • allocate space for 3 integers
  • each slot is filled with the default value

For int, the default value is:

0
Enter fullscreen mode Exit fullscreen mode

So immediately after creation, this array contains:

0, 0, 0
Enter fullscreen mode Exit fullscreen mode

2. Index Starts at 0

If the array size is 3, the valid indices are:

0 1 2
Enter fullscreen mode Exit fullscreen mode

The last valid index is always:

Length - 1
Enter fullscreen mode Exit fullscreen mode

This is one of the most important rules in arrays.


3. Compile-Time Error vs Runtime Error

Compile-Time Error

numbers[0] = "hello";
Enter fullscreen mode Exit fullscreen mode

This fails because the type is wrong.

  • numbers[0] expects an int
  • "hello" is a string

The compiler blocks execution before the program runs.


Runtime Error

numbers[3] = 100;
Enter fullscreen mode Exit fullscreen mode

This compiles.

But it crashes during execution because index 3 does not exist in an array of length 3.

Typical message:

Index was outside the bounds of the array
Enter fullscreen mode Exit fullscreen mode

This is a runtime error.


4. The Most Common Mistake

This is wrong:

numbers[numbers.Length]
Enter fullscreen mode Exit fullscreen mode

If Length = 3, valid indices are:

0, 1, 2
Enter fullscreen mode Exit fullscreen mode

So:

numbers[3]
Enter fullscreen mode Exit fullscreen mode

is invalid.

Always remember:

The last valid index is Length - 1.


5. The ^ Operator (Index from End)

This expression:

numbers2[^1]
Enter fullscreen mode Exit fullscreen mode

means:

the first element from the end

Equivalent to:

numbers2[numbers2.Length - 1]
Enter fullscreen mode Exit fullscreen mode

Examples:

  • ^1 → last element
  • ^2 → second-to-last element

It is a shorter way to count backward from the end.


6. The One Rule You Must Not Break in for Loops

Correct condition:

i < numbers.Length
Enter fullscreen mode Exit fullscreen mode

Wrong condition:

i <= numbers.Length
Enter fullscreen mode Exit fullscreen mode

Why is the second one wrong?

Because on the last iteration:

i == numbers.Length
Enter fullscreen mode Exit fullscreen mode

And that means you try to access an index that does not exist.

This is the classic off-by-one mistake.


7. The Biggest Limitation of Arrays

Arrays have fixed size.

Example:

new int[3]
Enter fullscreen mode Exit fullscreen mode

That size stays 3.

You cannot grow it.
You cannot shrink it.

So the structural rule is:

  • fixed number of elements → use an array
  • variable number of elements → later use List<T>

Final Summary

An array is an index-based structure that stores a fixed number of values of the same type.


Learning Check

In the following code, explain exactly when the runtime error happens by tracking the value of i step by step.

int[] numbers = { 10, 20, 30 };

for (int i = 0; i <= numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

Explain these points:

  1. How does i change starting from 0?
  2. What is the final value of i?
  3. At which exact moment does the crash happen, and why?

If you can explain that precisely,
you fully understand the relationship between arrays and for loops.

Top comments (0)