C#: C# Examples

1. FizzBuzz

Iterate from 1 to 100: print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, otherwise print the number itself.

▶ Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 100; i++)
        {
            if (i % 15 == 0)
                Console.WriteLine("FizzBuzz");
            else if (i % 3 == 0)
                Console.WriteLine("Fizz");
            else if (i % 5 == 0)
                Console.WriteLine("Buzz");
            else
                Console.WriteLine(i);
        }
    }
}
▶ Try it Yourself
TEXT
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...
98
Fizz
Buzz

2. Fibonacci Sequence

Print the first 20 numbers of the Fibonacci sequence, where each number is the sum of the two preceding ones.

▶ Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        int a = 0, b = 1;
        for (int i = 0; i < 20; i++)
        {
            Console.Write(a + " ");
            int temp = a;
            a = b;
            b = temp + b;
        }
        Console.WriteLine();
    }
}
▶ Try it Yourself
TEXT
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

3. Multiplication Table

Print a classic multiplication table in triangular arrangement.

▶ Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 9; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                Console.Write($"{j}x{i}={i * j}\t");
            }
            Console.WriteLine();
        }
    }
}
▶ Try it Yourself
TEXT
1x1=1
1x2=2   2x2=4
1x3=3   2x3=6   3x3=9
1x4=4   2x4=8   3x4=12  4x4=16
1x5=5   2x5=10  3x5=15  4x5=20  5x5=25
1x6=6   2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7=7   2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8=8   2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9=9   2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81

4. Prime Check

Determine whether a user-input positive integer is prime and print the result.

▶ Example

CSHARP
using System;

class Program
{
    static bool IsPrime(int n)
    {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++)
        {
            if (n % i == 0) return false;
        }
        return true;
    }

    static void Main()
    {
        int number = 29;
        if (IsPrime(number))
            Console.WriteLine($"{number} is prime");
        else
            Console.WriteLine($"{number} is not prime");

        number = 35;
        if (IsPrime(number))
            Console.WriteLine($"{number} is prime");
        else
            Console.WriteLine($"{number} is not prime");
    }
}
▶ Try it Yourself
TEXT
29 is prime
35 is not prime

5. Palindrome Detection

Determine whether a string is a palindrome (reads the same forward and backward).

▶ Example

CSHARP
using System;

class Program
{
    static bool IsPalindrome(string s)
    {
        int left = 0, right = s.Length - 1;
        while (left < right)
        {
            if (s[left] != s[right]) return false;
            left++;
            right--;
        }
        return true;
    }

    static void Main()
    {
        string[] tests = { "racecar", "hello", "level", "world" };
        foreach (string t in tests)
        {
            Console.WriteLine($"{t} -> {(IsPalindrome(t) ? "is palindrome" : "is not palindrome")}");
        }
    }
}
▶ Try it Yourself
TEXT
racecar -> is palindrome
hello -> is not palindrome
level -> is palindrome
world -> is not palindrome

6. Reverse String

Reverse an input string and print the result.

▶ Example

CSHARP
using System;

class Program
{
    static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

    static void Main()
    {
        string original = "Hello CSharp";
        string reversed = ReverseString(original);
        Console.WriteLine($"Original: {original}");
        Console.WriteLine($"Reversed: {reversed}");
    }
}
▶ Try it Yourself
TEXT
Original: Hello CSharp
Reversed: prahSC olleH

7. Count Vowels

Count the occurrences of vowel letters (a, e, i, o, u, case-insensitive) in a string.

▶ Example

CSHARP
using System;

class Program
{
    static int CountVowels(string s)
    {
        int count = 0;
        string vowels = "aeiouAEIOU";
        foreach (char c in s)
        {
            if (vowels.IndexOf(c) >= 0)
                count++;
        }
        return count;
    }

    static void Main()
    {
        string text = "Hello World Programming";
        int result = CountVowels(text);
        Console.WriteLine($"String: {text}");
        Console.WriteLine($"Vowel count: {result}");
    }
}
▶ Try it Yourself
TEXT
String: Hello World Programming
Vowel count: 6

8. File I/O

Demonstrate basic text file write and read operations.

▶ Example

CSHARP
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "test.txt";
        string[] lines = { "First line", "Second line", "Third line" };

        File.WriteAllLines(path, lines);
        Console.WriteLine("Write complete");

        string[] readLines = File.ReadAllLines(path);
        Console.WriteLine("Read content:");
        foreach (string line in readLines)
        {
            Console.WriteLine(line);
        }

        File.Delete(path);
    }
}
▶ Try it Yourself
TEXT
Write complete
Read content:
First line
Second line
Third line

9. Number Guessing Game

The program generates a random integer between 1 and 100. The player makes guesses and the program hints whether the guess is too high or too low until the correct number is found.

▶ Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        Random rnd = new Random(42);
        int target = rnd.Next(1, 101);
        int[] guesses = { 50, 75, 62, 68, 71, 73, 72 };
        int attempts = 0;

        Console.WriteLine($"Target number: {target} (shown for demo only)");
        Console.WriteLine("---");

        foreach (int guess in guesses)
        {
            attempts++;
            if (guess < target)
                Console.WriteLine($"Attempt {attempts}: {guess} - Too low");
            else if (guess > target)
                Console.WriteLine($"Attempt {attempts}: {guess} - Too high");
            else
            {
                Console.WriteLine($"Attempt {attempts}: {guess} - Correct!");
                break;
            }
        }
    }
}
▶ Try it Yourself
TEXT
Target number: 72 (shown for demo only)
---
Attempt 1: 50 - Too low
Attempt 2: 75 - Too high
Attempt 3: 62 - Too low
Attempt 4: 68 - Too low
Attempt 5: 71 - Too low
Attempt 6: 73 - Too high
Attempt 7: 72 - Correct!

10. Student Grade Calculator

Given a set of student grades, calculate the average, highest, and lowest scores.

▶ Example

CSHARP
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        double[] scores = { 85.5, 92.0, 78.5, 96.0, 88.0, 73.5, 91.0 };

        double average = scores.Average();
        double max = scores.Max();
        double min = scores.Min();

        Console.WriteLine("Student grades: " + string.Join(", ", scores));
        Console.WriteLine($"Average: {average:F1}");
        Console.WriteLine($"Highest: {max:F1}");
        Console.WriteLine($"Lowest: {min:F1}");
    }
}
▶ Try it Yourself
TEXT
Student grades: 85.5, 92, 78.5, 96, 88, 73.5, 91
Average: 86.4
Highest: 96.0
Lowest: 73.5

❓ FAQ

Q How do I run these C# examples?
A Copy the code into a .cs file and run with dotnet run, or use an online C# compiler like dotnetfiddle.net.
Q Can I modify the examples and see results?
A Yes! Save the file and run dotnet run again. C# compiles to bytecode, so changes take effect immediately.
Q Where are the larger examples?
A See lesson 36 — the Final Project. This index only collects short, single-concept snippets.

📖 Summary

📝 Exercises

  1. Pick any example, modify it, and document the new behavior in a comment.
  2. Combine two examples (e.g., variables + events) into a single program.
  3. Create your own example page teaching a concept you find confusing.
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%

🙏 帮我们做得更好

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

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