TU-Programmieren_2/lab1/taskB.cpp
2025-04-09 10:22:44 +02:00

95 lines
2.4 KiB
C++

/// @file
/// @brief task B
/// g++ -std=c++20 taskB.cpp -o taskB && ./taskB
#include <iostream>
#include <vector>
/// @todo implement your functions here, details see main.ipynb
/// @todo " 1. `sum`: **Summe** aller Elemente eines `Vector'",
int sum(std::vector<double> vector) {
double sum = 0;
for (auto i : vector) {
sum += i;
}
return sum;
}
/// @todo " 2. `sum`: **Summe** aller Elemente einer `Matrix`",
int sum(std::vector<std::vector<int>> matrix) {
int sum = 0;
for (auto row : matrix) {
for (auto i : row) {
sum += i;
}
}
return sum;
}
/// @todo " 3. `print`: **Formatierte Ausgabe** (in der Konsole) eines `Vectors` (in einer Zeile)",
void printVector(std::vector<double> vector) {
for (auto i : vector) {
std::cout << i << " ";
}
std::cout << std::endl;
}
/// @todo " 3. `print`: **Formatierte Ausgabe** (in der Konsole) einer `Matrix` (Zeile für Zeile)",
void printMatrix(std::vector<std::vector<int>> matrix) {
for (auto row : matrix) {
for (auto i : row) {
std::cout << i << " ";
}
std::cout << std::endl;
}
}
/// @todo " 4. `cout_even`: **Abzählen** wie viele Elemente einer `Matrix` gerade sind",
int countEven(std::vector<std::vector<int>> matrix) {
int count = 0;
for (auto row : matrix) {
for (auto i : row) {
if (i % 2 == 0) {
count++;
}
}
}
return count;
}
/// @todo " 5. `mean`: **Durchschnitt aller Elemente** einer `Matrix`",
float meanMatrix(std::vector<std::vector<int>> matrix) {
int sum = 0;
int count = 0;
for (auto row : matrix) {
for (auto i : row) {
sum += i;
count++;
}
}
return (float)sum / count;
}
int main() {
// one-dimensional sequence (vector) with 5 values
std::vector<double> vec{1.2, 2.5, 3., 4.1, 5.9};
// two-dimensional sequence, here we call it a matrix, with 3 rows with 4 values in each row
std::vector<std::vector<int>> mat{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
/// @todo call your functions using 'vec' or 'mat' as arguments and print the results
std::cout << "Sum of vector: " << sum(vec) << std::endl;
std::cout << "Sum of matrix: " << sum(mat) << std::endl;
std::cout << "Print vector: ";
printVector(vec);
std::cout << "Print matrix: ";
printMatrix(mat);
std::cout << "Count even: " << countEven(mat) << std::endl;
std::cout << "Mean of matrix: " << meanMatrix(mat) << std::endl;
return 0;
}