Boletín 4 - Estructuras de Datos
Arrays, registros y cadenas de caracteres.
Ejercicio 1
Plantee e implemente un programa en lenguaje C, que utilizando exclusivamente subprogramas, solicite números enteros por teclado y vaya almacenándolos en un array de 10 elementos, mostrando a continuación por pantalla el contenido del array creado.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Miguel Fraga Pico//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
void askNumbers(int *cadena){ int i; printf("Dime un numero"); for(i = 0; i < 10; i++) { scanf("%d", &cadena[i]); printf("Dime otro numero "); } printf("\n");}
void printNumbers(int *cadena){ int i; printf("La cadena es: \n"); for(i = 0; i < 10; i++) { printf("%d ", cadena[i]); }}
int main(){ int cadena[10]; askNumbers(cadena); printNumbers(cadena); return 1;}
Ejercicio 2
Plantee e implemente un programa en lenguaje C, que utilizando exclusivamente subprogramas, solicite nombres de animales por teclado y vaya rellenando un array de 7 elementos, mostrándolos posteriormente por pantalla apropiadamente.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Pablo Portas López <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
// Librerías#include <stdio.h>
// Constantes#define MAX 40#define NANIMAL 7
// Definicionestypedef char nombreanimal[40];
typedef struct{ nombreanimal nombre;}tRegAnimales[NANIMAL];
// Definición funcionesvoid introducirNombres(tRegAnimales listaAnimales);void imprimirNombres(tRegAnimales listaNombres);
// Mainint main() { tRegAnimales listaAnimales;
introducirNombres(listaAnimales); imprimirNombres(listaAnimales);
return 0;}
// Declaración Funcionesvoid introducirNombres(tRegAnimales listaAnimales){ printf("Introduzca los 7 nombres de animales separados por comas: "); for(int i = 0; i < NANIMAL; i++) scanf("%s, ",listaAnimales[i].nombre);}
void imprimirNombres(tRegAnimales listaNombres){ printf("Los 7 nombres són:"); for(int i = 0; i < NANIMAL; i++) printf(" %s",listaNombres[i].nombre); printf(".");}
Ejercicio 3
Plantee e implemente un programa en lenguaje C, que utilizando exclusivamente subprogramas, calcule la suma de los elementos de un array de números reales proporcionados por el usuario, considerando como máximo 30 elementos.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Pablo Portas López <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
// Librerías#include <stdio.h>
// Constantes#define MAX 30
// Definicionestypedef float listanumeros[MAX];
// Definición funcionesvoid introducirPorTeclado(listanumeros numeros);
void imprimirSumatorio(const listanumeros numeros);
// Mainint main() { listanumeros lnumeros; introducirPorTeclado(lnumeros); imprimirSumatorio(lnumeros); return 0;}
// Declaración Funcionesvoid introducirPorTeclado(listanumeros numeros) { printf("Introduzca los números que quiere sumar, para terminar introduzca 0: "); // Expresión lógica dentro del for: mientras i < 30 y a partir del primer número que el número // introducido anteriormente (i-1) no fuera 0. for (int i = 0; i < MAX && (i < 1 || numeros[i - 1] != 0.0); i++) scanf("%f", &numeros[i]);}
void imprimirSumatorio(const listanumeros numeros) { float suma = 0; // Impresión hasta el MAX o hasta llegar al primer 0 for (int i = 0; i < MAX && numeros[i] != 0; i++) suma += numeros[i]; printf("El sumatorio final son: %.2f", suma);}
Ejercicio 4
Plantee e implemente un programa en lenguaje C que almacene en memoria las horas de estudio que dedica un alumno a una asignatura determinada durante una semana. Solicite los datos apropiadamente al usuario y calcule y muestre la media de horas diarias empleadas en esa asignatura, asimismo indique el día en el que ha estado más aplicado (mayor número de horas estudiando) y más vago (menor número de horas estudiando).
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Pablo Portas López <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
// Librerías#include <stdio.h>
// Definicionestypedef struct { int horas; char nombre[10];} tRegdiasemana;
typedef tRegdiasemana vHorasSemana[7];
// Definición funcionesvoid introducirHoras(vHorasSemana horas);
void imprimirMediaYMostrarDias(vHorasSemana horas);
void ordenarDeMayorAMenor(vHorasSemana horas);
// Mainint main() { // Inicializo el Registro para cada día de la semana vHorasSemana horasestudio = {{0, "Lunes"}, {0, "Martes"}, {0, "Miércoles"}, {0, "Jueves"}, {0, "Viernes"}, {0,"Sábado"}, {0,"Domingo"}}; introducirHoras(horasestudio); imprimirMediaYMostrarDias(horasestudio); return 0;}
// Declaración Funcionesvoid introducirHoras(vHorasSemana horas) { printf("Introduzca las horas de estudio que le ha dedicado a Pro 1: \n"); for (int i = 0; i < 7; i++) { printf("%s: ",horas[i].nombre); scanf("%d", &horas[i].horas); while ((getchar()) != '\n'); // Limpio Buffer }
}
void imprimirMediaYMostrarDias(vHorasSemana horas) { int media = 0; for (int i = 0; i < 7; i++) media += horas[i].horas; media = media / 7; printf("La media de horas diarias: %d\n", media); ordenarDeMayorAMenor(horas); printf("El día que más horas estudiaste fué el %s (%d horas) y el que menos %s (%d horas).",horas[6].nombre,horas[6].horas,horas[0].nombre,horas[0].horas);}
void ordenarDeMayorAMenor(vHorasSemana horas){ vHorasSemana aux; for(int j = 1; j < 6; j++) { for (int i = 0; i < 7-j; i++) { if (horas[i].horas > horas[i + 1].horas) { aux[i] = horas[i]; // Movemos al aux horas[i] = horas[i + 1]; // Movemos el segundo al primer hueco horas[i + 1] = aux[i]; // Copiamos el valor del primero al segundo hueco } } }}
Ejercicio 5
Plantee e implemente un programa en lenguaje C para almacenar las temperaturas (en ºC) registradas en una ciudad durante un día hora a hora (0-23). Introduzca las temperaturas a partir de los datos proporcionados por el usuario, visualice ordenadamente las temperaturas registradas y calcule y muestre por pantalla la temperatura máxima, mínima y media alcanzadas.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define MAX 24
void pedirTemperatura(float temp[], int n);
void mostrarTemperaturas(float temp[], int n);
float temperaturaMedia(float temp[], int n);
float temperaturaMaxima(float temp[], int n);
float temperaturaMinima(float temp[], int n);
int main() { float temperatura[MAX];
pedirTemperatura(temperatura, MAX); mostrarTemperaturas(temperatura, MAX); printf("\nTemperatura maxima: %.2f\n", temperaturaMaxima(temperatura, MAX)); printf("Temperatura minima: %.2f\n", temperaturaMinima(temperatura, MAX)); printf("Temperatura media: %.2f\n", temperaturaMedia(temperatura, MAX));}
void pedirTemperatura(float temp[], int n) { printf("Introduce la temperatura de la ciudad:\n"); for (int i = 0; i < n; i++) { printf("Hora %d: \n", i + 1); scanf("%f", &temp[i]); }}
void mostrarTemperaturas(float temp[], int n) { printf("\nTEMPERATURAS A LO LARGO DEL DIA\n"); for (int i = 0; i < n; i++) printf("%d:00 - %.2f C\n", i, temp[i]);}
float medioTemperatura(float temp[], int n) { float tempTotal = 0; for (int i = 0; i < n; i++) { tempTotal += temp[i]; } return (tempTotal / n);}
float temperaturaMaxima(float temp[], int n) { float tempMax = temp[0];
for (int i = 1; i < n; i++) { if (temp[i] > tempMax) tempMax = i; } return tempMax;}
float temperaturaMinima(float temp[], int n) { float tempMin = temp[0];
for (int i = 1; i < n; i++) { if (temp[i] < tempMin) tempMin = i; } return tempMin;}
Ejercicio 7
Plantee e implemente un programa en lenguaje C que solicite al usuario su presupuesto semanal (en euros) y sus gastos diarios en distintos conceptos (por ejemplo transporte, alimentación y ocio) durante una semana. Calcule y muestre por pantalla el gasto total de la semana, el gasto semanal y el gasto medio diario en los distintos conceptos y el % del presupuesto semanal que gastó cada día.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define SEMANA 7
void pedirPresupuesto(float *pSemanal);
void pedirGastos(float gasto[], int n);
float totalGastosPorCategoria(float gasto[], int n);
float gastosTotalesSemanales(float transporte[], float alimentacion[], float ocio[]);
float gastoMedioDiario(float gasto[], int n);
float presupuestoGastado(float gastosTotales, float presupuesto);
int main() { float pSemanal, gTransporte[SEMANA], gAlimentacion[SEMANA], gOcio[SEMANA];
pedirPresupuesto(&pSemanal); printf("\nGastos semanales en transporte(euros):\n"); pedirGastos(gTransporte, SEMANA); printf("\nGastos semanales en alimentacion(euros):\n"); pedirGastos(gAlimentacion, SEMANA); printf("\nGastos semanales en ocio(euros):\n"); pedirGastos(gOcio, SEMANA);
printf("\nGasto en transporte: %.2f\n", totalGastosPorCategoria(gTransporte, SEMANA)); printf("\nGasto en alimentacion: %.2f\n", totalGastosPorCategoria(gAlimentacion, SEMANA)); printf("\nGasto en ocio: %.2f\n", totalGastosPorCategoria(gOcio, SEMANA)); printf("\nGASTO TOTAL SEMANAL: %.2f\n", gastosTotalesSemanales(gTransporte, gAlimentacion, gOcio)); printf("\nPORCENTAJE GASTADO: %.2f\n", presupuestoGastado(gastosTotalesSemanales(gTransporte, gAlimentacion, gOcio), pSemanal));}
void pedirPresupuesto(float *pSemanal) { printf("Presupuesto semanal:\t"); scanf("%f", &pSemanal);}
void pedirGastos(float gasto[], int n) { for (int i = 0; i < n; i++) { printf("Dia %d:\n", i + 1); scanf("%f", &gasto[i]); }}
float totalGastosPorCategoria(float gasto[], int n) { float total = 0; for (int i = 0; i < n; i++) { total += gasto[i]; } return total;}
float gastosTotalesSemanales(float transporte[], float alimentacion[], float ocio[]) { return totalGastosPorCategoria(transporte, SEMANA) + totalGastosPorCategoria(alimentacion, SEMANA) + totalGastosPorCategoria(ocio, SEMANA);}
float gastoMedioDiario(float gasto[], int n) { return (totalGastosPorCategoria(gasto, n) / n);}
float presupuestoGastado(float gastosTotales, float presupuesto) { return (gastosTotales / presupuesto) * 100;}
Ejercicio 8
Plantee e implemente un programa en lenguaje C que, mediante búsqueda secuencial, permita encontrar el menor y el mayor índice de donde se encuentra un valor dado X en un array de números enteros. El programa debe permitir al usuario introducir apropiadamente el array de números enteros y solicitarle el valor que desea encontrar.
Introduzca los elementos del array separados por espacios, "enter" para terminar:1 2 3 5 3 2 3 4 5 6 3 1 2 3
Introduzca el número que desea buscar: 3El número 3 aparece por primera vez en la posición 3 y por última vez en la posición 14.Introduzca el número que desea buscar: 4El número 4 aparece por primera y única vez en la posición 8.Introduzca el número que desea buscar: 9El número 9 no aparece en el array.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h>#define N 10
int main(){ // Define variables and ask for parameters int nums[N], guess, lGuess, uGuess; printf("\nInput an array of 10 elements by pressing Enter after each element: "); for(int i=0; i<10; i++){ scanf("%d", &nums[i]); } // Input guess printf("\nWhat number do you want to find?: "); scanf("%d", &guess); // Lower bound for(int i=0; i<N; i++){ if(nums[i] == guess){ lGuess = i; break; } } // Upper bound for(int i=N; i>=0; i--){ if(nums[i] == guess){ uGuess = i; break; } } // Print solutions printf("\nLower bound solution: %d", lGuess); printf("\nUpper bound solution: %d", uGuess); printf("\n");}
Ejercicio 9
Plantee e implemente un programa en lenguaje C que construya un array a partir de números enteros proporcionados por el usuario (máximo 20 elementos) y que a continuación sustituya los números pares por su cuadrado y los números impares por la parte entera de la raíz cuadrada de su valor absoluto. Muestre por pantalla tanto el array original como el resultante de las operaciones indicadas.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Miguel Fraga Pico//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>#include <math.h>
void escanearDatos(int *numeros,int tamano){ int i; for(i = 0 ;i < tamano; i++) { printf("Introduzca un valor:\n"); scanf("%d",&numeros[i]); }}void imprimirDatos (int *numeros, int tamano){ int i; for(i = 0 ;i < tamano; i++) { printf("%d, ",numeros[i]); }}void modificarArray(int *numeros,int tamano){ int i; for(i = 0; i < tamano; i++) { if(numeros[i]%2==0) { numeros[i]=pow(numeros[i],2); } else if(numeros[i] % 2 != 0) { numeros[i] = trunc(sqrt(abs(numeros[i]))); } }}int main(){ int tamano; printf("Introduzca cuantos numeros va a proprocionar:\n"); scanf("%d",&tamano); if(tamano<=0 || tamano>20) { printf("Introduzca un tamano valido"); return 2; } int numeros[tamano]; escanearDatos(numeros,tamano); imprimirDatos(numeros,tamano); printf("\n"); modificarArray(numeros,tamano); printf("\n"); imprimirDatos(numeros,tamano); return 0;}
Ejercicio 10
Plantee e implemente una función en lenguaje C que reciba dos arrays de enteros desordenados de 50 elementos cada uno y devuelva una array ordenado con los elementos de los dos anteriores.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Pablo Portas López <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
// Librerías#include <stdio.h>#include <time.h>#include <stdlib.h>
// Definicionestypedef int array50[50], array100[100];
// Definición funcionesvoid crearArrayAleatorio(array50 array);
void fusiondedosArrays(array50 array1, array50 array2, array100 arraydesalida);
void bubblesort(array100 array);
void imprimirArray(array100 array);
// Mainint main() { array50 array1, array2; array100 arrayfinal;
srand(time(NULL)); // Así solo se declara una vez crearArrayAleatorio(array1); crearArrayAleatorio(array2);
fusiondedosArrays(array1, array2, arrayfinal);
bubblesort(arrayfinal);
imprimirArray(arrayfinal);
return 0;}
// Declaración Funcionesvoid crearArrayAleatorio(array50 array) { for (int i = 0; i < 50; i++) { array[i] = rand() % 1000; // Para evitar números gigantes, prefiero un array de números menores a 1000; }}
void fusiondedosArrays(array50 array1, array50 array2, array100 arraydesalida) { for (int i = 0; i < 50; i++) { // El primer array en los elementos del 0 - 49 arraydesalida[i] = array1[i]; } for (int i = 0; i < 50; i++) { // El segundo array en los elementos del 50 - 99 arraydesalida[i + 50] = array2[i]; }}
void bubblesort(array100 array) { // Algoritmo BubbleSort https://es.wikipedia.org/wiki/Ordenamiento_de_burbuja int aux; for (int j = 1; j < 99; j++) { for (int i = 0; i < 100 - j; i++) { if (array[i] > array[i + 1]) { aux = array[i]; // Movemos al aux array[i] = array[i + 1]; // Movemos el segundo al primer hueco array[i + 1] = aux; // Copiamos el valor del primero al segundo hueco } } }}
void imprimirArray(array100 array) { printf("El array ordenado:\n %d", array[0]); for (int i = 1; i < 100; i++) { printf(", "); // Colocando la coma aquí conseguimos que el último elemento no tenga y así sea un punto. if (i % 20 == 0) printf("\n"); // Para que sea más legible en terminal. printf("%3d", array[i]); // El formato hace que queden en cuadrícula } printf("."); // El punto en cuestión}
Ejercicio 11
Plantee e implemente una función recursiva en lenguaje C que devuelva la suma de los elementos de un array de enteros.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h>
// Sum all the elements of the array using recursionint arraySum(int n, int sumNums[n], int loops, int accum){ if (loops == 0){return accum;} else{ accum+=sumNums[n-loops]; loops--; arraySum(n, sumNums, loops, accum); }}
int main(){ // Define variables and ask for parameters int n = 10; int toSum[n], accum = 0, loops = n; int result; printf("Input the 10 numbers for the array separated by Enter:\n"); for(int i=0; i<10; i++){ scanf("%d", &toSum[i]); } // Recursion fun starts here result = arraySum(n, toSum, loops, accum); // Print result printf("\nThe result of the sum is %d\n", result); return 0;}
Ejercicio 15
Plantee e implemente un programa en lenguaje C que permita introducir apropiadamente una matriz NxN de números reales y que muestre por pantalla en formato matricial tanto la matriz original introducida como su matriz traspuesta. Realice lo mismo considerando como tipo base de la matriz números enteros.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Miguel Fraga Pico//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>// i = fila// j = columnavoid crearMatriz(int tamanho, int matriz[tamanho][tamanho]){ int i; int j; for(j = 0; j < tamanho; j++) { for(i = 0; i < tamanho; i++) { printf("Posicion %d, %d \n", j + 1, i + 1); scanf("%d", &matriz[i][j]); } }}
void imprimirMatriz(int tamanho, int matriz[tamanho][tamanho]){ int i; int j; for(j = 0; j < tamanho; j++) { for(i = 0; i < tamanho; i++) { printf("%d ", matriz[i][j]); } printf("\n"); }}
void imprimirTraspuesta(int tamanho, int matriz[tamanho][tamanho]){ int i; int j; for(j = 0; j < tamanho; j++) { for(i = 0; i < tamanho; i++) { printf("%d ", matriz[j][i]); } printf("\n"); }}
int main(){ int tamanho; int traspuesta;
printf("De que tamanho quieres la matriz"); scanf("%d", &tamanho);
printf("Quieres la traspuesta? 1 = si, 0 = no"); scanf("%d", &traspuesta);
int matriz[tamanho][tamanho];
crearMatriz(tamanho, matriz);
if(traspuesta) { imprimirTraspuesta(tamanho, matriz); } else { imprimirMatriz(tamanho, matriz); }}
Ejercicio 20
Plantee e implemente un programa en lenguaje C que permita almacenar en memoria el nombre y las notas de una asignatura de una clase de 15 alumnos. Muestre por pantalla el nombre y nota de los alumnos que han obtenido la peor y la mejor calificación. Además muestre a continuación el listado con el nombre y nota de todos los alumnos.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define MAX 3
struct alumno { char nombre[20]; float nota;};
void introducirAlumno(struct alumno alumnos[], int n);
void mostrarAlumnado(struct alumno alumnos[], int n);
void mejorYPeorNota(struct alumno alumnos[], int n, struct alumno *mejor, struct alumno *peor);
int main() { struct alumno alumnos[MAX]; struct alumno mejor, peor;
introducirAlumno(alumnos, MAX); mostrarAlumnado(alumnos, MAX); mejorYPeorNota(alumnos, MAX, &mejor, &peor);
printf("\nMejor nota:\t%s - %.2f\n", mejor.nombre, mejor.nota); printf("Peor nota:\t%s - %.2f\n", peor.nombre, peor.nota);
}
void introducirAlumno(struct alumno alumnos[], int n) { for (int i = 0; i < n; i++) { printf("--- Alumno %d ---: \n", i + 1); printf("Nombre: \n"); scanf("%s", alumnos[i].nombre); printf("Nota de %s: \n", alumnos[i].nombre); scanf("%f", &alumnos[i].nota); }}
void mostrarAlumnado(struct alumno alumnos[], int n) { printf("\nLISTADO DE ALUMNOS\n"); for (int i = 0; i < n; i++) { printf("%s: %.2f\n", alumnos[i].nombre, alumnos[i].nota); } printf("\n");}
void mejorYPeorNota(struct alumno alumnos[], int n, struct alumno *mejor, struct alumno *peor) { // Inicializamos con el primer estudiante *mejor = alumnos[0]; *peor = alumnos[0];
for (int i = 0; i < n; i++) { if (alumnos[i].nota > mejor->nota) { *mejor = alumnos[i]; }
if (alumnos[i].nota < peor->nota) { *peor = alumnos[i]; } }}
Ejercicio 21
Diseñe la estructura de datos que permita almacenar en memoria la lista de tareas a realizar durante los días del año. Se debe de poder controlar la fecha, la descripción de tareas a realizar cada día con su hora y minutos. Tenga en cuenta que cada día no podrá tener más de 20 tareas.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <[email protected]>//// SPDX-License-Identifier: GPL-3.0-only
#define MAX_TAREAS 20
// Define una tareatypedef struct { int hora; int minutos; char descripcion[150];} tTarea;
// Define las tareas de un díatypedef struct { int dia; int mes; int anio; tTarea tareas[MAX_TAREAS];} tDiaTareas;
// Define las tareas de un añotypedef struct { tDiaTareas dias[365];} tListaTareas;
Ejercicio 24
Diseñe la estructura para almacenar en memoria la información de los trabajadores de un taller de 20 empleados. Si el empleado es oficinista tendrá un número de teléfono; si es conductor tendrá asignado el número de matrícula de un vehículo; y si es técnico tendrá asignado el código de barras de un ordenador. Se debe conocer el nombre, la fecha de nacimiento, tipo de puesto de trabajo y el nivel de estudios de todos los trabajadores.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Miguel Fraga Pico//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
struct empleados{ char puesto[50]; //oficinista conductor técnico char nivelEstudios[50]; char fechaNacimiento[50]; char nombre[50];};
void introducirEmpleado(struct empleados *e){ printf("Cual es el nombre del empleado?"); gets(&e->nombre); printf("Que puesto le corresponde al empleado?"); gets(&e->puesto); printf("Cual es la fecha de nacimiento del empleado? dd/mm/aaaa"); gets(&e->fechaNacimiento); printf("Cual es el nivel de estudios del empleado? "); gets(&e->nivelEstudios);}
void imprimirempleado(struct empleados e){ printf("El nombre del empleado es: %s\n", e.nombre); printf("La fecha de nacimiento del empleado es: %s\n", e.fechaNacimiento); printf("El nivel de estudios del empleado es: %s\n", e.nivelEstudios); printf("El puesto del empleado es: %s\n", e.puesto);}
int main(){ struct empleados empleados[20];
for(int i = 0; i < 20; i++) { printf("Introduciendo alumno %d:\n",i); introducirEmpleado(&empleados[i]); } for(int i = 0; i < 20; i++) { printf("Imprimiendo alumno %d:\n",i); imprimirempleado(empleados[i]); }}
Ejercicio 25
Plantee e implemente un programa en lenguaje C que lea una frase de teclado (secuencia de caracteres hasta fin de línea), y determine la frecuencia de aparición de cada vocal respecto al total de caracteres de la frase.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Daniel Deza Prieto//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>void reader(char frase[200]) { printf("Please input the phrase up to a size of 200 characters\n"); scanf(" %[^\n]s", frase);}void howmany(char frase[200], int acount, int ecount, int icount, int ocount, int ucount, int rest) { for (int i = 0; i < 200; i++) { (frase[i] == 'a') ? (acount++) : (rest++); (frase[i] == 'e') ? (ecount++) : (rest++); (frase[i] == 'i') ? (icount++) : (rest++); // Codigo terrible. I lose half the brain. Funciona eso si (frase[i] == 'o') ? (ocount++) : (rest++); (frase[i] == 'u') ? (ucount++) : (rest++); } printf("Hay a:%i e:%i i:%i o:%i u:%i", acount, ecount, icount, ocount, ucount);}int main() { int acount = 0; int ecount = 0; int icount = 0; int ocount = 0; int ucount = 0; int rest = 0; char frase[200]; reader(frase); howmany(frase, acount, ecount, icount, ocount, ucount, rest); return 0;}
Ejercicio 27
Plantee e implemente un programa en lenguaje C que lea una frase (como máximo de 100 caracteres) y que muestre a continuación cada palabra de la misma seguida del número de letras que la componen. Para simplificar suponga que las palabras pueden separarse únicamente por espacios, comas o puntos.
Introduzca una frase de como máximo 100 caracteres:Buenos días, vamos a comenzar. Encended los equipos.
Buenos 6días 4vamos 5a 1comenzar 8Encended 8los 3equipos 7
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h>#define N 100
// Count the amount of characters in the stringvoid countString(char toCount[N]){ int count = 0; for(int i=0; toCount[i]!='\0'; i++){ count++; } printf("Word %s has %d characters\n", toCount, count);}
// Separate the string and fix multiple separators in the string by ignoring themvoid separateString(char toSplit[N]){ char splitted[N][N]; int count=0, row=0, column=0; while(toSplit[count] != '\n'){ if(toSplit[count] == ' ' || toSplit[count] == ',' || toSplit[count] == '.'){ splitted[row][column] = '\0'; column = 0; if (toSplit[count-1] != ' ' && toSplit[count-1] != ',' && toSplit[count-1] != '.'){row++;} } else { splitted[row][column] = toSplit[count]; column++; } count++; } for(int i=0; splitted[i][0] != '\0'; i++){ countString(splitted[i]); }}
int main(){ // Define variables and ask for parameters char sentence[N]; printf("Type a sentence of max 100 characters:\n"); // fgets instead of gets for buffer overflow protection fgets(sentence, N, stdin); // Start the fun separateString(sentence); return 0;}
Ejercicio 28
Plantee e implemente un programa en lenguaje C que lea una frase (secuencia de caracteres hasta fin de línea), sustituya todas las secuencias de dos o más espacios por un único espacio y que muestre por pantalla la frase obtenida.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h>#define N 256
int main(){ // Define variables and ask for parameters int i=0, j=0; char sentence[N], fixedSentence[N]; printf("Type a sentence\n"); // fgets instead of gets for buffer protection fgets(sentence, N, stdin); // Fix the sentence's multiple spaces while(sentence[i]!='\0'){ if(sentence[i] == ' ' && sentence[i+1] == ' '){ i++; continue; } else { fixedSentence[j]=sentence[i]; i++; j++; } } // Print the result after apprending the end of string to the fixed variable fixedSentence[j+1] = '\0'; printf("\nThe sentence with fixed spaces is:\n%s", fixedSentence); return 0;}
Ejercicio 29
Diseñe una función que devuelva al revés la cadena recibida como parámetro.
Mostrar Solución
// SPDX-FileCopyrightText: 2023 Miguel Fraga Pico//// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>#include <string.h>
void invertirCadena(char cadena[]){ int longitud = strlen(cadena); int i, j;
for (i = 0, j = longitud - 1; i < j; i++, j--) { char temp = cadena[i]; cadena[i] = cadena[j]; cadena[j] = temp; }}
int main(){ printf("Introduce una oracion o frase\n"); char cadenaOriginal[50]; gets(&cadenaOriginal);
invertirCadena(cadenaOriginal);
printf("Cadena invertida: %s\n", cadenaOriginal);
return 0;}
Ejercicio 36
Implemente un programa que solicite cinco números enteros (ni > 0) al usuario y muestre por pantalla cada número y su descomposición factorial. Utilice una estructura de datos adecuada para almacenar a la vez los números y su descomposición.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h>#include <stdbool.h>#define N 100
void factorialDecomp(int toDecomp){ int factors[N], primes=2, loops=0, og=toDecomp; // Check if its 1 or 0 and just print out that the decomp is 1 if(toDecomp == 0 | toDecomp == 1){ printf("\nNumber %d factorial decomposition is: 1", og); return; } // Repeat the factorization with each reduced number until its 0 for(int i=0;i<N;i++){factors[i]=0;} while(toDecomp != 1){ if(toDecomp%primes == 0){ toDecomp/=primes; factors[loops]=primes; loops++; primes=2; } else {primes++;} } // Print the result printf("\nNumber %d factorial decomposition is: ", og); for(int i=0;factors[i]!=0;i++){ if(factors[i+1]==0){ printf("%d", factors[i]); } else {printf("%d*", factors[i]);} }}
int main(){ // Define variables and ask for parameters int decompose[5]; printf("Type 5 integers separated by spaces:\n"); // Its just 5 parameters no for loop needed here scanf("%d %d %d %d %d", &decompose[0], &decompose[1], &decompose[2], &decompose[3], &decompose[4]); // Repeat the decomp for all numbers for(int i=0;i<5;i++){ factorialDecomp(decompose[i]); } printf("\n"); return 0;}
Ejercicio 37
Implemente un programa que lea una fecha y la almacene en una cadena que quepan sus 10 caracteres (dd/mm/aaaa) añadiendo ceros a la izquierda del día, mes y año si son necesarios) y calcule y almacene en memoria los siguientes 100 años bisiestos. El programa debe dar la opción al usuario de cambiar la fecha introducida y ver por pantalla los n años bisiestos que desee a partir de la fecha dada.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h>#define N 11#define M 100
void checkLeaps(int n, int year){ int closeLeap, leaps[M], counter=1; //Check closest for(int i=0;i<4;i++){ if((year+i)%4 == 0){ closeLeap = year+i; break; } } // Get all the following leap years until the max amount is satisfied leaps[0]=closeLeap; while(counter != 100){ leaps[counter]=closeLeap+(4*counter); counter++; } // Print results printf("\nFollowing 100 leap years:\n"); for(int i=0; i<M; i++){ printf("%d ", leaps[i]); } printf("\n\n");}
int main(){ // Define variables char date[N]; int day, month, year; // Endless loop so the user can change parameters (1==1) while(1){ // Ask for parameters printf("Input a date in the dd/mm/yyyy format: "); scanf("%d/%d/%d", &day, &month, &year); // Fix the string so it can be passed to the function more easily snprintf(date, N, "%02d/%02d/%04d", day, month, year); checkLeaps(100, year); } return 0;}
Ejercicio 40
Plantee e implemente un programa en lenguaje C para simular el juego de la vida de John Conway.
Mostrar Solución
// SPDX-FileCopyrightText: 2024 Sprinter05//// SPDX-License-Identifier: GPL-3.0-only
// Libraries#include <stdio.h> // Main library#include <stdlib.h> // For managing the program#include <stdbool.h> // Bool function#include <unistd.h> // Use UNIX commands#include <time.h> // For random numbers#define N 16 // Change this number to change the matrix size#define SPEED 2 // Higher means faster: MUST BE GREATER OR EQUAL THAN 1#define clear() printf("\033[H\033[J") // Clean screen
// NOTE: RUN FROM VSCODE TERMINAL OR THE MODERN WINDOWS TERMINAL APP NOT CMD OTHERWISE UTF-8 EMOJIS WILL NOT DISPLAY// ALSO MAKE SURE UTF-8 SUPPORT IS ENABLED IN YOUR TERMINAL OF CHOICE, APPLIES TO ALL OPERATING SYSTEMS
int gameOfLife[N][N];int updatedGame[N][N];int ticks=0; // Generations
// THIS IS THE MATRIX THAT WILL RUN IF THE OPTION c (choose) IS CHOSEN AT RUNTIME// THIS EXAMPLE MATRIX IS OF SIZE 16X16 SO IF YOU CHANGE N MODIFY THE SIZE HERE TOO// 0 = DISABLED, 1 = ENABLEDint chooseGameOfLife[N][N] = { {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0}, {0,0,1,1,0,0,0,1,0,0,1,0,0,0,0,0}, {0,0,1,1,0,0,0,1,0,0,1,0,0,0,0,0}, {0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0}, {0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0}, {0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0}, {0,0,1,0,0,1,0,0,0,0,1,0,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
// Make sure the cell is not outsided of the matrixbool outOfBound(int row, int column){ bool oob; if(row >= N || row < 0 || column >= N || column < 0){oob = true;} else {oob = false;} return oob;}
// Check rules 1, 2 and 3 for death statusvoid checkDeath(int row, int column){ int liveNeighbours=0; // Check neighbours if(outOfBound(row+1,column) == false){if(gameOfLife[row+1][column] == 1){liveNeighbours++;}} if(outOfBound(row+1,column+1) == false){if(gameOfLife[row+1][column+1] == 1){liveNeighbours++;}} if(outOfBound(row+1,column-1) == false){if(gameOfLife[row+1][column-1] == 1){liveNeighbours++;}} if(outOfBound(row-1,column) == false){if(gameOfLife[row-1][column] == 1){liveNeighbours++;}} if(outOfBound(row-1,column+1) == false){if(gameOfLife[row-1][column+1] == 1){liveNeighbours++;}} if(outOfBound(row-1,column-1) == false){if(gameOfLife[row-1][column-1] == 1){liveNeighbours++;}} if(outOfBound(row,column+1) == false){if(gameOfLife[row][column+1] == 1){liveNeighbours++;}} if(outOfBound(row,column-1) == false){if(gameOfLife[row][column-1] == 1){liveNeighbours++;}} // Any live cell with fewer than two live neighbours dies, as if by underpopulation. if(liveNeighbours<2){updatedGame[row][column]=0;} // Any live cell with two or three live neighbours lives on to the next generation. else if(liveNeighbours>=2 && liveNeighbours<=3){updatedGame[row][column]=1;} // Any live cell with more than three live neighbours dies, as if by overpopulation. else if(liveNeighbours>3){updatedGame[row][column]=0;}}
// Check rule 4 for revive statusvoid checkRevive(int row, int column){ int liveNeighbours=0; // Check neighbours if(outOfBound(row+1,column) == false){if(gameOfLife[row+1][column] == 1){liveNeighbours++;}} if(outOfBound(row+1,column+1) == false){if(gameOfLife[row+1][column+1] == 1){liveNeighbours++;}} if(outOfBound(row+1,column-1) == false){if(gameOfLife[row+1][column-1] == 1){liveNeighbours++;}} if(outOfBound(row-1,column) == false){if(gameOfLife[row-1][column] == 1){liveNeighbours++;}} if(outOfBound(row-1,column+1) == false){if(gameOfLife[row-1][column+1] == 1){liveNeighbours++;}} if(outOfBound(row-1,column-1) == false){if(gameOfLife[row-1][column-1] == 1){liveNeighbours++;}} if(outOfBound(row,column+1) == false){if(gameOfLife[row][column+1] == 1){liveNeighbours++;}} if(outOfBound(row,column-1) == false){if(gameOfLife[row][column-1] == 1){liveNeighbours++;}} // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. if(liveNeighbours==3){updatedGame[row][column]=1;} // Remain dead else {updatedGame[row][column]=0;}}
// Run a generationvoid tick(){ // Run generation for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ if(gameOfLife[i][j] == 1){checkDeath(i, j);continue;} else if(gameOfLife[i][j] == 0){checkRevive(i, j);continue;} else {exit(1);} // Impossible case, exit with error } }}
// Show the game matrixvoid displayMatrix(){ printf("\n"); for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ if(updatedGame[i][j] == 0){printf("⬛");} if(updatedGame[i][j] == 1){printf("⬜");} } printf("\n"); } printf("Generation %d\n", ticks);}
// Print the initial statusvoid printInitial(){ printf("\n"); for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ if(gameOfLife[i][j] == 0){printf("⬛");} if(gameOfLife[i][j] == 1){printf("⬜");} } printf("\n"); } printf("Initial status\n");}
// Swap og and updated matrixvoid redoMatrix(){ // Put updated matrix into the original one for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ gameOfLife[i][j]=updatedGame[i][j]; } } // Set the updated matrix to 0 for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ updatedGame[i][j]=0; } }}
// Initial random conditionvoid randCondition(){ srand(time(NULL)); // Random init for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ gameOfLife[i][j]=rand()%2; } }}
int main(){ // Ask what to do char answ; while(answ != 'r' && answ != 'c'){ printf("Do you want a randomly generated generation or choose one? (r/c): "); scanf("%c", &answ); if(answ == 'r'){randCondition();} else if(answ == 'c'){ for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ gameOfLife[i][j] = chooseGameOfLife[i][j]; } } } } // Start dead cells on updated for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ updatedGame[i][j]=0; } } printInitial(); // Print initial state usleep(1000000); while(1){ clear(); // Clear screen tick(); // Run generation displayMatrix(); // Show the matrix ticks++; // Increase counter redoMatrix(); usleep(200000/SPEED); // Wait delay } return 0;}