Look at the code below. What will be printed to the console?
using System; class Program { static void Main() { int[] numbers = {5, 3, 8, 1, 2}; Array.Sort(numbers); int index = Array.IndexOf(numbers, 3); Console.WriteLine(index); } }
Remember that Array.Sort arranges the array in ascending order before searching.
After sorting, the array becomes [1, 2, 3, 5, 8]. The number 3 is at index 2 (0-based). So the output is 2.
What will be the output of the following C# program?
using System; class Program { static void Main() { string[] fruits = {"apple", "banana", "cherry"}; Array.Reverse(fruits); Console.WriteLine(fruits[1]); } }
Think about how reversing changes the order of elements.
Original array: ["apple", "banana", "cherry"]. After reversing: ["cherry", "banana", "apple"]. The element at index 1 is "banana".
Examine the code below. It throws an exception when run. What is the cause?
using System; class Program { static void Main() { int[] values = {10, 20, 30}; Array.Reverse(values, 1, 5); Console.WriteLine(string.Join(",", values)); } }
Check the parameters passed to Array.Reverse carefully.
The method Array.Reverse(array, index, length) requires that index + length does not exceed the array length. Here, 1 + 5 = 6, which is greater than the array length 3, causing ArgumentOutOfRangeException.
What will this program print?
using System; class Program { static void Main() { char[] letters = {'a', 'b', 'c', 'd'}; int pos = Array.IndexOf(letters, 'z'); Console.WriteLine(pos); } }
What does Array.IndexOf return if the item is not found?
If the element is not found, Array.IndexOf returns -1.
Consider this C# code snippet:
int[] arr = {4, 7, 1, 9};
Array.Sort(arr);
Array.Reverse(arr);
int index = Array.IndexOf(arr, 7);
After running this code, how many elements does arr contain?
Sorting and reversing do not change the number of elements in the array.
The array arr starts with 4 elements. Sorting and reversing only change the order, not the size. So it still has 4 elements.