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,880 questions

51,806 answers

573 users

How to sum the main diagonal (from left [0][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]);

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 = %i\n", sum_matrix_diagonal(arr2d));
    
    return 0;
}

int sum_matrix_diagonal(int arr[][LEN])
{
    int i, sum = 0;
    
    for (i = 0; i < LEN; i++) sum += arr[i][i];
    
    return sum;
}

/* 
run:

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

sum = 34

*/




answered Sep 22, 2014 by avibootz
...