← C EspañolChapter 06 of 13

Arreglos y Cadenas

## Objetivos de Aprendizaje - Crear e inicializar arreglos - Acceder y modificar elementos de arreglos - Trabajar con cadenas - Dominar operaciones con arreglos ## Declarar Arreglos ### Sintaxis ```c int numbers[5]; // Declaración int numbers[5] = {0}; // Declaración con inicialización ``` ### Inicialización ```c // Por tamaño (elementos inicializados a cero) int numbers[5] = {0}; // Resultado: [0, 0, 0, 0, 0] // Con valores int numbers[5] = {1, 2, 3, 4, 5}; // Inicialización parcial (el resto son 0) int numbers[5] = {1, 2}; // Resultado: [1, 2, 0, 0, 0] // Tamaño inferido del inicializador int numbers[] = {1, 2, 3, 4, 5}; ``` ### Inicialización por Defecto ```c int numbers[3]; // Contiene valores basura (indefinido) int numbers[3] = {0}; // Todos los elementos = 0 ``` ## Longitud del Arreglo ```c int numbers[] = {1, 2, 3, 4, 5}; int length = sizeof(numbers) / sizeof(numbers[0]); // 5 ``` ## Acceder a Elementos ### Índice ```c int numbers[] = {10, 20, 30, 40, 50}; printf("%d\n", numbers[0]); // Primer elemento: 10 printf("%d\n", numbers[4]); // Último elemento: 50 printf("%d\n", numbers[sizeof(numbers)/sizeof(numbers[0]) - 1]); // Último elemento ``` ### Modificar Elementos ```c int numbers[] = {10, 20, 30}; numbers[0] = 15; // Cambiar primer elemento numbers[2] = 35; // Cambiar último elemento ``` ### Verificación de Límites **Advertencia:** ¡C no verifica los límites del arreglo! ```c int numbers[3]; numbers[5] = 100; // ¡Sin error! Comportamiento indefinido numbers[-1] = 50; // ¡Sin error! Comportamiento indefinido ``` ## Iterar Arreglos ### Bucle for ```c int numbers[] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { printf("%d\n", numbers[i]); } ``` ### Bucle while ```c int numbers[] = {1, 2, 3, 4, 5}; int i = 0; while (i < 5) { printf("%d\n", numbers[i]); i++; } ``` ## Operaciones Comunes ### Suma y Promedio ```c int numbers[] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i++) { sum += numbers[i]; } double average = (double) sum / 5; ``` ### Encontrar Máximo ```c int numbers[] = {3, 7, 2, 9, 4}; int max = numbers[0]; for (int i = 1; i < 5; i++) { if (numbers[i] > max) { max = numbers[i]; } } ``` ### Contar Coincidencias ```c int numbers[] = {1, 2, 3, 2, 4, 2, 5}; int target = 2; int count = 0; for (int i = 0; i < 7; i++) { if (numbers[i] == target) { count++; } } ``` ## Ordenamiento ### Ordenamiento Burbuja ```c void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } ``` ### Usando qsort ```c #include int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main(void) { int numbers[] = {3, 1, 4, 1, 5, 9}; int size = sizeof(numbers) / sizeof(numbers[0]); qsort(numbers, size, sizeof(int), compare); return 0; } ``` ## Arreglos Multidimensionales ### Declaración ```c int matrix[3][4]; // 3 filas, 4 columnas ``` ### Inicialización de Arreglos Multidimensionales ```c int matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; ``` ### Acceder ```c printf("%d\n", matrix[0][0]); // Primer elemento: 1 printf("%d\n", matrix[2][3]); // Último elemento: 12 matrix[1][2] = 10; // Modificar elemento ``` ### Iterar ```c for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } ``` ### Orden Mayor de Fila ```c int matrix[2][3] = {1, 2, 3, 4, 5, 6}; // Se almacena como: // Fila 0: [1, 2, 3] // Fila 1: [4, 5, 6] ``` ## Cadenas ### Conceptos Básicos de Cadenas ```c char name[] = "Hello"; // {'H', 'e', 'l', 'l', 'o', '\0'} ``` ### Inicialización de Cadenas ```c char str1[] = "Hello"; // Con terminador nulo char str2[6] = "Hello"; // Tamaño explícito char str3[10] = "Hello"; // Arreglo más grande (el resto es '\0') ``` ### Arreglo de Caracteres vs Literal de Cadena ```c char arr[] = "Hello"; // Mutable - puede ser modificado char *ptr = "Hello"; // Apunta a memoria de solo lectura (comportamiento indefinido para modificar) ``` **Advertencia:** Los literales de cadena típicamente se almacenan en memoria de solo lectura. ## Funciones de Cadenas (string.h) ### strlen - Longitud de Cadena ```c #include char str[] = "Hello"; size_t len = strlen(str); // 5 ``` ### strcpy - Copiar Cadena ```c #include char dest[20]; strcpy(dest, "Hello"); ``` ### strncpy - Copiar N Caracteres ```c #include char dest[10]; strncpy(dest, "Hello World", sizeof(dest) - 1); dest[9] = '\0'; // Asegurar terminación nula ``` ### strcat - Concatenar ```c #include char str[20] = "Hello"; strcat(str, " World"); // "Hello World" ``` ### strncat - Concatenar N Caracteres ```c #include char str[20] = "Hello"; strncat(str, " World!!!", 6); // "Hello World" ``` ### strcmp - Comparar Cadenas ```c #include strcmp("abc", "abc"); // 0 (iguales) strcmp("abc", "def"); // negativo (< 0) strcmp("xyz", "abc"); // positivo (> 0) ``` ### strncmp - Comparar N Caracteres ```c #include strncmp("hello", "help", 3); // 0 (primeros 3 caracteres iguales) ``` ## Entrada de Cadenas ### scanf ```c char name[50]; scanf("%49s", name); // Lee hasta espacio en blanco printf("%s\n", name); ``` ### fgets (Recomendado) ```c #include char name[100]; fgets(name, sizeof(name), stdin); name[strcspn(name, "\n")] = '\0'; // Eliminar salto de línea ``` ## Cadena a Número ```c #include int i = atoi("42"); double d = atof("3.14"); long l = atol("123456"); ``` ### Conversión Segura (strtol, strtod) ```c #include char *endptr; int i = (int)strtol("123", &endptr, 10); if (*endptr != '\0') { // Conversión fallida } double d = strtod("3.14", &endptr); ``` ## Patrones Comunes ### Invertir Cadena ```c void reverse(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { char temp = str[i]; str[i] = str[len - 1 - i]; str[len - 1 - i] = temp; } } ``` ### Verificar Palíndromo ```c int isPalindrome(const char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - 1 - i]) { return 0; } } return 1; } ``` ## Resumen - Arreglos: `tipo nombre[tamaño]` o `tipo nombre[] = {valores}` - Acceso: `arreglo[índice]` - Tamaño del arreglo: `sizeof(arreglo) / sizeof(arreglo[0])` - Las cadenas son arreglos de caracteres que terminan en `\0` - Usar funciones de `string.h` para operaciones de cadenas - Usar `fgets()` para entrada segura de cadenas - C no verifica los límites del arreglo

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →