404 Not Found

404 Not Found


nginx

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:

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}");
▶ Try it Yourself
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:

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;
}
▶ Try it Yourself
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:

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]}");
    }
}
▶ Try it Yourself
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:

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;
}
▶ Try it Yourself
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

📝 Exercises

  1. Modify the bubble sort to sort in descending order, and output the intermediate results after each pass
  2. Add a method to the student score statistics that returns a list of indices for all failing scores (below 60)
  3. Add a "mark complete" feature to the to-do list; completed items should display with [✓] prefixed
  4. Add word frequency counting to the text analyzer, outputting the occurrence count for each word
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