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
import java.util.*;
class ab
{
char a[][];
Scanner sc=new Scanner(System.in);
int i,j,n;
char ch1,ch2,ch3;
void display()
{
while(true)
{
System.out.print("\nEnter Value of 'N': ");
n=sc.nextInt();
if(n>3 && n<10)
break;
}
a=new char[n][n];
System.out.print("\nEnter 1st Character: ");
ch1=sc.next().charAt(0);
System.out.print("\nEnter 2nd Character: ");
ch2=sc.next().charAt(0);
System.out.print("\nEnter 3rd Character: ");
ch3=sc.next().charAt(0);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i>0 && i<n-1 && j>0 && j<n-1)
a[i][j]=ch3;
else if((i+j)%3==0)
a[i][j]=ch1;
else
a[i][j]=ch2;
}
}
System.out.println("\nMatrix as follows ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
ab obj=new ab();
obj.display();
}
}
class ab
{
char a[][];
Scanner sc=new Scanner(System.in);
int i,j,n;
char ch1,ch2,ch3;
void display()
{
while(true)
{
System.out.print("\nEnter Value of 'N': ");
n=sc.nextInt();
if(n>3 && n<10)
break;
}
a=new char[n][n];
System.out.print("\nEnter 1st Character: ");
ch1=sc.next().charAt(0);
System.out.print("\nEnter 2nd Character: ");
ch2=sc.next().charAt(0);
System.out.print("\nEnter 3rd Character: ");
ch3=sc.next().charAt(0);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i>0 && i<n-1 && j>0 && j<n-1)
a[i][j]=ch3;
else if((i+j)%3==0)
a[i][j]=ch1;
else
a[i][j]=ch2;
}
}
System.out.println("\nMatrix as follows ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
ab obj=new ab();
obj.display();
}
}
No comments:
Post a Comment