Material didáctico para programación en C# consola: arreglos unidimensionales, multidimensionales, archivos, ejemplos, ejercicios y prácticas.
Un arreglo es una estructura que permite almacenar múltiples valores del mismo tipo en una sola variable, organizados por índices.
using System;
class Programa
{
static void Main()
{
// Arreglo de 5 enteros
int[] numeros = new int[5];
numeros[0] = 10;
numeros[1] = 20;
numeros[2] = 30;
numeros[3] = 40;
numeros[4] = 50;
Console.WriteLine("Elemento en índice 0: " + numeros[0]);
Console.WriteLine("Elemento en índice 4: " + numeros[4]);
}
}
Un arreglo puede ser de cualquier tipo de dato: int, double, string, bool, tipos definidos por el usuario, etc.
using System;
class Programa
{
static void Main()
{
// Arreglo de enteros
int[] edades = { 18, 20, 25 };
// Arreglo de cadenas
string[] nombres = { "Ana", "Luis", "María" };
// Arreglo de booleanos
bool[] activos = { true, false, true };
Console.WriteLine("Nombre: " + nombres[0] + ", Edad: " + edades[0] + ", Activo: " + activos[0]);
}
}
Formas comunes de declarar arreglos:
// Declaración y creación
int[] numeros = new int[3];
// Declaración, creación e inicialización
int[] otrosNumeros = new int[] { 1, 2, 3 };
// Declaración e inicialización implícita
int[] masNumeros = { 4, 5, 6 };
int[]).int[,]).
// Unidimensional
int[] vector = new int[5];
// Bidimensional (matriz)
int[,] matriz = new int[3, 3];
using System;
class Programa
{
static void Main()
{
int[] numeros = { 5, 10, 15, 20 };
for (int i = 0; i < numeros.Length; i++)
{
Console.WriteLine("Elemento[" + i + "] = " + numeros[i]);
}
}
}
using System;
class Programa
{
static void Main()
{
int[] edades = new int[3];
for (int i = 0; i < edades.Length; i++)
{
Console.Write("Ingresa la edad " + (i + 1) + ": ");
edades[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Edades capturadas:");
for (int i = 0; i < edades.Length; i++)
{
Console.WriteLine(edades[i]);
}
}
}
using System;
class Programa
{
static void Main()
{
int[] valores = { 2, 4, 6, 8 };
int suma = 0;
for (int i = 0; i < valores.Length; i++)
{
suma += valores[i];
}
Console.WriteLine("La suma es: " + suma);
}
}
using System;
class Programa
{
static void Main()
{
int[,] matriz = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < matriz.GetLength(0); i++)
{
for (int j = 0; j < matriz.GetLength(1); j++)
{
Console.Write(matriz[i, j] + " ");
}
Console.WriteLine();
}
}
}
using System;
class Programa
{
static void Main()
{
int[,] matriz = new int[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("Valor [" + i + "," + j + "]: ");
matriz[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("Matriz capturada:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(matriz[i, j] + " ");
}
Console.WriteLine();
}
}
}
using System;
class Programa
{
static void Main()
{
int[,] matriz = { { 1, 2, 3 }, { 4, 5, 6 } };
int suma = 0;
for (int i = 0; i < matriz.GetLength(0); i++)
{
for (int j = 0; j < matriz.GetLength(1); j++)
{
suma += matriz[i, j];
}
}
Console.WriteLine("Suma total: " + suma);
}
}
string[] nombres = { "Ana", "Luis", "María" };
for (int i = 0; i < nombres.Length; i++)
{
Console.WriteLine(nombres[i]);
}
double[] calificaciones = { 8.5, 9.0, 7.5 };
double suma = 0;
for (int i = 0; i < calificaciones.Length; i++)
{
suma += calificaciones[i];
}
double promedio = suma / calificaciones.Length;
Console.WriteLine("Promedio: " + promedio);
int[] datos = { 3, 7, 10, 15 };
int buscado = 10;
bool encontrado = false;
for (int i = 0; i < datos.Length; i++)
{
if (datos[i] == buscado)
{
encontrado = true;
break;
}
}
Console.WriteLine(encontrado ? "Encontrado" : "No encontrado");
int[,] matriz = new int[2, 3]
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
for (int i = 0; i < matriz.GetLength(0); i++)
{
for (int j = 0; j < matriz.GetLength(1); j++)
{
Console.Write(matriz[i, j] + " ");
}
Console.WriteLine();
}
int[,,] cubo = new int[2, 2, 2]
{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};
Console.WriteLine(cubo[1, 1, 1]); // 8
Un archivo es un recurso de almacenamiento en disco donde podemos guardar y recuperar datos.
En C# se manejan mediante clases como File, FileStream, StreamWriter, StreamReader, etc.
using System;
using System.IO;
class Programa
{
static void Main()
{
File.WriteAllText("datos.txt", "Hola, archivo en C#");
Console.WriteLine("Archivo creado.");
}
}
Algunos tipos comunes:
.txt).csv)
File.WriteAllText("ejemplo1.txt", "Contenido de ejemplo 1");
string[] lineas = { "Línea 1", "Línea 2", "Línea 3" };
File.WriteAllLines("ejemplo2.txt", lineas);
string csv = "Nombre,Edad\nAna,20\nLuis,22";
File.WriteAllText("personas.csv", csv);
using (StreamWriter sw = new StreamWriter("salida.txt"))
{
sw.WriteLine("Línea escrita con StreamWriter");
}
using (StreamReader sr = new StreamReader("salida.txt"))
{
string contenido = sr.ReadToEnd();
Console.WriteLine(contenido);
}
using (StreamWriter sw = new StreamWriter("salida.txt", true))
{
sw.WriteLine("Nueva línea agregada.");
}
using (StreamReader sr = new StreamReader("salida.txt"))
{
string linea;
while ((linea = sr.ReadLine()) != null)
{
Console.WriteLine(linea);
}
}
Program.cs.Reemplaza las rutas por tus propias capturas.
Leer 5 números, guardarlos en un arreglo y mostrar el mayor.
int[] numeros = new int[5];
for (int i = 0; i < 5; i++)
{
Console.Write("Número " + (i + 1) + ": ");
numeros[i] = int.Parse(Console.ReadLine());
}
int mayor = numeros[0];
for (int i = 1; i < 5; i++)
{
if (numeros[i] > mayor) mayor = numeros[i];
}
Console.WriteLine("El mayor es: " + mayor);
string[] nombres = new string[3];
int[] edades = new int[3];
for (int i = 0; i < 3; i++)
{
Console.Write("Nombre: ");
nombres[i] = Console.ReadLine();
Console.Write("Edad: ");
edades[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < 3; i++)
{
Console.WriteLine(nombres[i] + " tiene " + edades[i] + " años.");
}
using System.IO;
string[] lineas = { "Línea 1", "Línea 2", "Línea 3" };
File.WriteAllLines("ejercicio3.txt", lineas);
Console.WriteLine("Archivo ejercicio3.txt creado.");
string[] productos = { "Lapiz", "Cuaderno", "Borrador" };
File.WriteAllLines("productos.txt", productos);
Console.WriteLine("Productos guardados en productos.txt");
if (File.Exists("productos.txt"))
{
string[] lineasLeidas = File.ReadAllLines("productos.txt");
Console.WriteLine("Contenido de productos.txt:");
foreach (string linea in lineasLeidas)
{
Console.WriteLine(linea);
}
}
else
{
Console.WriteLine("El archivo productos.txt no existe.");
}
Puedes agregar diagramas de flujo, capturas de consola o esquemas de arreglos.