A class Palindrome contains a 2-dimensional integer array of order m × n where the maximum values for both ‘m’ and ‘n’ is 5. Design the class Palindrome to fill the matrix with first (m × n) palindrome numbers starting from 11.
The details of the members of the class are given below:
Class name: Palindrome
Data members/instance variables:
matrix[][]: stores the array elements.
m: integer to store the number of rows.
n: integer to store the number of columns.
p: to store the first palindrome number as 11.
Methods:
Palindrome(int r, int c): parameterized constructor to initialize the data members m=r,n=c and p=11.
void fill(): fills the matrix with first (m × n) palindrome numbers starting from 11.
void display(): displays the matrix after filling it with palindrome numbers.
Include main() method to create an object of the class and call the methods accordingly to enable the task.
import java.io.*;
class Palindrome{
int matrix[][];
int m;
int n;
int p;
public Palindrome(int r, int c){
m = r;
if(m > 5)
m = 5;
n = c;
if(n > 5)
n = 5;
p = 11;
matrix = new int[m][n];
}
public void fill(){
for(int i = 0; i < m; i++){
for(int j = 0; j < n;){
int rev = 0;
for(int k = p; k != 0; k /= 10)
rev = rev * 10 + k % 10;
if(p == rev){
matrix[i][j] = p;
j++;
}
p++;
}
}
}
public void display(){
System.out.println("Resultant Matrix:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Number of rows: ");
int rows = Integer.parseInt(br.readLine());
System.out.print("Number of columns: ");
int columns = Integer.parseInt(br.readLine());
Palindrome obj = new Palindrome(rows, columns);
obj.fill();
obj.display();
}
}
2 replies on “Fill Matrix with Palindrome Numbers in Java”
Write a program in Java to input a word and print its anagrams. Anagrams are the words that are made up of all the characters present in the original word by rearranging the characters.
For example:
INPUT:
TOP
OUTPUT:
TOP, TPO, OTP, OPT, PTO, POT
Sir,how to do this program without using recursive function??
Visit this link for the solution of the above problem. It is Question 9.