All Files here
This commit is contained in:
70
Q3.c
Normal file
70
Q3.c
Normal file
@@ -0,0 +1,70 @@
|
||||
#include <stdio.h>
|
||||
/* 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. Takes
|
||||
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. Takes
|
||||
void column_sums(int width, int height, int matrix[width][height], int return_array[]) {
|
||||
int column_sum;
|
||||
for(int i = 0; i < width; i++) {
|
||||
column_sum = 0;
|
||||
for(int j = 0; j < height; j++) {
|
||||
column_sum+=matrix[i][j];
|
||||
}
|
||||
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];
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
int row_sum_values[height];
|
||||
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");
|
||||
|
||||
int column_sum_values[height];
|
||||
column_sums(width, height, matrix, column_sum_values);
|
||||
printf("Column sum values are: ");
|
||||
for(int i = 0; i < width; i++) {
|
||||
printf("%d, ", column_sum_values[i]);
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user