Saltearse al contenido

Boletín 4 - Estructuras de Datos

Arrays, registros y cadenas de caracteres.

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
Ejercicio_01.c
// 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;
}

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
Ejercicio_02.c
// SPDX-FileCopyrightText: 2023 Pablo Portas López <pablo.portas@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
// Librerías
#include <stdio.h>
// Constantes
#define MAX 40
#define NANIMAL 7
// Definiciones
typedef char nombreanimal[40];
typedef struct{
nombreanimal nombre;
}tRegAnimales[NANIMAL];
// Definición funciones
void introducirNombres(tRegAnimales listaAnimales);
void imprimirNombres(tRegAnimales listaNombres);
// Main
int main() {
tRegAnimales listaAnimales;
introducirNombres(listaAnimales);
imprimirNombres(listaAnimales);
return 0;
}
// Declaración Funciones
void 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(".");
}

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
Ejercicio_03.c
// SPDX-FileCopyrightText: 2023 Pablo Portas López <pablo.portas@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
// Librerías
#include <stdio.h>
// Constantes
#define MAX 30
// Definiciones
typedef float listanumeros[MAX];
// Definición funciones
void introducirPorTeclado(listanumeros numeros);
void imprimirSumatorio(const listanumeros numeros);
// Main
int main() {
listanumeros lnumeros;
introducirPorTeclado(lnumeros);
imprimirSumatorio(lnumeros);
return 0;
}
// Declaración Funciones
void 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);
}

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
Ejercicio_04.c
// SPDX-FileCopyrightText: 2023 Pablo Portas López <pablo.portas@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
// Librerías
#include <stdio.h>
// Definiciones
typedef struct {
int horas;
char nombre[10];
} tRegdiasemana;
typedef tRegdiasemana vHorasSemana[7];
// Definición funciones
void introducirHoras(vHorasSemana horas);
void imprimirMediaYMostrarDias(vHorasSemana horas);
void ordenarDeMayorAMenor(vHorasSemana horas);
// Main
int 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 Funciones
void 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
}
}
}
}

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
Ejercicio_05.c
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <maite.gonzalez@udc.es>
//
// 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;
}

Plantee e implemente un programa en lenguaje C que, partiendo de la estructura creada en el ejercicio anterior, cree un sistema para almacenar las temperaturas (en ºC) registradas en una ciudad durante una semana (hora a hora cada día) Introduzca las temperaturas solicitando los datos apropiadamente al usuario. Calcule y muestre por pantalla las temperaturas medias diarias, las temperaturas medias de cada hora y la temperatura media semanal.

Mostrar Solución
Ejercicio_06.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <<i.villar@udc.es>>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
int main(){
float sumdiaria[7],mediadiaria[7];
float sumahoraria[24],mediahoraria[24];
float sumasemanal, mediasemanal;
float temperaturas[7][24];
char dias[7][50] = {"Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"};
for(int i=0;i<7;i++){
sumdiaria[i]=0;
printf("\n\n----%s----\n",dias[i]);
for(int j=0;j<24;j++){
printf("Temperatura a las %d horas:",j);
scanf("%f",&temperaturas[i][j]);
sumdiaria[i] += temperaturas[i][j];
sumasemanal += temperaturas[i][j];
}
mediadiaria[i] = sumdiaria[i]/24;
}
for(int i=0;i<7;i++){
printf("\nTemperatura media del %s: %.2f",dias[i],mediadiaria[i]);
}
for(int i=0;i<24;i++){
for(int j=0;j<7;j++) sumahoraria[i] += temperaturas[j][i];
mediahoraria[i] = sumahoraria[i]/24;
printf("\nTemperatura media de las %d horas: %.2f",i,mediahoraria[i]);
}
mediasemanal = sumasemanal/7/24;
printf("\nLa media de temperatura semanal es: %.2f",mediasemanal);
}

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
Ejercicio_07.c
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <maite.gonzalez@udc.es>
//
// 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;
}

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.

