Arrays
Introducción
En P1 (C) trabajabas con arrays: float v[20], int m[10][10], y pasabas el array a funciones junto con su longitud.
En P2 (C++) seguimos entendiendo los arrays, pero normalmente preferimos:
std::vector<T>para tamaño variable (se ajusta a los datos).std::array<T, N>cuando el tamaño es fijo y conocido.- Pasar contenedores por referencia para evitar copias.
En este tema usamos 3 ejemplos representativos (vector con centinela, máximo en vector, suma de matrices).
1) Leer notas hasta -1 o máximo (20) y calcular la media
P1 — C
#include <stdio.h>#include <stdbool.h>
#define TAM 20
float calculaMedia(float a[], int len);int rellenaDatos(float v[], int max);
int main() { float v[TAM]; int len; float media;
len = rellenaDatos(v, TAM); media = calculaMedia(v, len); printf("La nota media es %.2f\n", media);
return 0;}
float calculaMedia(float a[], int len) { float suma = 0.0f; float res;
for (int i = 0; i < len; i++) { suma = suma + a[i]; }
if (len > 0) { res = suma / len; } else { res = 0.0f; }
return res; // único return}
int rellenaDatos(float v[], int max) { int i = 0; float nota; bool valido;
do { printf("Introduce nota (-1 para terminar): "); scanf("%f", ¬a); valido = nota != -1.0f && i < max; if (valido) { v[i] = nota; i = i + 1; } } while (valido);
return i;}P2 — C++
#include <iostream>#include <vector>#include <iomanip>
double calculaMedia(const std::vector<double>& v);std::vector<double> leerNotas(std::size_t max);
int main() { const std::size_t MAX = 20;
std::vector<double> notas = leerNotas(MAX); double media = calculaMedia(notas);
std::cout << std::fixed << std::setprecision(2); std::cout << "La nota media es " << media << "\n";
return 0;}
std::vector<double> leerNotas(std::size_t max) { std::vector<double> v; v.reserve(max); // evita realocaciones frecuentes
double nota; while (v.size() < max) { std::cout << "Introduce nota (-1 para terminar): "; std::cin >> nota;
if (nota == -1.0) break; v.push_back(nota); }
return v;}
double calculaMedia(const std::vector<double>& v) { if (v.empty()) return 0.0;
double suma = 0.0; for (double x : v) suma += x;
return suma / static_cast<double>(v.size());}2) Leer un vector de enteros y obtener el mayor (con funciones)
P1 — C
#include <stdio.h>
#define TAM 10typedef int TVector[TAM];
int leerVector(TVector vector);void imprimirVector(TVector vector, int elementos);int mayorVector(TVector vector, int elementos);
int main() { TVector vector; int mayor, elementos;
elementos = leerVector(vector); imprimirVector(vector, elementos); mayor = mayorVector(vector, elementos);
printf("El elemento mayor del vector es : %d\n", mayor);
return 0;}
int leerVector(TVector vector) { int cantidad;
printf("¿Cuantos elementos vas a introducir [1-%d]?\n", TAM); scanf("%d", &cantidad);
for (int i = 0; i < cantidad; i++) { printf("Introduce el numero de la posicion %d: ", i); scanf("%d", &vector[i]); } return cantidad;}
void imprimirVector(TVector vector, int cantidad) { printf("Valores del vector:\n"); for (int i = 0; i < cantidad; i++) { printf("%d ", vector[i]); } printf("\n");}
int mayorVector(TVector vector, int cantidad) { int mayor = vector[0];
for (int i = 1; i < cantidad; i++) { if (vector[i] > mayor) mayor = vector[i]; } return mayor;}P2 — C++
#include <iostream>#include <vector>
std::vector<int> leerVector(std::size_t max);void imprimirVector(const std::vector<int>& v);int mayorVector(const std::vector<int>& v);
int main() { const std::size_t MAX = 10;
std::vector<int> v = leerVector(MAX); imprimirVector(v);
int mayor = mayorVector(v); std::cout << "El elemento mayor del vector es: " << mayor << "\n";
return 0;}
std::vector<int> leerVector(std::size_t max) { std::size_t cantidad;
std::cout << "¿Cuantos elementos vas a introducir [1-" << max << "]?\n"; std::cin >> cantidad;
if (cantidad > max) cantidad = max;
std::vector<int> v(cantidad); for (std::size_t i = 0; i < cantidad; i++) { std::cout << "Introduce el numero de la posicion " << i << ": "; std::cin >> v[i]; } return v;}
void imprimirVector(const std::vector<int>& v) { std::cout << "Valores del vector:\n"; for (int x : v) { std::cout << x << " "; } std::cout << "\n";}
int mayorVector(const std::vector<int>& v) { int mayor = v[0]; for (int x : v) { if (x > mayor) mayor = x; } return mayor;}3) Matrices: leer dos matrices, sumarlas e imprimir el resultado
P1 — C
#include <stdio.h>
#define FILAS 10#define COLUMNAS 10
typedef int TMatriz[FILAS][COLUMNAS];
void rellena(TMatriz);void suma(TMatriz, TMatriz, TMatriz);void imprime(TMatriz);
int main() { TMatriz m1, m2, resultado;
rellena(m1); rellena(m2); suma(m1, m2, resultado); imprime(resultado);
return 0;}
void rellena(TMatriz m) { for (int i = 0; i < FILAS; i++) for (int j = 0; j < COLUMNAS; j++) { printf("Valor [%d,%d]: ", i, j); scanf("%d", &m[i][j]); }}
void suma(TMatriz m1, TMatriz m2, TMatriz r) { for (int i = 0; i < FILAS; i++) for (int j = 0; j < COLUMNAS; j++) { r[i][j] = m1[i][j] + m2[i][j]; }}
void imprime(TMatriz m) { for (int i = 0; i < FILAS; i++) { for (int j = 0; j < COLUMNAS; j++) printf(" %d", m[i][j]); printf("\n"); }}P2 — C++
#include <iostream>#include <array>
constexpr int FILAS = 10;constexpr int COLUMNAS = 10;
using Matriz = std::array<std::array<int, COLUMNAS>, FILAS>;
void rellena(Matriz& m);Matriz suma(const Matriz& a, const Matriz& b);void imprime(const Matriz& m);
int main() { Matriz m1{}, m2{};
rellena(m1); rellena(m2);
Matriz r = suma(m1, m2); imprime(r);
return 0;}
void rellena(Matriz& m) { for (int i = 0; i < FILAS; i++) { for (int j = 0; j < COLUMNAS; j++) { std::cout << "Valor [" << i << "," << j << "]: "; std::cin >> m[i][j]; } }}
Matriz suma(const Matriz& a, const Matriz& b) { Matriz r{}; for (int i = 0; i < FILAS; i++) { for (int j = 0; j < COLUMNAS; j++) { r[i][j] = a[i][j] + b[i][j]; } } return r;}
void imprime(const Matriz& m) { for (int i = 0; i < FILAS; i++) { for (int j = 0; j < COLUMNAS; j++) { std::cout << " " << m[i][j]; } std::cout << "\n"; }}