Arrays
Um array guarda um número fixo de valores do mesmo tipo, cada um acessado por um índice que começa em 0.
Como funciona
Crie, leia, altere, percorra e ordene arrays em C#, inclusive bidimensionais.
Length dá o tamanho e ^1 lê o último elemento. foreach visita cada elemento, Array.Sort ordena no próprio lugar, new int[3] começa com zeros e int[,] cria uma grade indexada por linha e coluna.
Veja como funciona
Clique numa caixa ou mova o controle para escolher um índice. Insira ou apague para ver por que todos os elementos seguintes precisam se deslocar.
Exemplo de C# executável
using System;
using System.Linq;
class Program
{
static void Main()
{
// An array has a fixed length set when it is created.
int[] scores = { 72, 95, 88, 64 };
Console.WriteLine($"Length: {scores.Length}");
Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");
scores[3] = 70; // elements can be changed, the length cannot
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
Console.WriteLine($"Sum: {sum}, average: {sum / (double)scores.Length}");
// Array.Sort sorts in place; string.Join prints the elements.
Array.Sort(scores);
Console.WriteLine($"Sorted: {string.Join(", ", scores)}");
Console.WriteLine($"Max: {scores.Max()}");
// new int[3] creates an array of zeros.
int[] counts = new int[3];
counts[1] = 5;
Console.WriteLine($"Counts: {string.Join(" ", counts)}");
// A 2D array is indexed by row and column.
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine($"grid[1, 2] = {grid[1, 2]}");
}
}
Length: 4
First: 72, last: 64
Sum: 325, average: 81.25
Sorted: 70, 72, 88, 95
Max: 95
Counts: 0 5 0
grid[1, 2] = 6Pratique com o depurador
Pratique com um desafio
Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.
- Count Positive Numbers Count the values greater than zero in a list. Fácil
- Soma Acumulada Substitua cada valor pelo total acumulado até o momento. Fácil
- Swap First and Last Exchange the first and last items of a list. Fácil