Ejemplo de Ejecución
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: 3
El 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: 4
El número 4 aparece por primera y única vez en la posición 8.
Introduzca el número que desea buscar: 9
El número 9 no aparece en el array.
Mostrar Solución
Ejercicio_08.c
// 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");
}

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
Ejercicio_09.c
// 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;
}

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
Ejercicio_10.c
// SPDX-FileCopyrightText: 2023 Pablo Portas López <pablo.portas@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
// Librerías
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// Definiciones
typedef int array50[50], array100[100];
// Definición funciones
void crearArrayAleatorio(array50 array);
void fusiondedosArrays(array50 array1, array50 array2, array100 arraydesalida);
void bubblesort(array100 array);
void imprimirArray(array100 array);
// Main
int 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 Funciones
void 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
}

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
Ejercicio_11.c
// SPDX-FileCopyrightText: 2024 Sprinter05
//
// SPDX-License-Identifier: GPL-3.0-only
// Libraries
#include <stdio.h>
// Sum all the elements of the array using recursion
int 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;
}

Plantee e implemente una función en lenguaje C que indique si un array de enteros es capicúa.

Mostrar Solución
Ejercicio_12.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <<i.villar@udc.es>>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <stdbool.h>
bool esCapicua(int array[], int tamanio) {
for (int i = 0; i < tamanio / 2; i++) {
if (array[i] != array[tamanio - i - 1]) return false;
}
return true;
}
int main() {
int array[] = {1, 2, 3, 3, 1};
int t = sizeof(array) / sizeof(array[0]);
printf("El array %s capicua\n", esCapicua(array, t)? "es" : "no es");
}

Plantee e implemente un programa en lenguaje C que permita introducir apropiadamente una matriz NxN de números enteros (0< N < 20), la visualice apropiadamente por pantalla (formato matricial) y muestre el elemento mayor y el elemento menor de dicha matriz y sus posiciones.

Mostrar Solución
Ejercicio_13.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <<i.villar@udc.es>>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define MAX 20
int main() {
int N;
do {
printf("Introduzca el tamano de la matriz:");
scanf("%d", &N);
} while (N <= 0 || N > 20);
int matriz[MAX][MAX];
printf("Introduzca los elementos de la matriz (%dx%d):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Elemento [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matriz[i][j]);
}
}
printf("\nMatriz ingresada:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%3d ", matriz[i][j]);
}
printf("\n");
}
int mayor = matriz[0][0], menor = matriz[0][0];
int posMayorFila = 0, posMayorColumna = 0;
int posMenorFila = 0, posMenorColumna = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (matriz[i][j] > mayor) {
mayor = matriz[i][j];
posMayorFila = i;
posMayorColumna = j;
}
if (matriz[i][j] < menor) {
menor = matriz[i][j];
posMenorFila = i;
posMenorColumna = j;
}
}
}
printf("\nEl mayor elemento es %d en la posicion [%d][%d].\n", mayor, posMayorFila + 1, posMayorColumna + 1);
printf("El menor elemento es %d en la posicion [%d][%d].\n", menor, posMenorFila + 1, posMenorColumna + 1);
}

Plantee e implemente un programa en lenguaje C que permita introducir apropiadamente una matriz NxN de enteros y que, a petición del usuario, intercambie las filas o columnas i y j de dicha matriz. Muestre por pantalla en formato matricial tanto la matriz original introducida como la matriz resultante del intercambio de filas o columnas solicitado por el usuario.

Mostrar Solución
Ejercicio_14.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define MAX 20
void mostrarMatriz(int matriz[MAX][MAX], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%4d", matriz[i][j]);
}
printf("\n");
}
}
void Filas(int matriz[MAX][MAX], int N, int fila1, int fila2) {
for (int j = 0; j < N; j++) {
int temp = matriz[fila1][j];
matriz[fila1][j] = matriz[fila2][j];
matriz[fila2][j] = temp;
}
}
void Columnas(int matriz[MAX][MAX], int N, int col1, int col2) {
for (int i = 0; i < N; i++) {
int temp = matriz[i][col1];
matriz[i][col1] = matriz[i][col2];
matriz[i][col2] = temp;
}
}
int main() {
int N;
do {
printf("Introduzca el tamano de la matriz:");
scanf("%d", &N);
} while (N <= 0 || N > 20);
int matriz[MAX][MAX];
printf("Introduzca los elementos de la matriz (%dx%d):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Elemento [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matriz[i][j]);
}
}
printf("\nMatriz original:\n");
mostrarMatriz(matriz, N);
int op,i,j;
printf("\nSeleccione una opción:\n1. Intercambiar filas\n2. Intercambiar columnas\n");
printf("Opcion: ");
scanf("%d", &op);
if (op == 1) {
do{
printf("Introduzca las filas a intercambiar (1 <= fila <= %d): ", N);
scanf("%d %d", &i, &j);
} while(i < 1 || i > N || j < 1 || j > N || i == j);
Filas(matriz, N, i - 1, j - 1);
printf("\nMatriz despues de intercambiar las filas %d y %d:\n", i, j);
mostrarMatriz(matriz, N);
}
else if (op == 2) {
do{
printf("Introduzca las columnas a intercambiar (1 <= columna <= %d): ", N);
scanf("%d %d", &i, &j);
} while(i < 1 || i > N || j < 1 || j > N || i == j);
Columnas(matriz, N, i - 1, j - 1);
printf("\nMatriz despues de intercambiar las columnas %d y %d:\n", i, j);
mostrarMatriz(matriz, N);
}
else printf("Opcion no valida.\n");
}

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
Ejercicio_15.c
// SPDX-FileCopyrightText: 2023 Miguel Fraga Pico
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
// i = fila
// j = columna
void 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);
}
}

