Saturday, 28 June 2014

C++ program to find determinant of a matrix

 
Here is a C++ program to find determinant of a matrix .Here I have given two methods, in first method I have directly applied the formula and in second method I have used for-loop and bitwise operators .


C++ program to find determinant of matrix


#include<iostream>
using namespace std;
int main()
{
    int a[10][10],order,deter=0,z=1;
    cout<<"Enter order of matrix : ";
    cin>>order;
    if(order>3&&order<2)
    {
        cout<<"Cannot be calculated ";
        return 0;
    }
    cout<<"Enter matrix : "<<endl;
    for(int i=0;i<order;i++)
        for(int j=0;j<order;j++)
           cin>>a[i][j];
    if(order==2)
    {
        cout<<"Determinant of matrix : "<<(a[0][0]*a[1][1]-a[0][1]*a[1][0]);
        return 0;
    }

        deter+=a[0][0]*(a[1][1]*a[2][2]-a[1][2]*a[2][1]);
        deter-=a[0][1]*(a[1][0]*a[2][2]-a[1][2]*a[2][0]);
        deter+=a[0][2]*(a[1][0]*a[2][1]-a[1][1]*a[2][0]);
    cout<<"Determinant of matrix : "<<deter;
    return 0;
}

C++ program to find determinant of matrix using for-loop and bitwise operator

#include<iostream>
using namespace std;
int main()
{
    int a[10][10],order,deter=0,z=1;
    cout<<"Enter order of matrix : ";
    cin>>order;
    if(order>3&&order<2)
    {
        cout<<"Cannot be calculated ";
        return 0;
    }
    cout<<"Enter matrix : "<<endl;
    for(int i=0;i<order;i++)
        for(int j=0;j<order;j++)
           cin>>a[i][j];
    if(order==2)
    {
        cout<<"Determinant of matrix : "<<(a[0][0]*a[1][1]-a[0][1]*a[1][0]);
        return 0;
    }
    for(int i=0;i<3;i++,z=-z)
        deter=deter+a[0][i]*z*(a[1][1&(1<<i)]*a[2][3&(26>>(2*i))]-a[1][3&(26>>(2*i))]*a[2][1&(1<<i)]);
    cout<<"Determinant of matrix : "<<deter;
    return 0;
}

No comments:

Post a Comment