Saturday 28 June 2014

C++ program to find nth power of a matrix

Here are C++ program to find nth power of a matrix. In second program I have used operator overloading to find nth power of a matrix.


C++ program to find nth power of a matrix


#include<iostream>
using namespace std;
void copy(int (&a)[10][10],int (&b)[10][10],int ord)
{
    for(int i=0;i<ord;i++)
        for(int j=0;j<ord;j++)
           b[i][j]=a[i][j];
}
void mult(int (&a)[10][10],int (&b)[10][10],int (&c)[10][10],int ord)
{
    int sum=0;
    for(int i=0;i<ord;i++)
    {
       for(int j=0;j<ord;j++)
       {
           for(int k=0;k<ord;k++)
                sum+=a[i][k]*b[k][j];
           c[i][j]=sum;
           sum=0;
       }
    }
}
int main()
{
    int c[10][10],a[10][10],b[10][10],ord,sum=0,n;
    cout<<"Enter order of matrix (max 10*10): ";
    cin>>ord;
    cout<<"Enter power of : ";
    cin>>n;
    cout<<"Enter matrix A : "<<endl;
    for(int i=0;i<ord;i++)
        for(int j=0;j<ord;j++)
           cin>>a[i][j];
    copy(a,b,ord);
    for(int i=0;i<n-1;i++)
    {
        mult(a,b,c,ord);
        copy(c,b,ord);
    }
    cout<<"Matrix A^"<<n<<"  = "<<endl;
    for(int i=0;i<ord;i++)
    {
        for(int j=0;j<ord;j++)
            cout<<c[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}



C++ program to find nth power of a matrix using operator overloading


#include<iostream>
using namespace std;
struct pow
{
  int ar[10][10];
};
int ord;
void copy(pow &a,pow &b)
{
    for(int i=0;i<ord;i++)
        for(int j=0;j<ord;j++)
           b.ar[i][j]=a.ar[i][j];
}
void mult(pow &a,pow &b,pow &c)
{
    int sum=0;
    for(int i=0;i<ord;i++)
    {
       for(int j=0;j<ord;j++)
       {
           for(int k=0;k<ord;k++)
                sum+=a.ar[i][k]*b.ar[k][j];
           c.ar[i][j]=sum;
           sum=0;
       }
    }
}
pow operator^(pow &a,int n)
{
    pow c,b;
    copy(a,b);
    for(int i=0;i<n-1;i++)
    {
        mult(a,b,c);
        copy(c,b);
    }
    return c;
}
int main()
{
    pow a;
    int n;
    cout<<"Enter order of matrix (max 10*10): ";
    cin>>ord;
    cout<<"Enter power of : ";
    cin>>n;
    cout<<"Enter matrix A : "<<endl;
    for(int i=0;i<ord;i++)
        for(int j=0;j<ord;j++)
           cin>>a.ar[i][j];
    a=a^n;
    cout<<"Matrix A^"<<n<<"  = "<<endl;
    for(int i=0;i<ord;i++)
    {
        for(int j=0;j<ord;j++)
            cout<<a.ar[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}



1 comment: