Arrays

Loading concept...

🎒 Arrays: Your Magical Backpack of Data

Imagine you have a magical backpack that can hold exactly 5 toys. Each toy has its own special pocket numbered 0, 1, 2, 3, and 4. That’s exactly what an array is in C#—a container that holds multiple items of the same type, each in its own numbered slot!


📦 What is an Array?

An array is like a row of lockers at school. Each locker:

  • Has a number (starting from 0, not 1!)
  • Can hold one thing
  • All lockers hold the same type of thing
// Create a backpack with 5 toy slots
string[] toys = new string[5];

// Put toys in each slot
toys[0] = "Robot";
toys[1] = "Ball";
toys[2] = "Doll";
toys[3] = "Car";
toys[4] = "Puzzle";

🔑 Key Insight: Arrays start counting from 0, not 1. The first item is always at position 0!


🏗️ Creating Arrays: Three Magic Spells

Spell 1: Empty Container First

// Make empty backpack, fill later
int[] scores = new int[3];
scores[0] = 100;
scores[1] = 95;
scores[2] = 88;

Spell 2: Fill While Creating

// Make and fill at the same time
int[] scores = new int[] { 100, 95, 88 };

Spell 3: Shortcut Magic ✨

// Shortest way - C# figures it out!
int[] scores = { 100, 95, 88 };

All three spells create the exact same backpack with the same toys inside!


🎯 Accessing Array Items

Remember our numbered lockers? Here’s how to peek inside:

string[] fruits = { "Apple", "Banana", "Cherry" };

// Get the first fruit (position 0)
string first = fruits[0];  // "Apple"

// Get the last fruit (position 2)
string last = fruits[2];   // "Cherry"

📏 Finding Array Length

How many lockers do we have?

string[] fruits = { "Apple", "Banana", "Cherry" };
int count = fruits.Length;  // 3

⚠️ Warning: Length is 3, but the last position is 2! (Because we start at 0)


🔄 Array Types in C#

Single-Dimensional Arrays

The simplest kind—like a single row of lockers:

// One row of numbers
int[] numbers = { 10, 20, 30, 40, 50 };

Multi-Dimensional Arrays (2D)

Like a spreadsheet with rows AND columns—a grid of lockers!

// 3 rows Ă— 2 columns = 6 slots total
int[,] grid = new int[3, 2];
grid[0, 0] = 1;  // Row 0, Column 0
grid[0, 1] = 2;  // Row 0, Column 1
grid[1, 0] = 3;  // Row 1, Column 0

// Or create with values directly:
int[,] matrix = {
    { 1, 2 },
    { 3, 4 },
    { 5, 6 }
};
graph TD A["2D Array: matrix"] --> B["Row 0"] A --> C["Row 1"] A --> D["Row 2"] B --> E["[0,0]=1"] B --> F["[0,1]=2"] C --> G["[1,0]=3"] C --> H["[1,1]=4"] D --> I["[2,0]=5"] D --> J["[2,1]=6"]

Jagged Arrays (Array of Arrays)

Like lockers that can hold other lockers inside—each inner row can be different sizes!

// Create array that holds 3 arrays
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };       // 2 items
jagged[1] = new int[] { 3, 4, 5 };    // 3 items
jagged[2] = new int[] { 6 };          // 1 item

// Access: jagged[1][2] = 5

đź”§ Essential Array Operations

Changing Values

int[] nums = { 10, 20, 30 };
nums[1] = 99;  // Now: { 10, 99, 30 }

Looping Through All Items

Using for loop:

string[] colors = { "Red", "Green", "Blue" };
for (int i = 0; i < colors.Length; i++)
{
    Console.WriteLine(colors[i]);
}

Using foreach (easier!):

foreach (string color in colors)
{
    Console.WriteLine(color);
}

Sorting Arrays

int[] nums = { 5, 2, 8, 1, 9 };
Array.Sort(nums);
// Now: { 1, 2, 5, 8, 9 }

Reversing Arrays

int[] nums = { 1, 2, 3, 4, 5 };
Array.Reverse(nums);
// Now: { 5, 4, 3, 2, 1 }

Finding Items

string[] pets = { "Cat", "Dog", "Bird" };
int position = Array.IndexOf(pets, "Dog");
// position = 1

bool hasCat = Array.Exists(pets, p => p == "Cat");
// hasCat = true

🎯 Ranges and Indices: The Modern Way!

C# has cool shortcuts for grabbing parts of arrays. Think of it like saying “give me toys 2 through 4” instead of picking them one by one!

The Index Operator: ^ (From the End)

The ^ symbol counts from the back of the array:

int[] nums = { 10, 20, 30, 40, 50 };

int last = nums[^1];      // 50 (1st from end)
int secondLast = nums[^2]; // 40 (2nd from end)
graph LR A["nums array"] --> B["[0]=10"] B --> C["[1]=20"] C --> D["[2]=30"] D --> E["[3]=40"] E --> F["[4]=50"] F --> G["[^1]=50"] E --> H["[^2]=40"] D --> I["[^3]=30"]

The Range Operator: … (Slice It!)

Get multiple items at once with ..:

int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int[] slice1 = nums[2..5];   // { 2, 3, 4 }
int[] slice2 = nums[..3];    // { 0, 1, 2 }
int[] slice3 = nums[7..];    // { 7, 8, 9 }
int[] slice4 = nums[^3..];   // { 7, 8, 9 }
int[] copy = nums[..];       // Full copy!

Pattern: [start..end] includes start, excludes end!

Index and Range Types

You can save these as variables too:

Index lastIdx = ^1;
Range middle = 2..5;

int[] nums = { 0, 1, 2, 3, 4, 5 };
int lastNum = nums[lastIdx];     // 5
int[] midPart = nums[middle];    // { 2, 3, 4 }

🎮 Real-World Example: Game Scores

Let’s put it all together with a simple game score tracker:

// Store player scores
int[] scores = { 150, 200, 175, 225, 190 };

// Find highest score
int highest = scores.Max();  // 225

// Get last 3 scores
int[] recent = scores[^3..]; // { 175, 225, 190 }

// Sort and show top 3
int[] sorted = scores.ToArray();
Array.Sort(sorted);
Array.Reverse(sorted);
int[] top3 = sorted[..3]; // { 225, 200, 190 }

đź’ˇ Quick Tips

Do This ✅ Not This ❌
arr[0] for first item arr[1] (that’s the second!)
arr[^1] for last item arr[arr.Length] (crashes!)
Check Length before access Access blindly and crash
Use foreach for reading all Complex for loops when not needed

🎉 You Did It!

You now understand:

  • âś… What arrays are (numbered containers)
  • âś… How to create them (3 different ways!)
  • âś… Array types (1D, 2D, jagged)
  • âś… Operations (sort, reverse, find)
  • âś… Ranges and indices (^ and …)

Arrays are the foundation of handling collections in C#. Master these, and you’re ready for even more powerful collection types!

Remember: Arrays are like a magical backpack—once you know how many pockets it has, that number stays fixed. Need a stretchy backpack? That’s when you’ll learn about Lists! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.