BUCLE
FOR
//Hacer un triangulo de “*”:
using System;
public class HolaMundo
{
public static void Main(string[]
args)
{
for (int i = 0; i <= 5; i++)
{
for (int j = 1; j < i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
Console.Write("Hola Mundo");
}
}
ARREGLOS
Los arrays en C# son estructuras de datos
que almacenan una colección secuencial de tamaño fijo de elementos del mismo
tipo, accesibles mediante un índice basado en cero. Se declaran usando
corchetes (tipo[] nombre) y son fundamentales para gestionar conjuntos de datos
de forma eficiente, siendo parte del namespace System.Array.
OPERACIONES
using System;
class Program
{
static void Main()
{
// 1. REGISTRAR (Crear arreglo y asignar valores)
int[] numeros =
new int[5];
for (int i = 0; i < numeros.Length;
i++)
{
Console.Write($"Ingrese el valor {i + 1}: ");
numeros[i] = int.Parse(Console.ReadLine());
}
// 2. MOSTRAR
Console.WriteLine("\nElementos del arreglo:");
for (int i = 0;
i < numeros.Length; i++)
{
Console.WriteLine($"Índice {i}: {numeros[i]}");
}
// 3. BUSCAR
Console.Write("\nIngrese el valor a buscar: ");
int buscar = int.Parse(Console.ReadLine());
bool encontrado = false;
for (int i = 0;
i < numeros.Length; i++)
{
if (numeros[i] == buscar)
{
Console.WriteLine($"Valor
{buscar} encontrado en índice {i}");
encontrado = true;
break; // Detiene la búsqueda
al encontrar el primero
}
}
if (!encontrado) Console.WriteLine("Valor no encontrado.");
// 4. MODIFICAR
Console.Write("\nIngrese el índice a modificar (0-4): ");
int indiceMod = int.Parse(Console.ReadLine());
if (indiceMod >= 0 && indiceMod < numeros.Length)
{
Console.Write("Ingrese el nuevo valor: ");
numeros[indiceMod] = int.Parse(Console.ReadLine());
Console.WriteLine("Valor modificado exitosamente.");
}
else
{
Console.WriteLine("Índice inválido.");
}
}
}
INSERTAR VECTORES:
METODO INSERT Y LIST
using System;
using System.Collections.Generic;
class Program
{
static
void Main()
{
List<int> original = new List<int> { 1, 2, 4, 5 };
int elementoNuevo = 3;
int posicion = 2; // Posición deseada
original.Insert(posicion, elementoNuevo);
// original ahora es { 1, 2, 3, 4, 5 }
Console.WriteLine(string.Join(", ", original));
}
}
Insersion con i y j
using System;
public class HolaMundo
{
public static void Main(string[] args)
{
int[] original = { 1, 2, 4, 5 };
int elementoNuevo = 3;
int posicion = 2; // Posición deseada
int[] nuevoArray = new int[original.Length + 1];
for (int i = 0, j = 0; i < nuevoArray.Length; i++)
{
if (i == posicion)
{
nuevoArray[i] = elementoNuevo;
}
else
{
nuevoArray[i] = original[j];
j++;
}
}
Console.WriteLine("\nElementos del arreglo:");
for (int k = 0; k < nuevoArray.Length; k++)
{
Console.WriteLine($"Índice {k}: {nuevoArray[k]}");
}
}
}
ELIMINAR UN ELEMENTO:
using System;
public class HolaMundo
{
public static void Main(string[] args)
{
Console.Write("Hola Mundo"); int[] datos = { 10, 20, 30, 40 };
int indiceEliminar = 1; // Borrar 20
int[] resultado = new int[datos.Length - 1];
for (int i = 0, j = 0; i < datos.Length; i++)
{
if (i != indiceEliminar)
{
resultado[j] = datos[i];
j++;
}
}
Console.WriteLine("\nElementos del arreglo:");
for (int k = 0; k < resultado.Length; k++)
{
Console.WriteLine($"Índice {k}: {resultado[k]}");
}
// Resultado es { 10, 30, 40 }
}
}
EL MAYOR VALOR:
using System;
public class HolaMundo
{
public static void Main(string[] args)
{
int[] numeros = new int[5];
for (int i = 0; i < numeros.Length; i++)
{
Console.Write($"Ingrese el valor {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 valor es:" + mayor);
}
}
ORDENAMIENTO BURBUJA
using System;
public class HolaMundo
{
public static void Main(string[] args)
{
int x = 0, y = 0;
int[] numeros;
Console.Write("Escribe la cantidad de elementos:");
x = int.Parse(Console.ReadLine());
numeros = new int[x];
for (int w = 0; w < x; w++)
{
Console.Write("escribe el numero[{0}]: ", w);
numeros[w] = int.Parse(Console.ReadLine());
}
for (int i = 1; i < x; i++)
{
for(int j = 0; j < x - 1; j++)
{
if (numeros[i] < numeros[j])
{
y = numeros[i];
numeros[i] = numeros[j];
numeros[j] = y;
}
}
}
for(int z = 0; z < x; z++)
{
Console.WriteLine("{0}-{1}", z + 1, numeros[z]);
Console.ReadKey();
}
}
}
CADENAS
Las cadenas (strings) en C# son objetos
inmutables de la clase System.String que ofrecen métodos útiles para
manipular texto. Estos métodos facilitan tareas como convertir caso, buscar
caracteres o extraer subcadenas. A continuación, un resumen con ejemplos
sencillos.
Métodos de Conversión de Caso
- ToUpper() convierte toda la cadena a
mayúsculas: string texto = "hola mundo"; string mayus =
texto.ToUpper(); // "HOLA MUNDO".
- ToLower() convierte toda la cadena a
minúsculas: string texto = "HOLA MUNDO"; string minus =
texto.ToLower(); // "hola mundo".
Búsqueda y Posición
- IndexOf("caracter") devuelve la posición
(índice) de la primera ocurrencia: string texto = "Hola
mundo"; int pos = texto.IndexOf("m"); // 5.
- LastIndexOf("caracter") busca desde el
final: int ultima = texto.LastIndexOf("o"); // 9.
- Length obtiene la longitud: int largo = texto.Length;
// 10.
Extracción y Modificación
- Substring(inicio, longitud) extrae una
subcadena: string parte = texto.Substring(0, 4); //
"Hola".
- Replace("viejo", "nuevo") reemplaza
texto: string nuevo = texto.Replace("mundo",
"C#"); // "Hola C#".
- Remove(inicio, longitud) elimina caracteres: string
sinFin = texto.Remove(5); // "Hola".
Otras Funciones Útiles
- StartsWith("inicio") verifica si comienza con
texto: bool inicia = texto.StartsWith("Ho"); // true.
- EndsWith("fin") verifica el final: bool
termina = texto.EndsWith("do"); // true.
- Split(' ') divide en array: string[] palabras =
texto.Split(' '); // ["Hola", "mundo"].
FUNCIONES DE CADENAS:
using System;
class Program
{
static void Main()
{
string texto = "Hola Mundo";
Console.WriteLine($"Texto original: '{texto}'");
// Conversión de caso
Console.WriteLine($"ToUpper(): '{texto.ToUpper()}'"); // HOLA MUNDO
Console.WriteLine($"ToLower(): '{texto.ToLower()}'"); // hola mundo
// Longitud
Console.WriteLine($"Length: {texto.Length}"); // 10
// Búsqueda de posiciones
Console.WriteLine($"IndexOf('m'): {texto.IndexOf('m')}"); // 5
Console.WriteLine($"LastIndexOf('o'):
{texto.LastIndexOf('o')}"); // 9
// Extracción de subcadenas
Console.WriteLine($"Substring(0,4):
'{texto.Substring(0,4)}'"); // Hola
Console.WriteLine($"Substring(5):
'{texto.Substring(5)}'"); //
Mundo
// Reemplazo
Console.WriteLine($"Replace: '{texto.Replace("Mundo",
"C#")}'"); // Hola C#
// Eliminación
Console.WriteLine($"Remove(5): '{texto.Remove(5)}'"); // Hola
// Verificaciones
Console.WriteLine($"StartsWith('Ho'):
{texto.StartsWith("Ho")}"); // True
Console.WriteLine($"EndsWith('do'):
{texto.EndsWith("do")}");
// True
// División
string[] palabras = texto.Split(' ');
Console.WriteLine("Split(' '):");
foreach (string palabra in palabras)
{
Console.WriteLine($"- '{palabra}'");
}
// Hola
// Mundo
Console.WriteLine("\n--- Más ejemplos ---");
// Trim (elimina espacios al inicio y final)
string textoConEspacios = "
hola ";
Console.WriteLine($"Trim():
'{textoConEspacios.Trim()}'");
// hola
// Contains (verifica si contiene texto)
Console.WriteLine($"Contains('Mundo'):
{texto.Contains("Mundo")}"); // True
// Insertar texto
Console.WriteLine($"Insert(4, '!!!'): '{texto.Insert(4,
"!!!")}'"); // Hola!!! Mundo
}
}
No hay comentarios.:
Publicar un comentario