harvestfarmfresh.com
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 = 15
OUTPUT: SIZE OUT OF RANGE
import java.util.*;
class matRIX
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no.of rows M of a square matrix:");
int m=sc.nextInt();
char mat[][] = new char[m][m];
System.out.println("Enter corner elements - 1st character:");
char ch1=sc.next().charAt(0);
System.out.println("Enter boundary except corner elements - 2ndcharacter:");
char ch2=sc.next().charAt(0);
System.out.println("Enter non boundary - 3rdcharacter:");
char ch3=sc.next().charAt(0);
for(int i=0; i<m; i++)
{
for(int j=0; j<m;j++)
{
//fill corners with char 1
if( (i==0||i==m-1) && (j==0 || j==m-1))
mat[i][j]=ch1;
//fill non-corner boundary elememts with char 2
else if(i==0 || j==0 || i==m-1 || j==m-1)
mat[i][j]=ch2;
//fill rest with char 3
else
mat[i][j]=ch3;
}
}
//print the array
System.out.println("");
for(int i=0; i<m; i++)
{
for(int j=0; j<m; j++)
{
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
}
}
OUTPUT:
Enter no.of rows M of a square matrix:
5
Enter corner elements – 1st character:
@
Enter boundary except corner elements – 2ndcharacter:
?
Enter non boundary – 3rdcharacter:
#
@ ? ? ? @
? # # # ?
? # # # ?
? # # # ?
@ ? ? ? @