0

The code given below is a code for n*n matrix however on executing this code gives garbage values as output for n>=3.Kindly suggest me why?Also if possibly can somebody tell me how i can return 2D array from a function in c++.Thanks in advance.

#include<iostream>

using namespace std;
void rowcol(int[][10],int[][10],int,int);

int det(int arr[][10],int n)
{
      int cofact[10][10];
      if(n==2)
           return (arr[0][0]*arr[1][1])-(arr[0][1]*arr[1][0]);

      int val=0,flg=1;
      for(int i=0;i<n;i++)
      {
          rowcol(arr,cofact,i,n);
          val=val+(flg*det(cofact,n-1));
          flg*=-1;
       }

       return val;

   }

   void rowcol(int arr[][10] ,int cofact[][10],int l,int n)
    {

         for(int i=0;i<n;i++)
         {
            for(int j=0;j<n;j++)
            {
                if((i!=l)&&(j!=l))
                    cofact[i][j]=arr[i][j];
             }
         }

       }


      int main()
      {
         int n,val;
         int arr[10][10];
         cout<<"Enter the size of matrix:";
         cin>>n;
         cout<<"\nEnter the array elements row by row";
         for(int i=0;i<n;i++)
         {
           cout<<"\nEnter Row "<<i<<":";
           for(int j=0;j<n;j++)
            {
                cin>>arr[i][j];
            }
         }

         val=det(arr,n);
         cout<<"\nThe determinant of given matrix is:"<<val;

         return 0;
          }
  • 1
    Instead of hard-coding the matrix dimensions, use `std::vector`. – Some programmer dude Jan 18 '22 at 06:15
  • 1
    Also take this opportunity to learn how to *debug* your programs. For example by using a *debugger* to step through your code statement by statement while monitoring variables and their values. – Some programmer dude Jan 18 '22 at 06:15
  • 1
    As a probable hint about your problem: If you have read [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) or taken good classes, you should have known that uninitialized local variables (including arrays) will have *indeterminate* (read: garbage) values, and using such values in any way will lead to *undefined behavior*. – Some programmer dude Jan 18 '22 at 06:18
  • The way you extract the submatrix is not correct. The resulting matrix should have a size of (n-1) x (n-1) – Damien Jan 18 '22 at 14:12

0 Answers0