Example 2: Matricies (two dimensional array) and Write a C diagonal elements. Yo
ID: 3739061 • Letter: E
Question
Example 2: Matricies (two dimensional array) and Write a C diagonal elements. Your program should Example alemes fed function te matrix and compute the sum of the right to left diagonal elements. Your program read in the matrix. Your program should have a user defined function to add the program to read in a square compute check to see if the matrix is square . If not, return an error. 0 0 10001 should return a sum of 1+1+1+14 45 5 Example: 1 00 5 65 15 15 105 1 should return a sum of 25+65+10 100 Sample code void readMatrix(int array1, int rows, int columns) int addDiagonal(int arrary1, int rows, int columns); int main(vold) . void){ i return 0 void readMatrixint array1, int rows, int columns) return; int addDiagonalint arraryl, int rows, int columns) return sumExplanation / Answer
#include <stdio.h>
#include <stdlib.h>
void readMatrix(int **array, int rows, int cols);
int addDiagonal(int **array, int rows, int cols);
void readMatrix(int **array, int rows, int cols)
{
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
scanf("%d",&array[i][j]);
}
}
return;
}
int addDiagonal(int **array, int rows, int cols)
{
int sum = 0;
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(i==j)
sum += array[i][j];
}
}
return sum;
}
int main(void)
{
int rows, cols;
printf("Enter the number of rows :");
scanf("%d",&rows);
printf("Enter the number of columns :");
scanf("%d",&cols);
int **array=(int **)malloc(rows * sizeof(int));
for(int i=0;i<cols;i++)
array[i]=(int *)malloc(cols * sizeof(int));
readMatrix(array, rows, cols);
printf("Sum of Diagonals : %d ", addDiagonal(array, rows, cols));
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.