Plantee e implemente un programa en lenguaje C que permita introducir un cuadrado (NxN) por teclado y determine si es mágico. Un cuadrado mágico es una matriz NxN de números enteros del 1 al N^2 en la que la suma de sus filas, sus columnas y sus diagonales principales coincide.

Mostrar Solución
Ejercicio_16.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <stdbool.h>
#define MAX 20
bool Magico(int matriz[MAX][MAX], int N) {
int sumaObjetivo = 0;
int suma = 0;
for (int i = 0; i < N; i++) sumaObjetivo += matriz[0][i];
// Filas
for (int i = 0; i < N; i++) {
suma = 0;
for (int j = 0; j < N; j++) suma += matriz[i][j];
if (suma != sumaObjetivo) return false;
}
// Columna
for (int j = 0; j < N; j++) {
suma = 0;
for (int i = 0; i < N; i++) suma += matriz[i][j];
if (suma != sumaObjetivo) return false;
}
// Diagonal principal
suma = 0;
for (int i = 0; i < N; i++) suma += matriz[i][i];
if (suma != sumaObjetivo) return false;
// Diagonal secundaria
suma = 0;
for (int i = 0; i < N; i++) suma += matriz[i][N - i - 1];
if (suma != sumaObjetivo) return false;
return true;
}
int main() {
int N;
do {
printf("Introduzca el tamanho de la matriz (1 <= N < 20): ");
scanf("%d", &N);
} while (N <= 0 || N > 20);
int matriz[MAX][MAX];
printf("Introduzca los elementos de la matriz (%dx%d):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Elemento [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matriz[i][j]);
}
}
printf("\nLa matriz %s un cuadrado magico\n", Magico(matriz, N)? "es":"no es");
}

Plantee e implemente un programa en lenguaje C que mediante un menú apropiado permita al usuario introducir dos matrices NxN de números enteros () y seleccionar la operación (suma, resta o producto) que desea realizar con ellas. Muestre los resultados de la operación seleccionada por pantalla en formato matricial.

Mostrar Solución
Ejercicio_17.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define MAX 10
void mostrarMatriz(int matriz[MAX][MAX], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) printf("%3d", matriz[i][j]);
printf("\n");
}
}
void sumar(int m1[MAX][MAX], int m2[MAX][MAX], int res[MAX][MAX], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) res[i][j] = m1[i][j] + m2[i][j];
}
}
// Función para restar dos matrices
void restar(int m1[MAX][MAX], int m2[MAX][MAX], int res[MAX][MAX], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) res[i][j] = m1[i][j] - m2[i][j];
}
}
void mult(int m1[MAX][MAX], int m2[MAX][MAX], int res[MAX][MAX], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
res[i][j] = 0;
for (int k = 0; k < N; k++) res[i][j] += m1[i][k] * m2[k][j];
}
}
}
int main() {
int N;
do {
printf("Introduzca el tamano de las matrices (1 <= N < 10): ");
scanf("%d", &N);
} while (N <= 0 || N > 10);
int m1[MAX][MAX], m2[MAX][MAX], res[MAX][MAX];
printf("Introduzca los elementos de la primera matriz (%dx%d):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Elemento [%d][%d]: ", i + 1, j + 1);
scanf("%d", &m1[i][j]);
}
}
printf("Introduzca los elementos de la segunda matriz (%dx%d):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Elemento [%d][%d]: ", i + 1, j + 1);
scanf("%d", &m2[i][j]);
}
}
int opcion;
printf("1. Suma de matrices\n");
printf("2. Resta de matrices\n");
printf("3. Producto de matrices\n");
printf("Opcion: ");
scanf("%d", &opcion);
// Ejecutar la operación seleccionada
switch (opcion) {
case 1:
sumar(m1, m2, res, N);
printf("\nResultado de la suma de matrices:\n");
mostrarMatriz(res, N);
break;
case 2:
restar(m1, m2, res, N);
printf("\nResultado de la resta de matrices:\n");
mostrarMatriz(res, N);
break;
case 3:
mult(m1, m2, res, N);
printf("\nResultado del producto de matrices:\n");
mostrarMatriz(res, N);
break;
}
}

