C#: Exemplos em C#

1. FizzBuzz

Faça uma iteração de 1 a 100: imprima “Fizz” para os múltiplos de 3, “Buzz” para os múltiplos de 5, “FizzBuzz” para os múltiplos de ambos; caso contrário, imprima o próprio número.

▶ Exemplo

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);
        }
    }
}
▶ Experimente
TEXT 📖 Somente leitura
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...
98
Fizz
Buzz

2. Sequência de Fibonacci

Imprima os primeiros 20 números da sequência de Fibonacci, em que cada número é a soma dos dois números anteriores.

▶ Exemplo

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();
    }
}
▶ Experimente
TEXT 📖 Somente leitura
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

3. Tabuada

Imprima uma tabuada clássica disposta em formato triangular.

▶ Exemplo

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();
        }
    }
}
▶ Experimente
TEXT 📖 Somente leitura
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. Verificação do Prime

Determine se um número inteiro positivo inserido pelo usuário é primo e exiba o resultado.

▶ Exemplo

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");
    }
}
▶ Experimente
TEXT 📖 Somente leitura
29 is prime
35 is not prime

5. Detecção de palíndromos

Determine se uma sequência de caracteres é um palíndromo (se lê da mesma forma tanto para a frente quanto para trás).

▶ Exemplo

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")}");
        }
    }
}
▶ Experimente
TEXT 📖 Somente leitura
racecar -> is palindrome
hello -> is not palindrome
level -> is palindrome
world -> is not palindrome

6. Inverter a sequência de caracteres

Inverta uma string de entrada e imprima o resultado.

▶ Exemplo

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}");
    }
}
▶ Experimente
TEXT 📖 Somente leitura
Original: Hello CSharp
Reversed: prahSC olleH

7. Contar as vogais

Conte o número de ocorrências das letras vocálicas (a, e, i, o, u, sem distinção entre maiúsculas e minúsculas) em uma sequência de caracteres.

▶ Exemplo

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}");
    }
}
▶ Experimente
TEXT 📖 Somente leitura
String: Hello World Programming
Vowel count: 6

8. E/S de arquivos

Demonstrar operações básicas de leitura e gravação em arquivos de texto.

▶ Exemplo

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);
    }
}
▶ Experimente
TEXT 📖 Somente leitura
Write complete
Read content:
First line
Second line
Third line

9. Jogo de adivinhar números

O programa gera um número inteiro aleatório entre 1 e 100. O jogador faz suposições e o programa dá dicas se a suposição está muito alta ou muito baixa, até que o número correto seja adivinhado.

▶ Exemplo

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;
            }
        }
    }
}
▶ Experimente
TEXT 📖 Somente leitura
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. Calculadora de notas dos alunos

Dado um conjunto de notas dos alunos, calcule a média, a nota mais alta e a nota mais baixa.

▶ Exemplo

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}");
    }
}
▶ Experimente
TEXT 📖 Somente leitura
Student grades: 85.5, 92, 78.5, 96, 88, 73.5, 91
Average: 86.4
Highest: 96.0
Lowest: 73.5

❓ Perguntas Frequentes

P: Como faço para executar esses exemplos em C#? R: Copie o código para um arquivo .cs e execute com o comando dotnet run, ou use um compilador online de C#, como o dotnetfiddle.net.

P: Posso modificar os exemplos e ver os resultados? R: Sim! Salve o arquivo e execute o comando dotnet run novamente. O C# é compilado para bytecode, portanto as alterações entram em vigor imediatamente.

P: Onde estão os exemplos mais extensos? R: Consulte a lição 36 — o Projeto Final. Este índice reúne apenas trechos curtos, com um único conceito.

📖 Resumo

📝 Exercícios

  1. Escolha qualquer exemplo, modifique-o e documente o novo comportamento em um comentário.
  2. Combine dois exemplos (por exemplo, variáveis + eventos) em um único programa.
  3. Crie sua própria página de exemplo para explicar um conceito que você ache confuso.
Web-Tutorial.com

Equipe Técnica Web-Tutorial

Uma plataforma de tutoriais mantida por diversos desenvolvedores. Cada tutorial é escrito e revisado por profissionais da área correspondente. Trabalhamos para manter nosso conteúdo preciso e confiável — se encontrar algum problema, avise-nos.

100%