78 lines
2.2 KiB
C
78 lines
2.2 KiB
C
#include <stdio.h>
|
|
// Question 3
|
|
|
|
/* I know that the program would be overall simpler if I printed the sums in the function as they are
|
|
* calculated, but I have always been taught to avoid printing within functions, so I went with the
|
|
* returning an array of the sums method. It has the benefit of being able to use the sums later in the program
|
|
* if necessary
|
|
*/
|
|
|
|
// Function to calculate sum of each row of matrix
|
|
// Arguments are array width, height, the array, and the array of return values
|
|
void row_sums(int width, int height, int matrix[width][height], int return_array[]) {
|
|
int row_sum;
|
|
for(int i = 0; i < height; i++) {
|
|
row_sum = 0;
|
|
for(int j = 0; j < width; j++) {
|
|
row_sum+=matrix[i][j];
|
|
}
|
|
return_array[i] = row_sum;
|
|
}
|
|
}
|
|
// Function to calculate sum of each column of matrix
|
|
// Arguments are array width, height, the array, and the array of return values
|
|
void column_sums(int width, int height, int matrix[width][height], int return_array[]) {
|
|
int column_sum;
|
|
for(int i = 0; i < height; i++) {
|
|
column_sum = 0;
|
|
for(int j = 0; j < width; j++) {
|
|
column_sum+=matrix[j][i];
|
|
}
|
|
return_array[i] = column_sum;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
int width, height;
|
|
|
|
printf("Enter width then enter height:\n");
|
|
scanf("%d", &width);
|
|
scanf("%d", &height);
|
|
|
|
int matrix[width][height]; // The 2D array that holds the matrix
|
|
// Input values into the matrix
|
|
for(int i = 0; i < width; i++) {
|
|
for(int j = 0; j < height; j++) {
|
|
printf("Enter matrix value %d,%d: ", i, j);
|
|
scanf("%d", &matrix[i][j]);
|
|
}
|
|
}
|
|
// Print the matrix
|
|
for(int i = 0; i < width; i++) {
|
|
for(int j = 0; j < height; j++) {
|
|
printf("%d ", matrix[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
// Find sums for each row and print them
|
|
int row_sum_values[width]; // Holds the sums for each row
|
|
row_sums(width, height, matrix, row_sum_values);
|
|
printf("Row sum values are: ");
|
|
for(int i = 0; i < width; i++) {
|
|
printf("%d, ", row_sum_values[i]);
|
|
}
|
|
printf("\n");
|
|
|
|
// Find sums for each column and print them
|
|
int column_sum_values[height]; // Holds the sums for each column
|
|
column_sums(width, height, matrix, column_sum_values);
|
|
printf("Column sum values are: ");
|
|
for(int i = 0; i < height; i++) {
|
|
printf("%d, ", column_sum_values[i]);
|
|
}
|
|
printf("\n");
|
|
|
|
return 0;
|
|
}
|