In: Computer Science
Write a Java program to
1. read in the size of a square boolean matrix A
2. read in the 0-1 matrix elements
3. read in a positive integer n
4. display A^n
Multiplication.java
package multiplication;
import java.util.Scanner;
public class Multiplication {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int size_A;//size of the array
System.out.println("Enter the size of matrix");
size_A=in.nextInt();
int[][] A=new int[size_A][size_A];
for(int i=0;i<size_A;i++)
{
A[i]=new int[size_A];
}
System.out.println("Enter Matrix");
for(int i=0;i<size_A;i++)
for(int j=0;j<size_A;j++)
{
A[i][j]=in.nextInt();
}
int n;
System.out.println("Enter the N");
n=in.nextInt();
int[][] result=new int[size_A][size_A];
for(int i=0;i<size_A;i++)
for(int j=0;j<size_A;j++)
{
result[i][j]=A[i][j];
}
int[][] temp_result=new int[size_A][size_A];
for(int i=0;i<size_A;i++)
for(int j=0;j<size_A;j++)
{
temp_result[i][j]=0;
}
for(int count=0;count<n-1;count++)
{
for(int i=0;i<size_A;i++)
for(int j=0;j<size_A;j++)
for(int k=0;k<size_A;k++)
temp_result[i][j]+=A[i][k]*result[k][j];
for(int i=0;i<size_A;i++)
for(int j=0;j<size_A;j++)
{
result[i][j]=temp_result[i][j];
}
for(int i=0;i<size_A;i++)
for(int j=0;j<size_A;j++)
{
temp_result[i][j]=0;
}
}
System.out.println("A^n");
for(int i=0;i<size_A;i++)
{
for(int j=0;j<size_A;j++)
{
System.out.print(result[i][j]+"\t");
}
System.out.println();
}
}
}
CODE
SCREENSHOTS:
OUTPUT:
Enter the size of matrix
4
Enter Matrix
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1
Enter the N
6
A^n
32 0 0 32
0 32 32 0
0 32 32 0
32 0 0 32