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 Multiplying that matrix to the nth power. Like A^2 = matrix A * matrix A. Elements ONLY can be 0 or 1.
Answer:-
Hello, I have written the required program in JAVA. Please find the code below.
JAVA CODE:-
import java.util.Scanner;
class Solution
{
public static void main(String [] args)
{
Scanner in = new
Scanner(System.in);
/* Taking the size of square matrix
in input from user*/
System.out.println("Enter the size
of Square Matrix");
int size=in.nextInt();
int [][] A =new
int[size][size];
int [][] temp =new
int[size][size];
int [][] ans= new
int[size][size];
/*Taking the elements of square
matrix in input from user*/
System.out.println("Enter the elements of Matrix");
for(int i=0;i<size;i++)
{
for(int
j=0;j<size;j++)
{
System.out.print("Enter A["+i+"]["+j+"]");
A[i][j]=in.nextInt();
/* Checking the validity of given input*/
if(A[i][j]!=0&&A[i][j]!=1)
{
System.out.println("Invalid
element, only 1 and 0 are allowed. Please re-enter it");
j--;
}
}
}
for(int i=0;i<size;i++)
{
for(int
j=0;j<size;j++)
{
temp[i][j]=A[i][j];
}
}
/* Taking the value of n as input
from user*/
System.out.println("Enter the value of n");
int n = in.nextInt();
/* Logic for calculating A^n*/
for(int count =1;count<n;count++)
{
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
ans[i][j]=0;
for(int k=0;k<size;k++)
{
ans[i][j]+=temp[i][k]*A[k][j];
}
}
}
for(int i=0;i<size;i++)
{
for(int
j=0;j<size;j++)
{
temp[i][j]=ans[i][j];
}
}
}
/* Printing the required matrix A^n*/
System.out.println("The required Matrix A^"+n+" is as
below");
for(int i=0;i<size;i++)
{
for(int
j=0;j<size;j++)
{
System.out.print(ans[i][j]+" ");
}
System.out.print("\n");
}
}
}
Screenshots of the code:-
Please to the screenshots of the code for properly understanding the indentation of the code.
Screenshot 1:-
Screenshot 2:-
Screenshot 3:-
OUTPUT:-
In this java program, we have also handled the invalid input. If the user enters an invalid element (other than 0 or 1) for the matrix, it will be handled as shown in the below output.
I hope it would help.
Thanks!