I have simple program that gets the sum of main and anti diagonals of a matrix. And then it get the sum of first and last column of a matrix.For example:
1 2 3
4 5 6 --> The matrix
7 8 9
md = 1 5 9 = 15
ad = 7 5 3 = 15
lastCol = 3 6 9 = 18
firstCol = 1 4 7 = 12
How can i get the sum of the firstCol of a square matrix ?
Here is my code:
int main(){
int n;
scanf("%d",&n);
int i,j,a[n][n],firstCol=0,lastCol=0,md=0,ad=0;
for(i = 0;i <n;i ){
for(j=0;j<n;j ){
scanf("%d",&a[i][j]);
}
}
for(i = 0;i <n;i ){
for(j=0;j<n;j ){
if(i==j){
md =a[i][j];
}
if(i j==n-1){
ad =a[i][j];
}
}
}
for(i=0;i<n;i ){
lastCol =a[i][n-1];
}
}
CodePudding user response:
for (i = 0; i < n; i ) {
firstCol = a[i][0];
}
CodePudding user response:
Use functions. Try to make them a bit more universal. This one will return sum of the first column of any size array.
long long int sumFirstCol(size_t rows, size_t cols, int (*array)[cols])
{
long long int result = 0;
if(array && rows && cols)
{
for(size_t row = 0; row < rows; row )
{
result = array[row][0];
}
}
return result;
}
int main(void)
{
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},};
printf("%lld\n", sumFirstCol(3, 3, matrix));
}