Plantee e implemente un programa en lenguaje C que permita introducir apropiadamente una matriz NxN de números enteros (), la visualice apropiadamente por pantalla (formato matricial) y muestre la posición de un elemento punto de silla , si existe. Una matriz presenta un punto de silla si alguna posición de la misma es al mismo tiempo el menor valor de su fila y el mayor valor de su columna.

Mostrar Solución
Ejercicio_18.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#define MAX 10
void buscarPuntoDeSilla(int matriz[MAX][MAX], int N) {
int encontrado = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int candidato = matriz[i][j];
int esMenorEnFila = 1;
int esMayorEnColumna = 1;
for (int k = 0; k < N; k++) {
if (matriz[i][k] < candidato) {
esMenorEnFila = 0;
break;
}
}
for (int k = 0; k < N; k++) {
if (matriz[k][j] > candidato) {
esMayorEnColumna = 0;
break;
}
}
if (esMenorEnFila && esMayorEnColumna) {
printf("Punto de silla encontrado en la posicion [%d][%d] con valor %d.\n", i + 1, j + 1, candidato);
encontrado = 1;
}
}
}
if (!encontrado) printf("No se encontraron puntos de silla en la matriz.\n");
}
int main() {
int N;
do {
printf("Introduzca el tamano de la matriz (1 <= N < 10): ");
scanf("%d", &N);
} while (N <= 0 || N >= 10);
int matriz[MAX][MAX];
printf("Introduzca los elementos de la matriz (%dx%d):\n", N, N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Elemento [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matriz[i][j]);
}
}
buscarPuntoDeSilla(matriz, N);
}

Plantee e implemente un programa en lenguaje C que rellene tres arrays con 500 elementos enteros de forma aleatoria y posteriormente muestre por pantalla todos los números conseguidos de forma ordenada de menor a mayor.

Mostrar Solución
Ejercicio_19.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 500
#define TOTAL_SIZE (SIZE*3)
void rellenarArray(int arr[], int size) {
srand(time(NULL));
for (int i = 0; i < size; i++) arr[i] = rand() % 1000;
}
void combinarArrays(int arr1[], int arr2[], int arr3[], int combinado[], int size) {
for (int i = 0; i < size; i++) {
combinado[i] = arr1[i];
combinado[i + size] = arr2[i];
combinado[i + 2 * size] = arr3[i];
}
}
void bubble(int array[], int t) {
for (int i = 0; i < t - 1; i++) {
for (int j = 0; j < t - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
int main() {
int a1[SIZE], a2[SIZE], a3[SIZE];
int res[TOTAL_SIZE];
rellenarArray(a1, SIZE);
rellenarArray(a2, SIZE);
rellenarArray(a3, SIZE);
combinarArrays(a1, a2, a3, res, SIZE);
bubble(res, TOTAL_SIZE);
printf("Números ordenados de menor a mayor:\n");
for (int i = 0; i < TOTAL_SIZE; i++) {
printf("%d ", res[i]);
if ((i + 1) % 10 == 0) {
printf("\n"); // Imprimir 10 números por línea para mejor visualización
}
}
}

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
Ejercicio_20.c
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <maite.gonzalez@udc.es>
//
// 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];
}
}
}

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
Ejercicio_21.c
// SPDX-FileCopyrightText: 2024 Maite González Vázquez <maite.gonzalez@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#define MAX_TAREAS 20
// Define una tarea
typedef struct {
int hora;
int minutos;
char descripcion[150];
} tTarea;
// Define las tareas de un día
typedef struct {
int dia;
int mes;
int anio;
tTarea tareas[MAX_TAREAS];
} tDiaTareas;
// Define las tareas de un año
typedef struct {
tDiaTareas dias[365];
} tListaTareas;

