Skip to main content

✍️ Practice (Hard)

1. Predict the Output (return edition)​

Given the below program, what will be the output if i call Main?

static int[] Make()
{
int[] local = { 4, 5, 6 };
return local;
}

static void Main()
{
int[] r = Make();
r[1] = 0;

int[] s = Make();

Console.WriteLine($"{r[1]} {s[1]}");
}

2. Predict the Output (ref vs no ref)​

Given the below program, what will be the output if i call Main?

static void Main()
{
int[] a = { 1, 2, 3 };
int[] b = a;

Change(a, ref b);

Console.WriteLine($"{a[0]} {b[0]}");
}

static void Change(int[] x, ref int[] y)
{
x[0] = 10;
y = new int[] { 20, 30 };
x[0]++;
y[0]++;
}

3. Draw the Memory​

Given the program below, draw the stack and the heap at point (A) and again at point (B).

Label every variable, every array, and every arrow if Main is called.

static void Main()
{
int count = 2;
int[] data = { 7, 8 };
int[] copy = data;

Fill(data, count);
// (B)
}

static void Fill(int[] list, int value)
{
int[] other = new int[value];
list[0] = value;
// (A)
}

4. Fix the Error​

This code is supposed to double every number, but it doesn't compile. Why? Fix it.

int[] nums = { 1, 2, 3 };

foreach (int n in nums)
{
n = n * 2;
}

5. Twins?​

Given the below program, what will be the output?

int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
int[] c = a;

Console.WriteLine(a == b);
Console.WriteLine(a == c);

Is there a better way to check if 2 arrays are the same? If so, write it.

6. Unique​

Write Unique(int[] list) that returns a new array containing each value only once, in the order it first appears. The original array should not change.

int[] nums = { 4, 2, 4, 9, 2, 2, 7 };
int[] result = Unique(nums);
// result is { 4, 2, 9, 7 }
// nums is still { 4, 2, 4, 9, 2, 2, 7 }