Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,105 questions

40,777 answers

573 users

How to sum the diagonal (from right [LEN - 1][0]) of a matrix in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

#define LEN 5

int sum_matrix_diagonal(int arr[][LEN], char d);

int main(void)
{
    int i, j, arr2d[LEN][LEN];
   
    srand(time(NULL));
    for (i = 0; i < LEN; i++)
        for (j = 0; j < LEN; j++)
            arr2d[i][j] = rand() % 10 + 1;
            
    for (i = 0; i < LEN; i++)
    {
        for (j = 0; j < LEN; j++)
            printf("%4i", arr2d[i][j]);
         
        printf("\n");
    }
  
    printf("\nsum left = %i\n", sum_matrix_diagonal(arr2d, 'l')); // from left [0]0]
    printf("\nsum right = %i\n", sum_matrix_diagonal(arr2d, 'r')); // form right [LEN - 1][0]
    
    return 0;
}

int sum_matrix_diagonal(int arr[][LEN], char d)
{
    int i, j, sum = 0;
    
    if (d == 'l')
        for (i = 0; i < LEN; i++) sum += arr[i][i];
    else if (d == 'r')
             for (j = 0, i = LEN - 1; i >= 0; i--, j++) sum += arr[i][j];
    
    return sum;
}

/* 
run:

   1   4   5   4   1
   5  10   3   8   1
   6   5   1   1   2
   1   1   8   9   3
   6  10   1   9   7

sum left = 28

sum right = 17

*/






answered Sep 22, 2014 by avibootz
...