Ejercicios 13 04 parte 2

Ejercicios array con tope parte 2

1) Dados dos arrays con tope de hasta N elementos, calcular el array que contiene la suma de sus elementos. Usar una función. Precondición: tienen l a misma cantidad de elementos (valor del tope).
 2) Dado un array con tope de hasta N elementos, calcular el máximo del array. Usar una función.
 3) Idem anterior pero mínimo.
 4) Dado un array con tope de hasta N elementos de Enteros y una función de dominio Z, devolver el array de los f(x) para cada elemento x del array. 



#include <stdio.h>
#define MAX 10   // tamaño máximo de los arrays
// Definimos un tipo que contiene el array y su tope
typedef struct {
    int datos[MAX];
    int tope;   // cantidad de elementos válidos (0..MAX)
} ArrayEnteros;
// --------------- FUNCIONES AUXILIARES -----------------
// Suma de dos arrays
int sumarArrays(ArrayEnteros a, ArrayEnteros b, ArrayEnteros *resultado) {
    if (a.tope != b.tope) {
        resultado->tope = 0;
        return -1; // error: topes distintos
    }
    resultado->tope = a.tope;
    for (int i = 0; i < a.tope; i++) {
        resultado->datos[i] = a.datos[i] + b.datos[i];
    }
    return 0; // éxito
}
// Leer array desde teclado
int leerArray(ArrayEnteros *arr) {
    printf("Ingrese la cantidad de elementos (1..%d): ", MAX);
    scanf("%d", &arr->tope);
    if (arr->tope < 1 || arr->tope > MAX) {
        arr->tope = 0;
        return -1; // error: tope inválido
    }
    for (int i = 0; i < arr->tope; i++) {
        printf("Elemento %d: ", i + 1);
        scanf("%d", &arr->datos[i]);
    }
    return 0; // éxito
}
// Mostrar array
void mostrarArray(ArrayEnteros arr) {
    printf("[ ");
    for (int i = 0; i < arr.tope; i++) {
        printf("%d ", arr.datos[i]);
    }
    printf("]\n");
}
// Máximo
int maximoArray(ArrayEnteros arr, int *max) {
    if (arr.tope == 0) return -1;
    *max = arr.datos[0];
    for (int i = 1; i < arr.tope; i++) {
        if (arr.datos[i] > *max) {
            *max = arr.datos[i];
        }
    }
    return 0;
}
// Mínimo
int minimoArray(ArrayEnteros arr, int *min) {
    if (arr.tope == 0) return -1;
    *min = arr.datos[0];
    for (int i = 1; i < arr.tope; i++) {
        if (arr.datos[i] < *min) {
            *min = arr.datos[i];
        }
    }
    return 0;
}
// --------------- NUEVO: FUNCION f(x) -----------------
// f(x) = x*x + 2x + 1
int f(int x) {
    return x*x + 2*x + 1;
}
// Aplica f(x) a cada elemento de un array
int aplicarFuncion(ArrayEnteros arr, ArrayEnteros *resultado) {
    if (arr.tope == 0) {
        resultado->tope = 0;
        return -1; // error: array vacío
    }
    resultado->tope = arr.tope;
    for (int i = 0; i < arr.tope; i++) {
        resultado->datos[i] = f(arr.datos[i]);
    }
    return 0; // éxito
}
// --------------- MAIN -----------------
int main() {
    ArrayEnteros a, b, suma, transformado;
    // Leer primer array
    if (leerArray(&a) != 0) {
        printf("Error: tope inválido en el primer array.\n");
        return 1;
    }
    // Leer segundo array
    if (leerArray(&b) != 0) {
        printf("Error: tope inválido en el segundo array.\n");
        return 1;
    }
    // Sumar arrays
    if (sumarArrays(a, b, &suma) == 0) {
        printf("Array suma: ");
        mostrarArray(suma);
        // Máximo y mínimo
        int max, min;
        if (maximoArray(suma, &max) == 0)
            printf("Máximo del array suma: %d\n", max);
        if (minimoArray(suma, &min) == 0)
            printf("Mínimo del array suma: %d\n", min);
        // Aplicar f(x) a cada elemento
        if (aplicarFuncion(suma, &transformado) == 0) {
            printf("Array transformado con f(x)=x*x+2x+1: ");
            mostrarArray(transformado);
        } else {
            printf("Error: no se pudo aplicar f(x).\n");
        }
    } else {
        printf("Error: los arrays no tienen la misma cantidad de elementos.\n");
    }
    return 0;
}





Si queremos que la función f en la última parte pase como parámetro, lo hacemos con punteros a función.

#include <stdio.h>

#define MAX 10

typedef struct {
    int datos[MAX];
    int tope;
} ArrayEnteros;

// f(x) = x*x + 2x + 1
int f(int x) {
    return x*x + 2*x + 1;
}

// Otra función de ejemplo: g(x) = x-5
int g(int x) {
    return x - 5;
}

// Aplica una función pasada como parámetro a cada elemento del array
// Devuelve 0 si todo salió bien, -1 si el array está vacío
int aplicarFuncion(ArrayEnteros arr, ArrayEnteros *resultado, int (*func)(int)) {
    if (arr.tope == 0) {
        resultado->tope = 0;
        return -1;
    }
    resultado->tope = arr.tope;
    for (int i = 0; i < arr.tope; i++) {
        resultado->datos[i] = func(arr.datos[i]); // aquí usamos el puntero a función
    }
    return 0;
}

// Mostrar array
void mostrarArray(ArrayEnteros arr) {
    printf("[ ");
    for (int i = 0; i < arr.tope; i++) {
        printf("%d ", arr.datos[i]);
    }
    printf("]\n");
}

int main() {
    ArrayEnteros a = {{1, 2, 3, 4, 5}, 5};
    ArrayEnteros resultado;

    // Aplicar f(x)
    if (aplicarFuncion(a, &resultado, f) == 0) {
        printf("Aplicando f(x)=x*x+2x+1: ");
        mostrarArray(resultado);
    }

    // Aplicar g(x)
    if (aplicarFuncion(a, &resultado, g) == 0) {
        printf("Aplicando g(x)=x-5: ");
        mostrarArray(resultado);
    }

    return 0;
}
 

Comentarios

Entradas populares de este blog