Code:
// Adjacency Matrix
#include <iostream>
using namespace std;
void matin ( int G[][5], int P[][5], int r, int c ){
int i,j;
cout << "Enter an edge as 1 and no edge as 0 " << endl
<< "Please enter matrix by row. " << endl;
for ( i=0; i< r; i++ ){
for ( j=0; j<c; j++ ){
cin >> G[i][j];
G[i][j] = P[i][j] ;
};
};
}
void matout (int P[][5], int r, int c){
cout << endl;
int i,j;
for ( i=0; i<r; i++ ){
for ( j=0; j<c; j++ ){
cout << P[i][j] << " ";
};
cout << endl;
};
}
void matmult ( int A[][5], int P[][5], int G[][5], int r, int c, int n){
int i,j,k;
for ( k=0; k<r; k++ ){
for( i=0; i<r; i++ ){
int sum =0;
for ( j=0; j<n; j++ ){
sum = sum + P[k][j]* A[j][i] ;
G[k][i] = sum;
};
};
};matout (G,r,c);
}
int matpower ( int A[][5], int P[][5],int r, int c, int n ){
int G[5][5];
if ( n == 0 ){ //base case
cout << "Matrix to the 0 power has ended program " << endl;
return 1;
}
else if ( n > 0,--n ){
matmult( A,P,G,r,c, n );
matpower ( A,G,r,c,n );//p to g
};
return 1;
}
int main (){
int r, c;
cout << "This matrix program will handle any matrix up to 20 rows and 20 columns" << endl
<< "Please enter size of matrix rows and columns " << endl;
cin >> r >> c;
int P[5][5];
int A[5][5];
if (r!= 0 && c!= 0){
matin (A,P, r, c);
cout << endl;
matout(P, r,c);
int n;
cout << "Please enter the power multiple for matrix. " << endl
<< "(note: every power up to the one entered will be printed) ";
cin >> n;
cout << endl<< "Matrix from power of 1 through " << n << " power are:"
<< endl;
matout (P, r, c);
matpower(P, A, r, c, n);
}
return 0;
}
/*
Matrix from power of 1 through 3 power are:
0 1 0 0 1
0 0 1 0 0
0 1 0 0 1
0 0 1 0 0
1 0 0 1 0
1 0 1 1 0
0 1 0 0 1
1 0 1 1 0
0 1 0 0 1
0 1 1 0 1
0 2 1 0 2
1 0 1 1 0
0 2 1 0 2
1 0 1 1 0
1 1 1 1 1
Press any key to continue
*/