Skip to main content

✍️ Practice (Medium)

1. Predict the Output​

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

static void Main()
{
int[] nums = { 1, 2, 3 };
DoubleAll(nums);
Console.WriteLine(nums[2]);
}

static void DoubleAll(int[] list)
{
for (int i = 0; i < list.Length; i++)
{
list[i] = list[i] * 2;
}
}

2. Predict the Output (again)​

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

static void Main()
{
int[] a = { 1, 2, 3 };
Mix(a);
Console.WriteLine($"{a[0]} {a[1]} {a[2]}");
}

static void Mix(int[] list)
{
list[0] = 100;
list = new int[] { 7, 8, 9 };
list[1] = 200;
}

3. Predict the Output (yet again)​

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

static void Main()
{
int[] x = { 5, 5 };
int[] y = x;

y[1] = 9;

Console.WriteLine(x[1]);
}

4. Swap​

Write Swap(char[] list, int i, int j) that swaps the elements at index i and j.

char[] letters = { 'a', 'b', 'c' };
Swap(letters, 0, 2);
// letters is now { 'c', 'b', 'a' }

5. Fix the Error​

This code doesn't compile. Why?

int[] nums = { 5, 1, 4 };
int[] sorted = Array.Sort(nums);
Console.WriteLine(sorted[0]);

6. Grow it​

Given the below program, what will be the output?

int[] nums = { 1, 2, 3 };
Array.Resize(ref nums, 5);

Console.WriteLine(nums.Length);
Console.WriteLine(nums[4]);

7. Predict the Output (again again)​

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

static void Main()
{
int score = 10;
int[] scores = { 10, 20 };

Bump(score, scores);

Console.WriteLine($"{score} {scores[0]}");
}

static void Bump(int s, int[] list)
{
s++;
list[0]++;
}

8. Somethings Wrong​

This function is supposed to add an item to the end of an array, but after calling Main, fruits still has 4 items. Why? Fix it.

static void Main()
{
string[] fruits = { "mango", "apple", "kiwi", "banana" };
AddItem(fruits, "grape");
Console.WriteLine(fruits.Length); // 4 (BAD)
}

static void AddItem(string[] list, string item)
{
Array.Resize(ref list, list.Length + 1);
list[list.Length - 1] = item;
}