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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,879 questions

51,805 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
...