# How can i solve this matrix problem using recursion function in c?

I have already solved this problem using for loop.

Given an n x n matrix A. Here n is number of row and column. Write a recursive function to find the sum of the diagonal elements of A.

Example:

3 2 1
6 3 4
9 8 3

Output: 9

``````
#include<stdio.h>

void main()
{
int mat[12][12];
int i,j,row,col,sum=0;
printf("Enter the number of rows and columns for 1st matrix\n");
scanf("%d%d",&row,&col);
printf("Enter the elements of the matrix\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&mat[i][j]);
}
}

printf("The matrix\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(i==j)
{
sum=sum+mat[i][j];
}
}
}

printf("The sum of diagonal elements of a square matrix = %d\n",sum);
}
``````

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (`</>`) will also add backticks around text.

Note: Backticks are not single quotes.

Thanks for editing @ArielLeslie