Plantee e implemente una función en lenguaje C que reciba dos arrays de reales desordenados de 30 elementos cada uno y devuelva una array ordenado con los elementos de los dos anteriores.

Mostrar Solución
Ejercicio_22.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <stdlib.h>
#define SIZE 30
#define MERGED_SIZE (SIZE * 2)
void bubble(int array[], int tamanio) {
for (int i = 0; i < tamanio - 1; i++) {
for (int j = 0; j < tamanio - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
void fusionarYOrdenar(int array1[], int array2[], int resultado[]) {
for (int i = 0; i < SIZE; i++) resultado[i] = array1[i];
for (int i = 0; i < SIZE; i++) resultado[SIZE + i] = array2[i];
bubble(resultado, MERGED_SIZE);
}
int main() {
int array1[SIZE], array2[SIZE], resultado[MERGED_SIZE];
/*
printf("Array 1:\n");
for (int i = 0; i < SIZE; i++) scanf("%d", &array1[i]);
printf("Array 2:\n");
for (int i = 0; i < SIZE; i++) scanf("%d", &array2[i]);
*/
// Generar valores aleatorios para los arrays de prueba
printf("Generando valores aleatorios para los arrays...\n");
for (int i = 0; i < SIZE; i++) {
array1[i] = rand() % 100;
array2[i] = rand() % 100;
}
// Mostrar los arrays originales
printf("Array 1: ");
for (int i = 0; i < SIZE; i++) {
printf("%d ", array1[i]);
}
printf("\n");
printf("Array 2: ");
for (int i = 0; i < SIZE; i++) {
printf("%d ", array2[i]);
}
printf("\n");
fusionarYOrdenar(array1, array2, resultado);
printf("Array fusionado y ordenado: ");
for (int i = 0; i < MERGED_SIZE; i++) printf("%d ", resultado[i]);
printf("\n");
return 0;
}

Plantee e implemente una función en lenguaje C que reciba dos arrays de tipo base carácter, sin finalizar en ‘\0’, es decir, no son cadenas; ambos desordenados y con 100 elementos cada uno y devuelva un array ordenado con los elementos de los dos anteriores.

Mostrar Solución
Ejercicio_23.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <stdlib.h>
// Función de comparación para usar con qsort
int comparar(const void *a, const void *b) {
return (*(char*)a - *(char*)b);
}
char* combinarYOrdenar(char array1[], char array2[], int t) {
char *resultado = (char*)malloc(2 * t * sizeof(char)); // Reservar memoria para el array combinado
// Copiar los elementos del primer array al resultado
for (int i = 0; i < t; i++) {
resultado[i] = array1[i];
}
// Copiar los elementos del segundo array al resultado
for (int i = 0; i < t; i++) {
resultado[t + i] = array2[i];
}
// Ordenar el array combinado
qsort(resultado, 2 * t, sizeof(char), comparar);
return resultado; // Retornar el array combinado y ordenado
}
int main() {
int t;
printf("Ingrese el tamaño de los arrays (máximo 100): ");
scanf("%d", &t);
char array1[t], array2[t];
printf("Ingrese los %d elementos para el primer array:\n", t);
for (int i = 0; i < t; i++) {
printf("Elemento %d: ", i + 1);
scanf(" %c", &array1[i]);
}
printf("Ingrese los %d elementos para el segundo array:\n", t);
for (int i = 0; i < t; i++) {
printf("Elemento %d: ", i + 1);
scanf(" %c", &array2[i]);
}
char *arrayOrdenado = combinarYOrdenar(array1, array2, t);
printf("Array combinado y ordenado: ");
for (int i = 0; i < 2 * t; i++) {
printf("%c ", arrayOrdenado[i]);
}
printf("\n");
// Liberar la memoria
free(arrayOrdenado);
}

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
Ejercicio_24.c
// 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]);
}
}

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
Ejercicio_25.c
// 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;
}

Plantee e implemente un programa en lenguaje C que lea una frase (como máximo de 100 caracteres) y proporcione al usuario la posibilidad de sustituir alguna palabra de las introducidas por un sinónimo. Muestre por pantalla la frase original y la frase después de llevar a cabo la sustitución.

