DEV Community

seonglinchua
seonglinchua

Posted on

Mastering Arrays in C# for Coding Interviews

๐Ÿงฑ Arrays in C# โ€” A Practical Guide for Interview Preparation

Arrays are one of the most fundamental data structures used in programming and appear frequently in coding interviews.


โœ… What is an Array?

An array is a fixed-size, indexed collection of elements of the same type.


โœจ Declaring & Initializing Arrays

// Declare and allocate memory
int[] numbers = new int[5];

// Declare and assign values
int[] scores = new int[] { 90, 85, 78, 92, 88 };

// Short-hand initialization
string[] names = { "Alice", "Bob", "Charlie" };
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”„ Accessing and Updating Elements

int first = scores[0];
scores[2] = 80;
int last = scores[scores.Length - 1];
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Looping Through Arrays

// Using for loop
for (int i = 0; i < scores.Length; i++) {
    Console.WriteLine(scores[i]);
}

// Using foreach loop
foreach (int score in scores) {
    Console.WriteLine(score);
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง Useful Array Operations

Array.Sort(scores);         // Sort ascending
Array.Reverse(scores);      // Reverse array
int index = Array.IndexOf(scores, 92); // Find index of 92
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Common Use Cases

Use Case Description
Fixed-size data storage e.g., Top 5 student scores
Indexed logic Two pointers, prefix sum, etc.
Brute force comparisons e.g., nested loops for pair matching

๐Ÿงช Interview Example: Two Sum (Brute Force)

public int[] TwoSum(int[] nums, int target) {
    for (int i = 0; i < nums.Length; i++) {
        for (int j = i + 1; j < nums.Length; j++) {
            if (nums[i] + nums[j] == target)
                return new int[] { i, j };
        }
    }
    return new int[] { -1, -1 };
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ Summary

Feature Syntax Example
Declare int[] arr = new int[5];
Access arr[0], arr[arr.Length - 1]
Update arr[2] = 100;
Loop for or foreach
Sort/Reverse Array.Sort(arr), Array.Reverse()

Stay tuned for the next post where we tackle HashSet and use it to solve unique element problems efficiently.

Top comments (1)

Collapse
 
ghost_engineer_2883a1ca0a profile image
Ghost Engineer

try this if you get stuck during the interview. its an AI co-pilot that solves the questions for you so you can focus on the more important part of the interview, the communication part. its also a really good study tool: ghostengineer.com