#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
#define N 3
typedef float array(N);
void findmax(float *max, array x)
{
int I;
*max = fabs(x[0]);
for(i=1;i<N;i++)
if(fabs(x[i]) > *max)
*max = fabs(x[i]);
}
int main()
{
float a[N][N],x[N],r[N],maxe,err,errv,aerr,e,s,t;
int i,j,k,itr,maxitr;
cout<<"Enter the matrix rowwise"<<endl;
for(i=0;i<N;i++)
for(j=0j<N;j++)
cin>>a[i][j];
cout<<"Enter the initial approximation";
cout<<" to the eigen vector"<<endl;
for(i=0;i<N;i++)
cin>>x[i];
cout<<"Enter the allowed error,";
cout<<"maximum iterations"<<endl;
cin>>aerr>>maxitr;
cout<<fixed;
cout<<"Itr no."<<setw(11)<<"Eigenvalue";
cout<<setw(19)<<"EigenVector"<<endl;
//Finding the largest eigenvalue in the initial approx, to eigen vector
findmax(&e,x);
//Starting iterations
for(itr=1;itr<=maxitr;itr++)
{
//multiply the matrices
for(i=0;i<N;i++)
{
s=0;
for(k=0;k<N;k++)
s += a[i][k]*x[k];
r[i]=s;
}
findmax(&t,r);
for(i=0;i<N;i++)
r[i] /= t;
maxe=0;
for(i=0;i<N;i++)
{
err=fabs(x[i]-r[I]);
if(err>maxe)
maxe=err;
x[i]=r[I];
}
errv=fabs(t-e);
e=t;
cout<<setw(4)<<itr;
cout<<setw(12)<<setprecision(4)<<e;
for(i=0;i<N;i++)
cout<<setw(9)<<setprecision(3)<<x[I];
cout<<endl;
if((errv <= aerr) && (maxe <= aerr))
{
cout<<"Converges in"<<itr;
cout<<"iterations"<<endl;
cout<<"Largest eigen value=";
cout<<setw(6)<<setprecision(2)<<e<<endl;
cout<<"Eigen Vector:-"<<endl;
for(i=0;i<N;i++)
cout<<"x["<<setw(3)<<i+1<<"]=";
cout<<setw(6)<<setprecision(2)<<x[i]<<endl;
cout<<endl;
return 0;
}
}
cout<<"Solution does not converge,";
cout<<"iterations not sufficient"<<endl;
return 1;
}
