TU-Programmieren_2/exercise10/task1.main.c
2025-04-09 10:22:44 +02:00

68 lines
2.3 KiB
C

/// @file
/// @brief Task1: "single-file" executable C program
/// @todo Include C standard library headers, as needed
/// @todo Implement a function 'max_column_sum' according to the description below:
/// The function receives a "m x n"-matrix holding signed integer values stored in a contiguous block of memory using
/// row-major layout. Specifically it receives these arguments
/// - number of rows m
/// - number of columns n
/// - pointer to a contiguous block of memory containing m*n signed integer values
/// - row-major storage order is used, access of element (i,j) -> data[j + n*i]
/// The function then calculates the maximum column sum, i.e. the maximum sum of values in one column of the matrix, and
/// returns this value.
/// @todo Implement a 'main' function conducting the following tasks in this order:
/// - construct three local variables containing the following values:
/// - an integer value for the number of rows: 2
/// - an integer value for the number of columns: 4
/// - an array of integer values to be interpreted as a 2x4 matrix in row-major layout containing these values:
/// {5, -2, -12, 4, 1, 3, -5, 6}
/// - use your function to calculate the maximum column sum of the 2x4 matrix specified by your three local variables
/// - print the result to the console
/// @file
/// @brief Task1: "single-file" executable C program
#include <stdio.h>
/// Function to calculate the maximum column sum of a matrix
int max_column_sum(int m, int n, int data[]) {
int max_sum = data[0]; // Initialize with first element
// Loop through each column
for (int j = 1; j < n; j++) {
int current_sum = 0;
// Loop through each row in the current column
for (int i = 0; i < m; i++) {
// Calculate sum of elements in current column
current_sum += data[j + n * i];
}
// Update max_sum if current sum is greater
if (current_sum > max_sum) {
max_sum = current_sum;
}
}
return max_sum;
}
int main() {
// Define matrix dimensions
int rows = 2;
int cols = 4;
// Define matrix data in row-major order
int data[] = {5, -2, -12, 4, 1, 3, -5, 6};
// Calculate maximum column sum
int max_column_sum_value = max_column_sum(rows, cols, data);
// Print the result
printf("Maximum column sum: %d\n", max_column_sum_value);
return 0;
}