Programming Examples
Java program to declare a square matrix and fill the data based on given criteria
Write a program to declare a square matrix M [ ] [ ] of order ‘N’ where ‘N’ must be greater than 3 and less than 10. Allow the user to accept three different characters from the keyboard and fill the array according to the instruction given below:
(i) Fill the four corners of the square matrix by character 1.
(ii) Fill the boundary elements of the matrix (except the four corners) by character 2.
(iii) Fill the non-boundary elements of the matrix by character 3.
Test your program with the following data and some random data:
Example 1:
INPUT: N = 4
FIRST CHARACTER: @
SECOND CHARACTER: ?
THIRD CHARACTER: #
OUTPUT:
@ ? ? @
? # # ?
? # # ?
@ ? ? @
Example 2:
INPUT: N = 5
FIRST CHARACTER: A
SECOND CHARACTER: C
THIRD CHARACTER: X
OUTPUT:
A C C C A
C X X X C
C X X X C
C X X X C
A C C C A
Example 3:
INPUT: N = 12
OUTPUT: SIZE OUT OF RANGE
Solution
import java.util.*;
class SquareMatrix
{
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
int n;
char M[][]=new char[10][10];
System.out.println("Enter the value of n : ");
n=sc.nextInt();
sc.nextLine();
if(n<3 || n>10)
{
System.out.println("Invalid Input");
System.exit(0);
}
System.out.println("Enter the Charcter 1 : ");
char ch1=sc.next().charAt(0);
System.out.println("Enter the Charcter 2 : ");
char ch2=sc.next().charAt(0);
System.out.println("Enter the Charcter 3 : ");
char ch3=sc.next().charAt(0);
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
if((a==0||a==n-1)&&(b==0||b==n-1))
{
M[a][b]=ch1;
}
else if(a==0||a==n-1)
{
M[a][b]=ch2;
}
else
{
M[a][b]=ch3;
}
}
}
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
System.out.print(M[a][b]+" ");
}
System.out.println();
}
}
}
Output
Enter the value of n :Â
5
Enter the Charcter 1 :Â
@
Enter the Charcter 2 :Â
#
Enter the Charcter 3 :Â
%
@ # # # @Â
% % % % %Â
% % % % %Â
% % % % %Â
@ # # # @Â