×

C# Crash Course

Course Home C# Introduction and Setup C# Variables and Data Types C# Console Input and Output C# Operators and Expressions C# Conditional Statements - If and Else C# Switch Statements C# While and Do-While Loops C# For Loops C# Nested Loops C# Methods - Part 1 (Basics) C# Methods - Part 2 (ref, out, and Recursion) C# Arrays C# Number Systems (Binary and Hexadecimal) C# Exception Handling (Try-Catch) C# Random Numbers C# String Methods and Manipulation C# Course Summary and Best Practices


C# Arrays

What is an Array?

An array is a collection that stores multiple values of the same type in a single variable. Think of it as a list of numbered boxes, each holding a value.

// Instead of this:
int iNum1 = 10;
int iNum2 = 20;
int iNum3 = 30;
int iNum4 = 40;
int iNum5 = 50;

// Use this:
int[] iNumbers = { 10, 20, 30, 40, 50 };

Array Declaration and Initialization

Method 1: Declare and Initialize with Values

// Integer array
int[] iNumbers = { 1, 2, 3, 4, 5 };

// String array
string[] sNames = { "Alice", "Bob", "Charlie" };

// Double array
double[] dPrices = { 19.99, 29.99, 39.99 };

// Character array
char[] cGrades = { 'A', 'B', 'C', 'D', 'F' };

Method 2: Declare Size, Then Assign Values

// Create array with 5 elements
int[] iNumbers = new int[5];

// Assign values
iNumbers[0] = 10;
iNumbers[1] = 20;
iNumbers[2] = 30;
iNumbers[3] = 40;
iNumbers[4] = 50;

Method 3: Declare, Then Initialize

int[] iNumbers;
iNumbers = new int[] { 1, 2, 3, 4, 5 };

// Or
string[] sNames;
sNames = new string[3];
sNames[0] = "Alice";
sNames[1] = "Bob";
sNames[2] = "Charlie";

Accessing Array Elements

Arrays use zero-based indexing (first element is at index 0).

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

Console.WriteLine(iNumbers[0]);  // 10 (first element)
Console.WriteLine(iNumbers[1]);  // 20 (second element)
Console.WriteLine(iNumbers[2]);  // 30 (third element)
Console.WriteLine(iNumbers[3]);  // 40 (fourth element)
Console.WriteLine(iNumbers[4]);  // 50 (fifth element)

// Index:               0   1   2   3   4
// Array:             [10, 20, 30, 40, 50]

Modifying Array Elements

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

Console.WriteLine(iNumbers[1]);  // 20

iNumbers[1] = 99;  // Change second element

Console.WriteLine(iNumbers[1]);  // 99

Array Length

Use the Length property to get the number of elements:

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

Console.WriteLine($"Array length: {iNumbers.Length}");  // 5

// Last element (length - 1)
Console.WriteLine($"Last element: {iNumbers[iNumbers.Length - 1]}");  // 50

Looping Through Arrays

Using For Loop (Most Common)

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

for (int i = 0; i < iNumbers.Length; i++)
{
    Console.WriteLine($"Element at index {i}: {iNumbers[i]}");
}

// Output:
// Element at index 0: 10
// Element at index 1: 20
// Element at index 2: 30
// Element at index 3: 40
// Element at index 4: 50

Using Foreach Loop

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

foreach (int iNum in iNumbers)
{
    Console.WriteLine(iNum);
}

// Output:
// 10
// 20
// 30
// 40
// 50

For vs Foreach

Use For Loop When: ✅ You need the index ✅ You want to modify array elements ✅ You want to loop in reverse

Use Foreach Loop When: ✅ You just need to read values ✅ You don't need the index ✅ Cleaner, simpler code

Array Operations

Sum of Array Elements

int[] iNumbers = { 10, 20, 30, 40, 50 };
int iSum = 0;

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

Console.WriteLine($"Sum: {iSum}");  // Sum: 150

Finding Maximum Value

int[] iNumbers = { 10, 45, 30, 92, 50 };
int iMax = iNumbers[0];  // Assume first is max

for (int i = 1; i < iNumbers.Length; i++)
{
    if (iNumbers[i] > iMax)
    {
        iMax = iNumbers[i];
    }
}

Console.WriteLine($"Maximum: {iMax}");  // Maximum: 92

Finding Minimum Value

int[] iNumbers = { 10, 45, 5, 92, 50 };
int iMin = iNumbers[0];  // Assume first is min

for (int i = 1; i < iNumbers.Length; i++)
{
    if (iNumbers[i] < iMin)
    {
        iMin = iNumbers[i];
    }
}

Console.WriteLine($"Minimum: {iMin}");  // Minimum: 5

Calculating Average

int[] iNumbers = { 10, 20, 30, 40, 50 };
int iSum = 0;

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

double dAverage = (double)iSum / iNumbers.Length;

Console.WriteLine($"Average: {dAverage}");  // Average: 30

Counting Elements

int[] iNumbers = { 10, 25, 30, 15, 40, 22 };
int iCountAbove20 = 0;

for (int i = 0; i < iNumbers.Length; i++)
{
    if (iNumbers[i] > 20)
    {
        iCountAbove20++;
    }
}

Console.WriteLine($"Numbers above 20: {iCountAbove20}");  // 4

Practical Examples

Example 1: Student Grades

using System;

