Q1.
Write a program to create a matrix A[][] of size M*N and rotate it 270
degrees anti clock wise.
Algorithm
Step 1:Start the algorithm.
Step 2:Input the size of the matrix by the user.
Step 3:Store the input number of rows and columns in variables 'M' and 'N'
respectively.
Step 4:Check if the size is valid or not.
Step 5:If valid, create a matrix of size M*N.
Step 6:Input elements of the matrix by the user.
Step 7:Display the matrix
Step 8:Rotate the matrix by 270 degrees anti clock wise with the help of the
variable 'help'.
Step 9:Display the resulted matrix.
Step 10:End the Algorithm.
Program
import java.util.Scanner;
class TwoSeventyDegrees
public static void main(String args[])
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows greater than 2 and less than
10");
int M=sc.nextInt();
System.out.println("Enter the number of columns greater than 2 and less than
10");
int N=sc.nextInt();
//Checking if the input size of matrix is valid or not
if(M<3 || M>10 || N<3 || N>10)
System.out.println("Input size of the matrix is Invalid");
else
//Creating the matrix
int A[][]=new int[M][N];
System.out.println("Enter the elements of the array");
//Entering array elements
for(int i=0;i<M;i++)
for(int j=0;j<N;j++)
System.out.println("Enter element at index: ("+i+" , "+j+")" );
A[i][j]=sc.nextInt();
// (a) Displaying the elements of the matrix
System.out.println("ORIGINAL MATRIX");
for(int i=0;i<M;i++)
for(int j=0;j<N;j++)
{
System.out.print(A[i][j]+"\t");
System.out.println();
// (b) Rotating the matrix by 270 degrees anti clock wise
int ar[][]=new int [N][M];
int help=M-1;
for(int i=0;i<M;i++)
for(int j=0;j<N;j++)
ar[j][i]=A[help][j];
help--;
//Displaying the Resultant matrix
System.out.println();
System.out.println("ROTATED MATRIX(270 DEGREE ANTI CLOCK
WISE)");
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
System.out.print(ar[i][j]+"\t");
System.out.println();
}
VARIABLE DESCRIPTION
VARIABLE NAME DATA TYPE PURPOSE
M int To store number of rows.
N int To store number of Columns.
help int To help with 270 degree anti clock wise rotation.
INPUT/OUTPUT
INPUT: M=3
N=4
ENTER ELEMENTS: 8,7,9,3,-2,0,4,5,1,3,6,-4
OUTPUT:
ORIGINAL MATRIX
8 7 9 3
-2 0 4 5
1 3 6 -4
ROTATED MATRIX(270 DEGREE ANTI CLOCK WISE)
1 -2 8
3 0 7
6 4 9
-4 5 3
Q2. Write a program to check if the string is a Snowball string or not.
Algorithm
Step 1:Start the algorithm.
Step 2:Input the string and calculate its length.
Step 3:Store its last character in a variable ‘ch’ and check if it ends with ‘.’,’?’ or
‘!’.
Step 4:If valid, store remove the last character.
Step 5:Take out every word from the string and store it in the array ss[].
Step 6:Check if the words of the string are in ascending order.
Step 7:If, all are in ascending order, print Snowball String.
Step 8:Else Print Not Snowball String.
Step 9: End the Algorithm.
Program
import java.util.*;
class Snowball
public static void main(String args[])
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Sentence");
String str=sc.nextLine();
//Storing length of string
int ll=str.length();
//Taking out the last character of the string top chexk if it ends with '.','!' or '?'.
char ch=str.charAt(ll-1);
if(ch!= '.' && ch!= '?' && ch!= '!')
{
System.out.println("Invalid Input");
else
//Removing the last character
str=str.substring(0,str.length()-1);
StringTokenizer s=new StringTokenizer(str," ");
int l=s.countTokens();
boolean f=true;
//Creating an array to store all the words of the string
String ss[]=new String [l];
for(int i=0;i<l;i++)
ss[i]=s.nextToken();
//Checking for Snowball String
for(int i=0; i<l-1;i++)
if(ss[i+1].length() != ((ss[i].length())+1))
{
f=false;
break;
if(f)
System.out.println("Snowball String");
else
System.out.println("Not Snowball String");
}
VARIABLE DESCRIPTION
VARIABLE NAME DATA TYPE PURPOSE
str String To store input string.
ll int To store the length of the string.
ch char To store the last character of the string.
l int To store the number of words in the string.
f boolean Flag to check for Snowball String.
ss[] String To store the words.
INPUT/OUTPUT
INPUT: str = I am the King.
OUTPUT: Snowball String
INPUT: str = I am the King
OUTPUT: Invalid Output
INPUT: str = I am King
OUTPUT: Not Snowball String
Q3. A Vampire number is a composite natural number with an even number
of digits that can be factored into two natural numbers each with half as many
digits as the original number and not both with trailing zeros, where the two
factors contain precisely all the digits of the original number, in any order of
counting multiplicity.
Example: 1260 = 21*60 (where 21 and 60 contain precisely all the digits of the
number)
Thus, 1260 is a Vampire number.
Accept two positive integers m and n, where m is less than n and the values of
both ‘m’ and ’n’ must be greater than or equal to 1000 and less than or equal
to 9999 as user input. Display all Vampire numbers that are in the range
between m and n (both inclusive) and output them along with the frequency,
in the format specified below:
Algorithm :
Step 1: Start the algorithm
Step 2 : In the main method, input the value of m and n to store the upper and
lower limits of the range given by the user
Step 3 : count and print the total number of vampire numbers in the provided range
Step 4 : Create a Boolean method isVampire that checks whether a number is
vampire number or not
• Convert the given number into a string using String.valueOf function and
store it in a variable numString and store its length.
• Firstly, Check whether the number has even number of digits and then
proceed further.
• Extract all the factors of the given number using for-loop and then store the
original number string and factors-String in two different arrays of char data
type.
• Sort both the arrays in ascending order using sort function
• Compare both the arrays using equals function.
• If both arrays are equal ,return true else false
Step 5 : Create a method sort(char arr[]) that sorts the given array in ascending
order using bubble sort technique .
Step 6 : Create a Boolean method equals(char a1[],char a2[]) that checks for the
equality of the two arrays.
Step 7 : End the algorithm
Program
//VAMPIRE NUMBER USING STRING
import java.util.Scanner;
public class Vampire
public static void main(String args[])
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of M");
int m = sc.nextInt();
System.out.println("Enter the value of N");
int n = sc.nextInt();
if(m>n || m<1000 || n<1000 || m>9999 || n>9999)
System.out.println("INVALID INPUT");
return;
}
int count = 0;
System.out.println("The vampire numbers are : ");
for(int i=m;i<=n;i++)
if(isVampire(i))
count++;
System.out.println(i);
System.out.println("Total Vampire numbers in the given range : "+count);
public static boolean isVampire(int number)
String numString = String.valueOf(number);
int length=numString.length();
if(length%2!=0)
return false;
for(int i= (int)Math.pow(10,length/2-1);i<=(int)Math.pow(10,length/2);i++)
{
int factor1 = i;
int factor2 = number/factor1;
if(factor1*factor2==number)
String factorString = String.valueOf(factor1) + String.valueOf(factor2);
char originalChar[] = new char[length];
for(int x=0;x<length;x++)
originalChar[x]=numString.charAt(x);
char factorsChar[] = new char[factorString.length()];
for(int y=0;y<length;y++)
factorsChar[y]=factorString.charAt(y);
sort(originalChar);
sort(factorsChar);
if(equals(originalChar,factorsChar))
return true;
return false;
public static void sort(char arr[])
for(int x=0;x<arr.length;x++)
{
for(int y=0;y<arr.length-1-x;y++)
if(arr[y]>arr[y+1])
char temp= arr[y];
arr[y]=arr[y+1];
arr[y+1]=temp;
public static boolean equals(char a1[], char a2[])
if(a1.length!=a2.length)
return false;
for(int i=0;i<a1.length;i++)
if(a1[i] != a2[i])
return false;
return true;
}
VARIABLE DESCRIPTION
Variable Name Data Type Description
m,n Int To store the upper and the
lower limit of the given
range
count Int To count the number of
Vampire numbers present
in the given range
numString String To store the Vampire
number in String data
type
length Int To store the length of
numString
i,x,y Int For-loop variables
factor1,factor2 Int To store the two factors of
the given number
factorString String To store the concated
factors in String data type
originalChar[] char Array to store the
characters of the original
String
factorsChar[] char Array to store the
characters of the concated
String
temp char Temporary variable
INPUT/OUTPUT:
Input :
Enter the value of M
1100
Enter the value of N
1800
Output :
The vampire numbers are :
1260
1395
1435
1530
Total Vampire numbers in the given range : 4
Q4 . Check whether the matrix is doubly markov matrix
Algorithm
Step 1:Start of Algorithm.
Step 2:Input the number of the square matrix.
Step 3:Check whether the input number is in range of not.(N>3 && N<9)
Step 4:Initialize a variable isNegative to check whether there is no negative
number in the matrix.
Step 5:Initialize a variable isMarkov to check whether the matrix is doubly markov
or not.
Step 6:Intput the elements of the Matrix.
Step 7:Check whether the row elements sum upto 1.0.
Step 8:Check whether the column elements sum upto 1.0.
Step 9:Print the matrix and check if isMarkov false or true.
Step 10:If isMarkov is true print that the above matrix is doubly markov matrix.
Step 11:End the Alogorithm.
Program
import java.util.*;
class Doubly_Markov
public static void main(String args[])
Scanner sc=new Scanner(System.in);
System.out.println("N = ");
int n=Integer.parseInt(sc.nextLine());
if(n<3&&n>9)
System.out.println("Size is out of range");
return;
double m[][]=new double[n][n];
boolean isNegative=false;
boolean isMarkov=true;
System.out.println("Enter elements in the matrix:");
for(int i=0;i<n;i++)
{
double row=0.0;
for(int j=0;j<n;j++)
m[i][j]=Double.parseDouble(sc.nextLine());
if(m[i][j]<0)
isNegative=true;
row +=m[i][j];
//Checking if row elements sum=1.0
if(row != 1.0)
isMarkov=false;
if(isNegative)
System.out.println("Negative numbers enetered. Invalid entry ");
return;
//Checking column if the sum is 1.0 or not
for(int j=0;j<n;j++)
double column=0.0;
for(int i=0;i<n;i++)
column += m[i][j];
if(column !=1.0)
isMarkov=false;
break;
System.out.println("Formed matrix : ");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
System.out.print(m[i][j] + "\t");
System.out.println();
if(isMarkov)
System.out.println("It is a doubly markov matrix");
}
else
System.out.println("It is not a doubly markov matrix");
Variable description
Variables Data type Use
n int To store the number of rows as well as
column
isNegative boolean To check if there is no negative element
isMarkov boolean To check if the matrix is doubly markov
matrix or not
m int To store the elements
row double To check if the sum of each row is 1 or not
column double To check if the sum of each column is 1 or
not
i int Loop variable
j int Loop variable
Input/Output:
N=3
Enter elements in the matrix:
0.5
0.25
0.25
0.25
0.75
0.0
0.25
0.75
Formed matrix:
0.5 0.25 0.25
0.25 0.75 0.0
0.25 0.0 0.75
It is a doubly markov matrix
Q5. Write a program to accept a sentence which may be either terminated by
‘.’ Or ‘?’ or ‘!’ only. The word may be separated by a single blank and are in
upper case. Perform the following tasks :
i) Count the number of vowels and consonants present in each word.
ii) Generate the output of the frequency in the form of a bar graph,
where V denotes vowels and C consonants.
Algorithm :
1) Start the algorithm.
2) Input a sentence from the user, trim it.
3) Using char last, check whether sentence ends in a . ? or ! .
4) If not then display Invalid input.
5) If the condition is met, convert the sentence to Uppercase.
6) Create a StringTokenizer object with delimiter as . ? ! or whitespace. Extract
each word using nextToken() method.
7) Now count the number of consonants and vowels in the given word.
8) Input the ‘con’ string with C for each consonant and ‘vow’ string with V for
each vowel.
9) Display con and vow next to each word until the sentence ends.
10)End the algorithm.
Program
import java.util.Scanner;
import java.util.StringTokenizer;
public class Vowel_Con
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence ending in . ? or !");
String s = sc.nextLine().trim();
char last = s.charAt(s.length()-1);
if (last != '.' &&last != '?' &&last != '!')
System.out.println("Invalid input");
else
s = s.toUpperCase().trim();
StringTokenizer st = new StringTokenizer(s, ".?! ");
int len = st.countTokens();
for (int i=1; i<=len; i++)
String word = st.nextToken();
int w = word.length();
int c = 0, v = 0;
for (int j=0; j<w; j++)
char x = word.charAt(j);
if (x == 'A' || x == 'E' || x == 'I' || x == 'O' || x ==
'U')
v++;
else
c++;
System.out.print(word + "\t");
String con = "", vow = "";
for (int a=0; a<c; a++)
{
con += "C";
for (int b=0; b<v; b++)
vow += "V";
System.out.print(con + "\n");
System.out.println("\t" + vow);
Variable Description :
Name of variable Type Purpose
S String To store the sentence
entered by the user
Last char To check whether last
character if .?or !
St StringTokenizer object For extracting the words
of the sentence
Len int Total number of words
in the sentence
W int Length of the extracted
word
C int Number of consonants
in a particular word
V int Number of vowels in a
particular word
Con String To store the character C
for each consonant in a
word
Vow String To store the character V
for each vowel in the
word
Input/Output
Sample Input :
Enter a sentence ending in . ? or !
its been long since i met you !
Sample Output :
ITS CC
BEEN CC
VV
LONG CCC
SINCE CCC
VV
MET CC
V
YOU C
VV
Q6. Write a program in java to enter date in dd/mm/yyyy format and day of
the week on which a project was given. If a college allots 90 days (including
the project giving day) to complete the work, then calculate the date on which
the project is to be submitted along with the day name. if the final submission
day is Sunday then the students get one extra day and submit the project on
the next day that is Monday.
Also check the validity of the date entered and display your output in the
format as given below :
Enter project date in (dd/mm/yyyy) format (end in full stop): 20/2/2024
Enter the day of the week on which the project was given: TUESDAY
PROJECT SUBMISSION DATE: 19/5/2024
DAY OF THE WEEK: SUNDAY
Project to be submitted on 20/5/2024 MONDAY
Algorithm :
1) Start the algorithm.
2) First the user enters a date in dd/mm/yyyy format and we check for the
validity of the date.
3) If the date is valid then perform the following steps.
4) Create a loop for 90 days and increment the day by on each time.
5) Now if the date becomes the last date of the month we are required to
increment the month by 1. We will keep track in which month are we and
accordingly check for the last date.
6) If the month is the last month of the year that is December; then we need to
set the month to ‘1’ i.e. January and we need to increment the year by one.
7) While incrementing the date keep incrementing the weekday also.
8) If the year is a leap year then Feb will have 29 days instead of 28.
9) Finally if the day is a Sunday increment the date by one.
10) Print the final date.
11) End the algorithm.
Program
import java.util.Scanner;
public class ProjectSubmissionDate
public static void main(String[] args)
Scanner scanner = new Scanner(System.in);
System.out.print("Enter project date in (dd/mm/yyyy) format");
String projectDateStr = scanner.nextLine();
String[] parts = projectDateStr.split("/");
if (parts.length != 3)
System.out.println("Invalid date format. Please enter in
dd/mm/yyyy format.");
return;
int day = Integer.parseInt(parts[0]) - 1;
int month = Integer.parseInt(parts[1]);
int year = Integer.parseInt(parts[2]);
if (!isValidDate(day, month, year))
System.out.println("Invalid date entered.");
return;
System.out.print("Enter the day of the week on which the project was
given: ");
String dayOfWeek = scanner.nextLine().toUpperCase();
int daysForProject = 90;
int[] daysInMonth = { 31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
while (daysForProject> 0)
int daysInCurrentMonth = daysInMonth[month - 1];
if (day == daysInCurrentMonth)
day = 1;
if (month == 12)
month = 1;
year++;
}
else
month++;
else
day++;
daysForProject--;
String submissionDayOfWeek = getDayOfWeek(dayOfWeek,
daysForProject);
System.out.println("PROJECT SUBMISSION DATE: " + day + "/" +
month + "/" + year);
System.out.println("DAY OF THE WEEK: " +
submissionDayOfWeek);
if (submissionDayOfWeek == "SUNDAY")
System.out.println("Project to be submitted on " + (day + 1) +
"/" + month + "/" + year + " MONDAY");
}
public static boolean isValidDate(int day, int month, int year)
if (year < 1 || month < 1 || month > 12 || day < 1 || day > 31)
return false;
int[] daysInMonth = { 31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
return day <= daysInMonth[month - 1];
public static boolean isLeapYear(int year)
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
public static String getDayOfWeek(String startDay, intdaysToAdd)
String[] daysOfWeek = { "SUNDAY", "MONDAY", "TUESDAY",
"WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };
int startDayIndex = 0;
for (inti = 0; i<daysOfWeek.length; i++)
if (startDay.equals(daysOfWeek[i]))
{
startDayIndex = i - 1;
break;
int finalDayIndex = (startDayIndex + daysToAdd) % 7;
if (finalDayIndex == 0 &&startDayIndex != 0)
finalDayIndex = 7;
return daysOfWeek[finalDayIndex - 1];
Variable Description :
Name of variable Type Purpose
projectDateStr String The date when the
project was given
parts[] String[] Array to store the parts
of the date
Day int To store the day
Month int To store the month
Year int To store the year
dayOfWeek String To input the day on
which the project was
given and calculate
accordingly
daysForProject int Number of days for
project submission = 90
daysInMonth[] int[] Number of days in all
the months of the year
daysInCurrentMonth int Number of days in the
current month
submissionDayOfWeek String The day of the week on
which the project needs
to be submitted
daysInMonth[] int[] Array containing the
number of days in the
month
daysOfWeek[] String[] Array containing the
days of the week
startDayIndex int Starting day counted as
zero
finalDayIndex int The index of the final
day as in array
Input/Output
Sample Input:
Enter project date in (dd/mm/yyyy) format: 27/6/2023
Enter the day of the week on which the project was given: TUESDAY
Sample Output :
PROJECT SUBMISSION DATE: 24/9/2023
DAY OF THE WEEK: SUNDAY
Project to be submitted on 25/9/2023 MONDAY
Q7. Hamming numbers are numbers whose prime factors are 2, 3 or 5 only.
Examples :
9: Prime Factors= 3*3 Hamming number
14: Prime Factors= 2*7 Not Hamming number
Write a program to input an integer and check whether it is Hamming or not.
Print the number along with its factors and whether it is Hamming or not.
Algorithm :
1) Start the algorithm.
2) Input a number from the user to check for hamming number.
3) First create a method to check whether a number is prime or not; A prime
number except 2,3,5 is never Hamming.
4) Create another method to check for Hamming number.
5) In the method use a loop from 2 to n/2 and check the divisibility of the
number with the prime.
6) If the number is prime and divides the number to be checked, then see
whether the divisor is 2,3 or 5.
7) If the divisor is not 2, 3 or 5 then the number is not Hamming as it got
divided by a prime number other than 2,3 or 5; otherwise the number is of-
course, Hamming.
8) In the main method print the message.
9) End the algorithm.
Program
import java.util.Scanner;
import java.util.StringTokenizer;
public class Hamming
static boolean isPrime(int n)
int t = n;
boolean prime = true;
for (int i=2; i<=t/2; i++)
if (t % i == 0)
prime = false;
break;
return prime;
static boolean isHam(int n)
int t = n;
boolean ham = true;
if(isPrime(t) && t != 2 && t != 3 && t != 5)
return false;
for (int i=2; i<=t/2; i++)
if (t % i == 0 &&isPrime(i))
if (i != 2 &&i != 3 &&i != 5)
{
ham = false;
break;
return ham;
public static void main(String[] args)
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check Hamming");
int n = sc.nextInt();
if (isHam(n))
System.out.println(n + " is a Hamming number");
else
System.out.println(n + " is NOT a Hamming number");
}
Variable Description :
Name of variable Type Purpose
N int To store the number
entered by the user
T int To store the copy of the
number n
Prime boolean To check whether
number is prime or not
Ham boolean To check whether
number is hamming or
not
Input/Output
Sample Input :
Enter a number to check Hamming
20
Sample Output:
20 is a Hamming number
Q8. Write a program to create a 2D array of size n*n and fill the numbers in a
circular fashion in anticlockwise with natural numbers from 1 to n2
Algorithm:
1. Start the algorithm.
2. Create the main method and store the size of the square matrix entered
by the user in ‘n’.
3. Create a double dimension array ‘arr[][]’ of size n*n.
4. Declare 3 integer variables as ‘x’, ‘a’ and ‘b’ and initialize them as 1,
0 and n-1 respectively.
5. Start a while loop till a < n.
• Create a for loop where control variable of the loop ‘i’ varies
from ‘a’ to ‘b’ where ‘i’ increases by 1 for every iteration.
Store the value of ‘x’ in arr[i][a] and increment the value of ‘x’
by 1. Close the for loop. Increment the value of ‘a’ by 1.
• Create another for loop where control variable of the loop ‘i’
varies from ‘a’ to ‘b’ where ‘i’ increases by 1 for every
iteration. Store the value of ‘x’ in arr[b][i] and increment the
value of ‘x’ by 1. Close the for loop.
• Create another for loop where control variable of the loop ‘i’
varies from ‘b-1’ to ‘a’ where ‘i’ decreases by 1 for every
iteration. Store the value of ‘x’ in arr[i][b] and increment the
value of ‘x’ by 1. Close the for loop. Decrement the value of
‘b’ by 1.
• Create another for loop where control variable of the loop ‘i’
varies from ‘b’ to ‘a’ where ‘i’ decreases by 1 for every
iteration. Store the value of ‘x’ in arr[a-1][i] and increment the
value of ‘x’ by 1. Close the for loop. Close the while loop
6. Print the array.
7. End the algorithm.
Program
import java.util.Scanner;
public class Question8
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the matrix: ");
int n = sc.nextInt();
int x = 1;
int arr[][] = new int[n][n];
int a = 0;
int b = n - 1;
while (a < n)
{
for (int i = a; i <= b; i++)
{
arr[i][a] = x++;
}
a++;
for (int i = a; i <= b; i++)
{
arr[b][i] = x++;
}
for (int i = b - 1; i >= a - 1; i--)
{
arr[i][b] = x++;
}
b--;
for (int i = b; i >= a; i--)
{
arr[a-1][i] = x++;
}
}
System.out.println("Circular Matrix Anti-Clockwise:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
Variable Description:
Name Data Type Purpose
n int to store the size of the
array
arr[][] int to store the numbers in
circular fashion
x int to store the numbers
which are to be entered
in the array
a, b int to store the position of
the number entered in the
array
i int control variable of outer
loop
j int control variable of inner
loop
Input/Output
Input: n = 5
Output:
Circular Matrix Anti-Clockwise:
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9
Q9. Given a square matrix M of order m. The maximum value possible for m
is 10 and minimum is 3. Accept 3 different characters from the keyboard and
fill the array according to the output shown in the following example:
m=4
First character: *
Second character: ?
Third character: #
Output: # * * #
? # # ?
? # # ?
# * * #
Algorithm:
1. Start the algorithm.
2. Create the main method and store the size of the array entered by the user in
‘m’.
3. If ‘m’ is less than 3 or more than 10, display error message and exit the
program.
4. Create a double dimesion character array ‘arr[][]’ of size m*m.
5. Accept the three characters which are to be filled in the array from the user
and store them in ‘ch1’, ‘ch2’ and ‘ch3’ respectively.
6. Create a nested for loop where control variable of outer loop ‘i’ varies from
0 to m-1 and control variable of inner loop ‘j’ also varies from 0 to m-1.
If i = j or i - j = m - 1, store the value of ‘ch3’ in arr[i][j].
Else if i = 0 or i = m - 1, store the value of ‘ch1’ in arr[i][j].
Else if j = 0 or j = m - 1, store the value of ‘ch2’ in arr[i][j].
Else, store the value of ‘ch3’ in arr[i][j]. Close the nested for loop.
7. Print the filled array.
8. End the algorithm.
Program
import java.util.Scanner;
public class Square
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int m = sc.nextInt();
if(m > 10 || m < 3)
{
System.out.println("***Size out of range***");
System.exit(0);
}
char arr[][] = new char[m][m];
System.out.println("Enter the first character: ");
char ch1 = sc.next().charAt(0);
System.out.println("Enter the second character: ");
char ch2 = sc.next().charAt(0);
System.out.println("Enter the third character: ");
char ch3 = sc.next().charAt(0);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
{
if(i == j || (i + j) == m - 1)
arr[i][j] = ch3;
else if(i == 0 || i == m-1 )
arr[i][j] = ch1;
else if(j == 0 || j == m-1)
arr[i][j] = ch2;
else
arr[i][j] = ch3;
}
}
System.out.println("Filled array: ");
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
Variable Description
Name Data Type Purpose
m int to store the size of the
array
arr[][] char to store the characters
entered by the user
ch1 char to store the first character
entered by the user
ch2 char to store the second
character entered by the
user
ch3 char to store the third
character entered by the
user
i int control variable of outer
loop
j int control variable of inner
loop
Input/Output
Input:
m=5
ch1 = *
ch2 = ?
ch3 = #
Output:
# * * * #
? # # # ?
? # # # ?
? # # # ?
# * * * #