Answer the question
In order to leave comments, you need to log in
How to get the result of a function in main when working with matrices?
Good day to all, I need to write a function for the sum of the elements of the main diagonal of the matrix. The program fully works with one exception, I can't move the code into a separate function. Perhaps an error in the parameters that I pass to the function, or in the function call itself
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int sum (int n, int matrix[n][n]) {
int sum = 0;
for (int j = 0; j < n; ++j){
for (int i = 0; i < n; ++i){
if (j == i){
sum += matrix[j][i];
}
}
}
return sum;
}
int main ()
{
int n, i, j;
int sum_of = 0;
printf("n \n");
scanf("%d",&n);
int matrix[n][n];
srand(time(0));
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
matrix[i][j] = rand()%10;
}
}
for (i = 0; i < n; i++){
for (j = 0; j < n; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
sum_of = sum(matrix[][]);
printf("%d", sum_of);
return 0;
}
Answer the question
In order to leave comments, you need to log in
sum_of = sum(matrix[][]);
int sum (int n, int matrix[n][n]) { int sum = 0; for (int j = 0; j < n; ++j){ for (int i = 0; i < n; ++i){ if (j == i){ sum += matrix[j][i]; } } } return sum; }
int sum (int n, int matrix[n][n])
{
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += matrix[i][i];
}
return sum;
}
Something I doubt that your program works. You are trying to set an array of arbitrary length on the stack. On the stack, you can only create arrays of a fixed length, since memory is allocated for them at compile time. In your case, you need to use a heap (see the malloc() and free() functions) https://en.wikipedia.org/wiki/C_dynamic_memory_all...
This is if we are talking about C, if you write it in C ++ (please distinguish these languages) then the vector will help you
The program is fully functional
printf("n \n");
scanf("%d",&n);
int matrix[n][n];
int *matrix;
matrix = calloc( n * n, 1);
free(matrix);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question