Practice: Arrays and Methods Combined
Bubble Sort
Goal: Implement the bubble sort algorithm to sort an integer array in ascending order, displaying the results before and after sorting.
Requirements:
- Write bubble sort logic that compares adjacent elements and swaps them in each pass
- Display the array contents before and after sorting
- Count the actual number of swaps performed
Example
CSHARP
int[] numbers = { 64, 34, 25, 12, 22, 11, 90, 5 };
Console.WriteLine("Before sorting: " + string.Join(", ", numbers));
int swapCount = 0;
for (int i = 0; i < numbers.Length - 1; i++)
{
bool swapped = false;
for (int j = 0; j < numbers.Length - 1 - i; j++)
{
if (numbers[j] > numbers[j + 1])
{
(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j]);
swapped = true;
swapCount++;
}
}
if (!swapped) break;
}
Console.WriteLine("After sorting: " + string.Join(", ", numbers));
Console.WriteLine($"Swap count: {swapCount}");
TEXT
Before sorting: 64, 34, 25, 12, 22, 11, 90, 5
After sorting: 5, 11, 12, 22, 25, 34, 64, 90
Swap count: 20
Student Score Statistics
Goal: Use an array to store student scores, and calculate the average, highest, lowest scores and the number of students above average through methods.
Requirements:
- Define methods to calculate the average, maximum, and minimum separately
- Count the number of students scoring above the average
- Format and display all results
Example
CSHARP
int[] scores = { 85, 92, 78, 60, 95, 88, 72, 66, 91, 83 };
double average = CalcAverage(scores);
int max = CalcMax(scores);
int min = CalcMin(scores);
int aboveAvg = CountAbove(scores, average);
Console.WriteLine($"Score list: {string.Join(", ", scores)}");
Console.WriteLine($"Average: {average:F1}");
Console.WriteLine($"Highest: {max}");
Console.WriteLine($"Lowest: {min}");
Console.WriteLine($"Above average count: {aboveAvg}");
double CalcAverage(int[] arr)
{
double sum = 0;
foreach (int s in arr) sum += s;
return sum / arr.Length;
}
int CalcMax(int[] arr)
{
int max = arr[0];
foreach (int s in arr) if (s > max) max = s;
return max;
}
int CalcMin(int[] arr)
{
int min = arr[0];
foreach (int s in arr) if (s < min) min = s;
return min;
}
int CountAbove(int[] arr, double threshold)
{
int count = 0;
foreach (int s in arr) if (s > threshold) count++;
return count;
}
TEXT
Score list: 85, 92, 78, 60, 95, 88, 72, 66, 91, 83
Average: 81.0
Highest: 95
Lowest: 60
Above average count: 5
To-Do List
Goal: Implement a simple to-do list using a string array, supporting add, remove, and view operations.
Requirements:
- Maximum array capacity of 10 items
- Check if the list is full when adding, and validate the index when removing
- Encapsulate add, remove, and display logic in methods
Example
CSHARP
string[] todos = new string[10];
int count = 0;
AddItem("Learn C# arrays");
AddItem("Complete exercises");
AddItem("Review methods and parameters");
ListAll();
RemoveItem(1);
ListAll();
void AddItem(string item)
{
if (count >= todos.Length)
{
Console.WriteLine("⚠️ To-do list is full, cannot add.");
return;
}
todos[count] = item;
count++;
Console.WriteLine($"Added: {item}");
}
void RemoveItem(int index)
{
if (index < 0 || index >= count)
{
Console.WriteLine("⚠️ Invalid index, removal failed.");
return;
}
string removed = todos[index];
for (int i = index; i < count - 1; i++)
{
todos[i] = todos[i + 1];
}
todos[count - 1] = null;
count--;
Console.WriteLine($"Removed: {removed}");
}
void ListAll()
{
Console.WriteLine("--- To-Do List ---");
if (count == 0)
{
Console.WriteLine("(empty)");
return;
}
for (int i = 0; i < count; i++)
{
Console.WriteLine($"{i}. {todos[i]}");
}
}
TEXT
Added: Learn C# arrays
Added: Complete exercises
Added: Review methods and parameters
--- To-Do List ---
0. Learn C# arrays
1. Complete exercises
2. Review methods and parameters
Removed: Complete exercises
--- To-Do List ---
0. Learn C# arrays
1. Review methods and parameters
Simple Text Analyzer
Goal: Perform word frequency analysis on input text, use StringBuilder to concatenate results, and encapsulate analysis functions in methods.
Requirements:
- Count total words and total characters
- Find the longest word
- Use StringBuilder to build the analysis report
- Split analysis logic into independent methods
Example
CSHARP
string text = "CSharp is a powerful programming language and programming is fun";
int wordCount = CountWords(text);
int charCount = CountChars(text);
string longest = FindLongestWord(text);
var report = BuildReport(text, wordCount, charCount, longest);
Console.WriteLine(report);
int CountWords(string input)
{
if (string.IsNullOrWhiteSpace(input)) return 0;
string[] words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
return words.Length;
}
int CountChars(string input)
{
return input.Length;
}
string FindLongestWord(string input)
{
if (string.IsNullOrWhiteSpace(input)) return "";
string[] words = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string longest = words[0];
foreach (string w in words)
{
if (w.Length > longest.Length) longest = w;
}
return longest;
}
StringBuilder BuildReport(string input, int words, int chars, string longestWord)
{
var sb = new StringBuilder();
sb.AppendLine("===== Text Analysis Report =====");
sb.AppendLine($"Original: {input}");
sb.AppendLine($"Word count: {words}");
sb.AppendLine($"Character count: {chars}");
sb.AppendLine($"Longest word: {longestWord} ({longestWord.Length} chars)");
sb.Append("===== Analysis Complete =====");
return sb;
}
TEXT
===== Text Analysis Report =====
Original: CSharp is a powerful programming language and programming is fun
Word count: 10
Character count: 60
Longest word: programming (11 chars)
===== Analysis Complete =====
❓ FAQ
Q What does
if (!swapped) break do in bubble sort?A If no swaps occur in a pass, the array is already sorted. Breaking early saves time by avoiding unnecessary iterations.
Q Why do we need to shift the array forward after removing an element from the to-do list?
A Arrays are stored contiguously. After removing a middle element, subsequent elements must shift forward to fill the gap, otherwise null gaps would appear.
Q What is the difference between StringBuilder and concatenating strings with
+?A StringBuilder reuses the same buffer in memory, avoiding the creation of a new string object with each concatenation. It performs better for large numbers of concatenations.
Q What does
StringSplitOptions.RemoveEmptyEntries do?A By default, Split preserves empty string entries. Adding this option automatically removes empty items produced by consecutive delimiters.
📖 Summary
- Bubble sort achieves ascending order through nested loops and swaps per pass; early exit optimization reduces unnecessary traversals
- Passing arrays as method parameters enables traversal and computation inside methods, keeping the main logic clear
- An array-based to-do list requires manual management of element count and shifting, illustrating the fixed-size nature of arrays
- StringBuilder is suitable for repeated string concatenation; method decomposition makes text analysis logic easier to maintain and reuse
📝 Exercises
- Modify the bubble sort to sort in descending order, and output the intermediate results after each pass
- Add a method to the student score statistics that returns a list of indices for all failing scores (below 60)
- Add a "mark complete" feature to the to-do list; completed items should display with
[✓]prefixed - Add word frequency counting to the text analyzer, outputting the occurrence count for each word



