Given a square matrix M[][] of order 'n'. The maximum value possible for 'n' is 10. Accept three different characters from the keyboard and fill the array according to the output shown in the examples. If the value of n exceeds 10 then an appropriate message should be displayed. Input: First Character '' Second Character '?' Third Character '#' Output: # _ # ? # # ? ? # # ? # _ * #
import java.util.*;
public class MatPattern {
char[] ch = new char[3];
int n;
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Size :");
n = sc.nextInt();
if (n < 1 || n > 10) {
System.out.println("Size out of range");
System.exit(-1);
}
for (int x = 0; x < 3; x++) {
System.out.print("Character " + (x + 1) + " :");
ch[x] = sc.next().charAt(0);
}
sc.close();
}
void pattern() {
int size = n;
n--;
boolean[] con = new boolean[3]; // condition to print
System.out.println();
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
int r_x = n - x; // reverse index of x
con[0] = (x > y && r_x > y) || (x < y && r_x < y);
con[1] = (x < y && r_x > y) || (x > y && r_x < y);
con[2] = y == x || y == r_x;
for (int i = 0; i < 3; i++)
if (con[i])
System.out.print(ch[i] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
MatPattern a = new MatPattern();
a.input();
a.pattern();
}
}
Name | Type | Uses |
---|---|---|
global | ||
ch | char[] | the 3 characters on which the pattern will be based |
n | int | the dimension of the 2D Array(sqaure) to be printed |
void input() | ||
sc | Scanner | object to take user input |
void pattern() | ||
size | int | to store the size of the sqaure matrix |
con | int[] | condition if the 3 characters are to be printed |
x, y | int | counter variables to iterate over the matrix |
i | int | counter variable to print the 3 charcaters |
void main() | ||
a | MatPattern | object to call its methods |