Mostrar Solución
Ejercicio_26.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <i.villar@udc.es>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <string.h>
#define MAX_LONGITUD 100 // Longitud máxima de la frase
void reemplazarPalabra(char *frase, const char *palabra, const char *sinonimo) {
int longitudPalabra = strlen(palabra);
int longitudSinonimo = strlen(sinonimo);
int longitudFrase = strlen(frase);
int palabraEncontrada = 0;
int lpos;
for (int i = 0; i <= longitudFrase - longitudPalabra; i++) {
int lpos = 0;
for (int j = 0; j < longitudPalabra; j++) {
if (frase[i + j] == palabra[j]) lpos++;
}
if (lpos == longitudPalabra) {
palabraEncontrada = 1;
// Si el sinónimo es más corto que la palabra original
if (longitudSinonimo < longitudPalabra) {
// Reemplazar la palabra con el sinónimo
for (int k = 0; k < longitudSinonimo; k++) {
frase[i + k] = sinonimo[k];
}
// Mover el resto de la cadena hacia la izquierda
int desplazamiento = longitudPalabra - longitudSinonimo;
for (int l = i + longitudSinonimo; l < longitudFrase; l++) {
frase[l - desplazamiento] = frase[l];
}
}
// Si el sinónimo es más largo que la palabra original
else if (longitudSinonimo > longitudPalabra) {
// Mover el resto de la cadena hacia la derecha para hacer espacio
int desplazamiento = longitudSinonimo - longitudPalabra;
for (int l = longitudFrase; l >= i + longitudPalabra; l--) {
frase[l + desplazamiento] = frase[l];
}
// Reemplazar la palabra con el sinónimo
for (int k = 0; k < longitudSinonimo; k++) {
frase[i + k] = sinonimo[k];
}
}
// Si la palabra y el sinónimo tienen la misma longitud
else {
// Simplemente reemplazar la palabra con el sinónimo
for (int k = 0; k < longitudSinonimo; k++) {
frase[i + k] = sinonimo[k];
}
}
break; // Solo reemplazamos la primera ocurrencia
}
}
// Si no se encontró la palabra
if (!palabraEncontrada) {
printf("La palabra no se encontró en la frase.\n");
}
}
int main() {
char frase[500];
char palabra[MAX_LONGITUD], sinonimo[MAX_LONGITUD];
// Leer la frase
printf("Ingrese una frase: ");
gets(frase);
printf("Ingrese la palabra que desea reemplazar: ");
gets(palabra);
printf("Ingrese el sinónimo: ");
gets(sinonimo);
printf("\nFrase original: %s\n", frase);
reemplazarPalabra(frase, palabra, sinonimo);
printf("Frase después de la sustitución: %s\n", frase);
}

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.

Ejemplo de Ejecución
Introduzca una frase de como máximo 100 caracteres:
Buenos días, vamos a comenzar. Encended los equipos.
Buenos 6
días 4
vamos 5
a 1
comenzar 8
Encended 8
los 3
equipos 7
Mostrar Solución
Ejercicio_27.c
// 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 string
void 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 them
void 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;
}

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
Ejercicio_28.c
// 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;
}

Diseñe una función que devuelva al revés la cadena recibida como parámetro.

Mostrar Solución
Ejercicio_29.c
// 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;
}

Diseñe una función que sume dos números de 2500 cifras cada uno.

Mostrar Solución
Ejercicio_30.c
// SPDX-FileCopyrightText: 2025 Isabel Villar García <<i.villar@udc.es>>
//
// SPDX-License-Identifier: GPL-3.0-only
#include <stdio.h>
#include <string.h>
#define MAX_LONGITUD 100 // Longitud máxima de la frase
int main() {
char frase[MAX_LONGITUD];
char palabra[MAX_LONGITUD], sinonimo[MAX_LONGITUD];
printf("Ingrese una frase: ");
gets(frase);
printf("Ingrese la palabra que desea reemplazar: ");
gets(palabra);
printf("Ingrese el sinónimo: ");
gets(sinonimo);
printf("\nFrase original: %s %d\n", frase, strlen(frase));
printf("Palabra: %s %d\n", palabra,strlen(palabra));
printf("Sinonimo: %s %d", sinonimo,strlen(sinonimo));
}

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
Ejercicio_36.c
// 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;
}

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
Ejercicio_37.c
// 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;
}

Plantee e implemente un programa en lenguaje C para simular el juego de la vida de John Conway.

Mostrar Solución
Ejercicio_40.c
// 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 = ENABLED
int 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 matrix
bool 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 status
void 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 status
void 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 generation
void 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 matrix
void 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 status
void 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 matrix
void 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 condition
void 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;
}