namespace StudentGrades
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] iGrades = new int[5];

            // Get grades from user
            Console.WriteLine("Enter 5 grades:");
            for (int i = 0; i < iGrades.Length; i++)
            {
                Console.Write($"Grade {i + 1}: ");
                iGrades[i] = int.Parse(Console.ReadLine());
            }

            // Calculate statistics
            int iSum = 0;
            int iMax = iGrades[0];
            int iMin = iGrades[0];

            for (int i = 0; i < iGrades.Length; i++)
            {
                iSum += iGrades[i];
                if (iGrades[i] > iMax) iMax = iGrades[i];
                if (iGrades[i] < iMin) iMin = iGrades[i];
            }

            double dAverage = (double)iSum / iGrades.Length;

            // Display results
            Console.WriteLine("\n--- Grade Statistics ---");
            Console.WriteLine($"Total: {iSum}");
            Console.WriteLine($"Average: {dAverage:0.00}");
            Console.WriteLine($"Highest: {iMax}");
            Console.WriteLine($"Lowest: {iMin}");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}

Example 2: Search in Array

using System;

namespace ArraySearch
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] iNumbers = { 15, 23, 8, 42, 16, 7, 35 };

            Console.Write("Enter number to search: ");
            int iSearch = int.Parse(Console.ReadLine());

            bool bFound = false;
            int iPosition = -1;

            for (int i = 0; i < iNumbers.Length; i++)
            {
                if (iNumbers[i] == iSearch)
                {
                    bFound = true;
                    iPosition = i;
                    break;
                }
            }

            if (bFound)
            {
                Console.WriteLine($"Found {iSearch} at index {iPosition}");
            }
            else
            {
                Console.WriteLine($"{iSearch} not found in array");
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}

Example 3: Reverse Array

using System;

namespace ReverseArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] iNumbers = { 1, 2, 3, 4, 5 };

            Console.WriteLine("Original array:");
            foreach (int iNum in iNumbers)
            {
                Console.Write(iNum + " ");
            }

            // Reverse the array
            for (int i = 0; i < iNumbers.Length / 2; i++)
            {
                int iTemp = iNumbers[i];
                iNumbers[i] = iNumbers[iNumbers.Length - 1 - i];
                iNumbers[iNumbers.Length - 1 - i] = iTemp;
            }

            Console.WriteLine("\n\nReversed array:");
            foreach (int iNum in iNumbers)
            {
                Console.Write(iNum + " ");
            }

            Console.WriteLine("\n\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}

// Output:
// Original array: 1 2 3 4 5
// Reversed array: 5 4 3 2 1

Multi-Dimensional Arrays

2D Arrays (Matrix)

// Declare and initialize
int[,] iMatrix = new int[3, 3]
{
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Access elements
Console.WriteLine(iMatrix[0, 0]);  // 1
Console.WriteLine(iMatrix[1, 2]);  // 6
Console.WriteLine(iMatrix[2, 1]);  // 8

// Loop through 2D array
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        Console.Write(iMatrix[i, j] + " ");
    }
    Console.WriteLine();
}

// Output:
// 1 2 3
// 4 5 6
// 7 8 9

Getting 2D Array Dimensions

int[,] iMatrix = new int[3, 4];

int iRows = iMatrix.GetLength(0);     // 3
int iColumns = iMatrix.GetLength(1);  // 4

Console.WriteLine($"Rows: {iRows}");
Console.WriteLine($"Columns: {iColumns}");

Array Methods

Array.Sort()

int[] iNumbers = { 45, 12, 78, 23, 56 };

Array.Sort(iNumbers);

foreach (int iNum in iNumbers)
{
    Console.Write(iNum + " ");
}
// Output: 12 23 45 56 78

Array.Reverse()

int[] iNumbers = { 1, 2, 3, 4, 5 };

Array.Reverse(iNumbers);

foreach (int iNum in iNumbers)
{
    Console.Write(iNum + " ");
}
// Output: 5 4 3 2 1

Array.IndexOf()

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

int iIndex = Array.IndexOf(iNumbers, 30);
Console.WriteLine($"30 found at index: {iIndex}");  // 2

int iIndex2 = Array.IndexOf(iNumbers, 99);
Console.WriteLine($"99 found at index: {iIndex2}");  // -1 (not found)

Array.Clear()

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

Array.Clear(iNumbers, 0, iNumbers.Length);

foreach (int iNum in iNumbers)
{
    Console.Write(iNum + " ");
}
// Output: 0 0 0 0 0

Practice Exercises

Exercise 1: Sum of Even Numbers

Create an array of 10 numbers, calculate and display the sum of even numbers only.

Exercise 2: Find Second Largest

Find the second largest number in an array.

Exercise 3: Remove Duplicates

Count how many unique numbers are in an array.

Exercise 4: Shift Elements

Shift all elements one position to the right (last element goes to first).

Exercise 5: Matrix Addition

Add two 3x3 matrices together.

Common Mistakes to Avoid

Index Out of Range:

int[] iNumbers = { 10, 20, 30 };
Console.WriteLine(iNumbers[3]);  // ERROR! Index 3 doesn't exist

Correct:

int[] iNumbers = { 10, 20, 30 };
Console.WriteLine(iNumbers[2]);  // OK (last element)

Wrong Loop Condition:

for (int i = 0; i <= iNumbers.Length; i++)  // WRONG! Causes error

Correct:

for (int i = 0; i < iNumbers.Length; i++)  // Correct

Forgetting Array Size:

int[] iNumbers = new int[];  // WRONG! Must specify size

Correct:

int[] iNumbers = new int[5];  // OK
// Or
int[] iNumbers = { 1, 2, 3, 4, 5 };  // OK

Key Takeaways

✅ Arrays store multiple values of the same type ✅ Arrays use zero-based indexing (first element is 0) ✅ Use .Length to get number of elements ✅ Use for loop when you need index ✅ Use foreach when you just need values ✅ Always check array bounds to avoid errors ✅ Can use Array class methods for sorting, reversing, etc.


Next Topic: C# Number Systems (Binary, Hexadecimal)