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
The logic is quite simple, first fill all the elements of the matrix by the second charcter.
then overwrite the elements with row position raging from 1 to less than N-1 and coloumn
position ranging from 1 to less than N-1 with the third character.
Finally overwrite the corner elemets with the first charcter.
for(i=0;i<order;i++)
for(j=0;j<order;j++)
mat[i][j]=characters[1]; //filling all the elements with SECOND char
for(i=1;i<order-1;i++) //filling the non-boundary elements with THIRD char
for(j=1;j<order-1;j++)
mat[i][j]=characters[2];
mat[0][0]=mat[0][order-1]=mat[order-1][0]=mat[order-1][order-1]=characters[0]; //
filling the corner elements
import java.util.*;
public class ISC2020Q1 {
public static void main(String[] args) {
int N;
Scanner in = new Scanner(System.in);
do {
System.out.println("Enter the order of the square matrix:");
N = in.nextInt();
if(N>10
|| N <3)
System.out.println("OUT OF RANGE,TRY AGAIN");
}while(N>10
|| N <3);
MatrixPattern obj = new MatrixPattern(N);
obj.inputCharacters();
obj.inputElementsInMatrix();
obj.display();
in.close();
}
}
class MatrixPattern {
public void inputElementsInMatrix() {
int i,j;
for(i=0;i<order;i++)
for(j=0;j<order;j++)
mat[i][j]=characters[1];
for(i=1;i<order-1;i++) //filling the non-boundary elements
for(j=1;j<order-1;j++)
mat[i][j]=characters[2];
mat[0][0]=mat[0][order-1]=mat[order-1][0]=mat[order-1][order-1]=characters[0]; // filling the corner elements
for(i=0;i<3;i++)
System.out.println(disp[i]+" CHARACTER IS:"+characters[i]);
}
public void inputCharacters() {
Scanner in = new Scanner(System.in);
System.out.println("Enter thecharacters");
s=in.nextLine();
characters =s.toCharArray();
in.close();
}
public void display() {
for(int i=0;i<order;i++) {
for(int j=0;j<order;j++)
System.out.print(mat[i][j]+" ");
System.out.println();
}
}
MatrixPattern(int N){
order = N;
mat = new char[order][order];
}
private String s;
private String[] disp = {"FIRST","SECOND","THIRD"};
private char[] characters;
private char[][] mat;
private int order;
}
No comments:
Post a Comment