Summary - Array methods
Combine Sort, Reverse and Find to write a class list app.
Summary - Array methods
In this section you learned Array.Sort, Array.Reverse, Array.IndexOf, Array.Copy and Array.Find / FindAll. They all work in place or return new arrays; none removes the need to write loops, but each shortens the code.
Now we will combine them into a small class list app. Sorting, searching and finding the top score will come together in a single Main method.
Exercise Sort and print the top score
Sort the given int[] scores = { 78, 92, 65, 88 }; array with Array.Sort(scores). Then print the top score, that is scores[scores.Length - 1], with Console.WriteLine.
Show example solution
Sort with Array.Sort(scores);, then print the top score with Console.WriteLine(scores[scores.Length - 1]);.
Example solution:
using System;
class Program
{
static void Main()
{
int[] scores = { 78, 92, 65, 88 };
// Sort and print the top score
Array.Sort(scores);
Console.WriteLine(scores[scores.Length - 1]);
}
}
Exercise Find a specific score
On the given int[] scores = { 78, 92, 65, 88 }; array, find the index of the value 65 with Array.IndexOf(scores, 65) and print it with Console.WriteLine.
Show example solution
Find the index with int idx = Array.IndexOf(scores, 65);, then print with Console.WriteLine(idx);.
Example solution:
using System;
class Program
{
static void Main()
{
int[] scores = { 78, 92, 65, 88 };
// Find the index of 65 and print it
int idx = Array.IndexOf(scores, 65);
Console.WriteLine(idx);
}
}
Test yourself
-
What is the last element after sorting?
int[] scores = { 78, 92, 65, 88 }; Array.Sort(scores); Console.WriteLine(scores[scores.Length - 1]);- 78
- 92
- 65
- 88
Show answer
92 — Correct. The last element of an ascending sorted array is the largest: 92.
-
Search with IndexOf
int[] scores = { 65, 78, 88, 92 }; int idx = ____; Console.WriteLine(idx);Show answer
int[] scores = { 65, 78, 88, 92 }; int idx = Array.IndexOf(scores, 88); Console.WriteLine(idx); -
Match the concepts
- Array.Sort
- Sorts ascending
- Array.Reverse
- Reverses
- Array.IndexOf
- Finds index
- Array.Find
- First match