0% found this document useful (0 votes)
5 views103 pages

Core Java Programs for Class XII A

The document outlines a computer project for the academic session 2025-2026, focusing on core Java programs covering topics such as object passing, arrays, strings, inheritance, and data structures like stacks and queues. It includes detailed descriptions of various classes and their functionalities, along with example code for each topic. The project is authored by Vansh Agarwal, a student in Class XII A, and contains structured content with an index for easy navigation.

Uploaded by

shivamku7659
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views103 pages

Core Java Programs for Class XII A

The document outlines a computer project for the academic session 2025-2026, focusing on core Java programs covering topics such as object passing, arrays, strings, inheritance, and data structures like stacks and queues. It includes detailed descriptions of various classes and their functionalities, along with example code for each topic. The project is authored by Vansh Agarwal, a student in Class XII A, and contains structured content with an index for easy navigation.

Uploaded by

shivamku7659
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

2025 - 2026

COMPUTER
PROJECTTOPIC:
Core Java Programs on -
Object Passing
Arrays (SDA & DDA)
Strings
Inheritance
Stack & Queue

Name - Vansh Agarwal


Class - XII A
Roll No. - 40
Session - 2025-26
CONTENTS
PAGE
INDEX PROGRAMS
NO.

1 OBJECT PASSING 01-18

2 SINGLE DIMENSIONAL ARRAY 19-30

3 DOUBLE DIMENSIONAL ARRAY 31-51

4 STRINGS 52-63

5 INHERITENCE 64-85

6 STACK & QUEUE 86-100


Question 1:
Main Class: op1

Data Members:

x → x-coordinate of point (int) y → y-


coordinate of point (int) dis → distance
between two points (double)

Member Functions:

1. op1() → default constructor

o Initialize x = 0, y = 0, dis = 0.0

2. void getval() →

o Read x and y from user using Scanner

3. void calradius(op1 obj1, op1 obj2) →

o Calculate Euclidean distance between obj1 and obj2


o Print: "DISTANCE BETWEEN POINTS"
o Print: dis

4. void display() →

o Print x
o Print y

import [Link].*;
class op1{
int x,y;
double dis;
op1() {
x=0;y=0;dis=0.0;
}
void getval() {
Scanner in=new Scanner ([Link]);
x=[Link](); y=[Link]();

}
void calradius(op1 obj1,op1 obj2) {
dis=[Link]([Link]((obj1.x-obj2.x),2)+[Link]((obj1.y-
obj2.y),2));
[Link]("DISTANCE BETWEEN POINTS");

[Link](dis);
}
void display() {
[Link](x);
[Link](y);
}
public static void main(String[] args) {
op1 ox=new op1();
[Link]("enter x&y of 1st point");
[Link]();
op1 oy=new op1();
[Link]("enter x&y of 2nd point");
[Link]();
[Link](ox,oy);

}
}

OUTPUT :
Question 2:
Main Class: op2

Data Members:

name → student name (String)


maths → marks in Mathematics (int)
physics → marks in Physics (int)
chemistry → marks in Chemistry (int)

Member Functions:

1. op2(String name, int maths, int physics, int chemistry) → parameterized constructor

o Initialize [Link] = name


o Initialize [Link] = maths
o Initialize [Link] = physics
o Initialize [Link] = chemistry

2. static double calculateAverage(op2 m) → Calculate average of three subjects:

o Return average as double

3. void display() →

o Use calculateAverage(this) to get average

[Link].*;
publicclass op2 {
String name;
intmaths, physics, chemistry;
op2(String name, int maths, int physics, int chemistry) {
[Link] = name;
[Link] = maths;
[Link] = physics;
[Link] = chemistry;

}
static double calculateAverage(op2 m) {
double average = ([Link] + [Link] + [Link]) / 3.0;
return average;
}
void display() {
[Link]("%s Average: %.2f\n", name,
calculateAverage(this));
}
public static void main(String[] args) {
Scanner in=new Scanner([Link]);
[Link]("name of 1st person: ");
String a=[Link]();
[Link]("marks in physics , chemistry and maths: ");
int p=[Link]();
int c=[Link]();
int m=[Link]();
op2 student1 = new op2(a, m,p,c);
[Link]("name of 2nd person: ");
String a1=[Link]();
[Link]("marks in physics , chemistry and maths: ");
int p1=[Link]();
int c1=[Link]();
int m1=[Link]();
op2 student2 = new op2(a1, m1,p1,c1);
[Link]("Student 1 Average: " +
calculateAverage(student1));
[Link]("Student 2 Average: " +
calculateAverage(student2));
[Link]("\nUsing display method:");
[Link]();
[Link]();
}
}

OUTPUT :
Question 3:
Main Class: op3

Data Members:

empId → employee ID (String)


salary → employee salary (double)

Member Functions:

1. op3(String empId, double salary) → parameterized constructor

o Initialize [Link] = empId


o Initialize [Link] = salary

2. public double getSalary() →

o Return salary

3. public String toString() → Return formatted string


4. public static op3 compareSalary(op3 e1, op3 e2) →

o Compare [Link]() and [Link]()


o Return object with higher salary
o If [Link] > [Link] → return e1
o Else → return e2

import [Link].*;
class op3 {
String empId;
double salary;
public op3(String empId, double salary) {
[Link] = empId;
[Link] = salary;
}
public double getSalary() {
return salary;
}
publicString toString() {
return "ID = " + empId + ", Salary = " + salary;
}
publicstatic op3 compareSalary(op3 e1, op3 e2) {
if([Link]() > [Link]()) {
return e1;
}else {
return e2;
}
}
publicstatic void main(String[] args) {
Scanner in=new Scanner([Link]);
[Link]("1st employee name and salary"); String
a=[Link](); intb=[Link](); op3emp1 = new op3(a,b);
[Link]("2nd employee name and salary");
String c=[Link](); intd=[Link](); op3emp2 = new op3(c,
d);
[Link]("op3 1: " + emp1);
[Link]("op3 2: " + emp2);
op3higherPaid = compareSalary(emp1, emp2);
[Link]("op3 with higher salary: " + higherPaid);
}
}
OUTPUT :
Question4 :
Main Class: op4

Data Members:

accountNumber → account ID (String)


balance → current balance (double)

Member Functions:

1. op4(String accountNumber, double balance) → parameterized constructor

o Initialize [Link] = accountNumber


o Initialize [Link] = balance

2. public double getBalance() →

o Return balance

3. public boolean withdraw(double amount) →

o If amount > 0 and amount <= balance:


balance -= amount
Return true

o Else → return false

4. public void deposit(double amount) →

o If amount > 0:
balance += amount

5. public String toString() →

o Return: accountNumber + ": " + balance

6. public static boolean transferFunds(op4 source, op4 destination, double amount) →

o [Link](amount)
o If true→call [Link](amount)
o Returntrue
o Else→return false

import [Link].*;
class op4 {
String accountNumber;
double balance;
op4(String accountNumber, double balance) {
[Link] = accountNumber;
[Link] = balance;
}
public double getBalance() {
return balance;
} public boolean withdraw(double amount)
{ if (amount > 0 && amount <= balance) {

balance -= amount;
return true;
}
return false;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public String toString() {
return accountNumber + ": " + balance;
}
public static boolean transferFunds(op4 source, op4 destination,
double amount) {
if ([Link](amount)) {
[Link](amount);
return true;
}
return false;
}
public static void main(String[] args) {
Scanner in=new Scanner([Link]);
[Link]("name and balance of sender");
String a=[Link]();
int ba=[Link]();
op4 account1 = new op4(a, ba);
[Link]("name and balance of reciever");
String a1=[Link]();
int ba1=[Link]();
op4 account2 = new op4(a1, ba1);
[Link]("Initial Balances:");
[Link]("Account " + account1);
[Link]("Account " + account2);
[Link]("amount to transfer");
double transferAmount = [Link]();
boolean transferSuccess = transferFunds(account1, account2,
transferAmount);
[Link]("Transfer " + transferAmount + " from A123 to
B456: " +
(transferSuccess ? "Successful" : "Failed"));
[Link]("Updated Balances:");
[Link]("Account " + account1);
[Link]("Account " + account2);
}
}
OUTPUT :

Question5 :
Class Name: op5

Data Members:
int m → Marks in Mathematics
int s → Marks in Science (Physics/Chemistry – as per input prompt)
int e → Marks in English (or third subject – as per input)

Member Functions:

1. op5(int m, int s, int e) → Parameterized constructor to initialize the marks of a


student in three subjects.
2. double getPercentage() → Calculates and returns the percentage of the student.
Formula: (m + s + e) / 3.0
3. static double calculateClassAverage(op5[] arr) → Takes an array of op5 student
objects and returns the average percentage of the entire class. Logic:

o Sum the getPercentage() of all students


o Divide by the number of students ([Link])

ALGORITHM : Step 1: Start the program. Step 2: Define class op5 with
integer variables m, s, e. Step 3: Create constructor to set m, s, e using this
keyword. Step 4: Define getPercentage method to return (m + s + e)
divided by 3.0. Step 5: Define static calculateClassAverage method taking
op5 array. Step 6: Initialize sum to 0. Step 7: Loop through each student in
array. Step 8: Add student's getPercentage to sum. Step 9: Return sum
divided by array length. Step 10: In main, create Scanner object. Step 11:
Print input prompt for marks. Step 12: For first student, print label and
read three marks into a, b, c. Step 13: For second student, print label and
read into a1, b1, c1. Step 14: For third student, print label and read into a2,
b2, c2. Step 15: For fourth student, print label and read into a3, b3, c3.
Step 16: Create op5 array with four student objects using read marks.
Step 17: Loop from i=0 to 3.
Step 18: Print student number and their percentage.
Step 19: Call calculateClassAverage on array and print result.
Step 20: End the program.

SOURCE CODE :
import [Link].*;
public class op5 {
int m, s, e;
op5(int m, int s, int e) {
this.m = m;
this.s = s;
this.e = e;
}
double getPercentage() {
return (m + s + e) / 3.0;
}
static double calculateClassAverage(op5[] arr) {
double sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += arr[i].getPercentage();}

return sum / [Link];}


return sum / [Link];
}
public static void main(String[] args) {
Scanner in=new Scanner([Link]);
[Link]("enter marks of phy,chem,maths");
[Link]("for 1st student");
int a=[Link]();int b=[Link](); int c=[Link]();
[Link]("for 2nd student");
int a1=[Link](); int b1=[Link](); int c1=[Link]();
[Link]("for 3rd student");

int a2=[Link](); int b2=[Link](); int c2=[Link]();


[Link]("for 4th student");
int a3=[Link](); int b3=[Link]();int c3=[Link]();
op5[] students = {
new op5(a,b,c),
new op5(a1,b1,c1),
new op5(a2,b2,c2),
new op5(a3,b3,c3) };

for(int i = 0; i < [Link]; i++) {


[Link]("Student " + (i+1) + " Percentage: " +
students[i].getPercentage());}
[Link]("Class Average: " + calculateClassAverage(students));}}

VARIABLE DESCRIPTION
[Link]. DATA TYPE VARIABLE DESCRIPTION
1. Int m Store physics marks
2. Int s Store chemistry marks
3. Int e Store maths marks
4. Double sum To store sum
5. Int i For loop
6. Int a,a1,a2 To store phy marks
7. Int b,b1,b2 To store chem marks
8. Int c,c1,c2 To store maths marks
OUTPUT :
Question 1: Write a Java program to accept n words in a Single Dimension
Array, and for each word, display the frequency of each uppercase letter in
it.

import [Link].*;
class sda1 {
public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Enter size of array");
int n = [Link]();
[Link]();
String[] a = new String[n];
[Link]("Enter words");
for (int i = 0; i < n; i++) {

a[i] = [Link]().toUpperCase().trim();
}
for (int i = 0; i < [Link]; i++) {
String word = a[i];
if ([Link]())
continue;
[Link]("Word: " + word);
int[] freq = new int[26];
for (int j = 0; j < [Link](); j++) {

char c = [Link](j);
if (c >= 'A' && c <= 'Z') freq[c - 'A']++;
}
[Link]("Letter\tFrequency");
for (int p = 0; p < 26; p++) {
if (freq[p] > 0)
[Link]((char)(p + 'A') + "\t" + freq[p]);
}
[Link]();} }}
OUTPUT :
Question2:Givena1Darray of n integers, rearrange it so that all even
numberscomebeforeallodd numbers. Preserve the relative order of even
and oddelements.
import [Link].*;

class sda2 {

publicstaticvoidmain(String[] args) {

Scannerin=newScanner([Link]);
[Link]("Enter size of array");

int n = [Link]();
int[] a = new int[n];

[Link]("Enter element of array");


for(inti=0;i<n;i++)

a[i] = [Link]();

int[]result=newint[n];

int idx = 0;

for(inti=0;i<n;i++) {

if(a[i]%2==0)result[idx++] = a[i];

for(inti=0;i<n;i++) {

if(a[i]%2!=0)result[idx++] = a[i];

for(inti=0;i<n;i++) [Link](result[i] + " ");


}

OUTPUT :
Question 3: Write a Java program to input an array of integers, sort it
using bubble sort, and search for a target element using binary search.
import [Link].*;
class sda3 {
public static void main(String[] args) {
Scanner in=new Scanner([Link]);
[Link]("Enter size of array");
int n=[Link]();
int a[]=new int[n];
[Link]("Enter element of array");
for(int i=0;i<n;i++)
{

a[i]=[Link]();
}
[Link]("Enter element of search");
int target = [Link]();
for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {


if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
int result = binarySearch(a, target);
[Link](result == -1 ? "Element not found" : "Element found at
index: " + result);
}
public static int binarySearch(int[] arr, int target) {
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;

}
return -1; }
}
OUTPUT :
Question 4 : WriteaJavaprogram to input an array of integers and
printthefrequencyofeachelement using a visited array.
import [Link].*;
class sda4
{

publicstaticvoidmain(String[] args) {
Scannerin=newScanner([Link]);
[Link]("Entersize of array");
int n=[Link]();
int a[]=new int[n];
[Link]("Enterelement of array");
for(int i=0;i<n;i++)
{

a[i]=[Link]();
}
boolean[]visited=newboolean[n];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int count = 1;
for(intj=i+1;j<n;j++) {
if (a[i] == a[j]) {
visited[j] = true;
count++;
}
}
[Link]("Element " + a[i] + " occurs " + count + "
times");
}
}
}
}
OUTPUT :
Question 5 : Write a Java program to input array size, elements, and a
target sum; print all pairs of elements that sum to the target.
ALGORITHM:

Step 1: Start program.


Step 2: Create Scanner object.

Step 3: Read array size n.


Step 4: Create array a[] of size n.

Step 5: Read n elements into array.


Step 6: Read target sum.

Step 7: Print header for pairs.


Step 8: For i from 0 to n-2.

Step 9: For j from i+1 to n-1.


Step 10: If a[i] + a[j] equals target.

Step 11: Print pair (a[i], a[j]).


Step 12: End program.

SOURCE CODE :

import [Link].*;

class sda5

public static void main(String[] args) {

Scanner in=new Scanner([Link]);

[Link]("Enter size of array");

int n=[Link]();

int a[]=new int[n];


[Link]("Enter element of array");

for(int i=0;i<n;i++)

a[i]=[Link]();

[Link]("target to achieve");

int target = [Link]();

[Link]("Pairs with sum " + target + ":");

int nn = [Link];

for (int i = 0; i < nn - 1; i++) {

for (int j = i + 1; j < n; j++) {

if (a[i] + a[j] == target) {

[Link]("Pair: (" + a[i] + ", " + a[j] + ")");

VARIABLE DESCRIPTION
[Link]. DATA TYPE VARIABLE DESCRIPTION
1. Int n To store array size
2. Int a[] To create an array of size n
3. Int target To store target value
4. Int nn To store array length
5. Int i,j For loop
OUTPUT :
Question1 : Write a Java program to input size of square matrix, read
elements, print original matrix, transpose it, and print transposed matrix.

import [Link].*;
class dda1
{

public static void main()


{
Scanner in=new Scanner([Link]);
[Link]("enter size nxn");
int n=[Link]();
int a[][]=new int[n][n];
[Link]("enter element in array");
for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {


a[i][j]=[Link]();
}
}
[Link]("ORIGINAL MATRIX");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
for(inti=0; i < [Link]; i++) {
for(intj= i; j < a[0].length; j++) {
inttemp = a[i][j];
a[i][j]= a[j][i];
a[j][i]= temp;
}
}
[Link]("Arranged MATRIX");
for(inti=0; i < n; i++) {
for(intj= 0; j < n; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
}
}
OUTPUT :
QUESTION 2 :Write a program to declare a square matrix A[][] of order
(M × M) where 'M' must be greater than 3 and less than 10. Allow the
user to input positive integers into this matrix. Perform the following
tasks on the matrix:
[Link] the non-boundary elements in ascending order using any standard
sorting technique and rearrange them in the matrix.
[Link] the sum of both the diagonals.
[Link] the original matrix, rearranged matrix and only the diagonal
elements of the rearranged matrix with their sum.
import [Link].*;
public class dda2
{

public static void main(String args[]) {


Scanner in = new Scanner([Link]);
[Link]("Enter size of the matrix ");
int n = [Link]();
if (n<= 3|| n>= 10) {

[Link]("The matrix size is out of range");


}
else{
int a[][] = new int[n][n];
[Link]("Enter elements in the matrix: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] < 0) {
[Link]("INVALID INPUT");
}
else
{
a[i][j]=[Link]();
}
}
}
[Link]("ORIGINAL MATRIX");
for(inti=0;i<n; i++) {
for(intj=0;j< n; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
int sum = 0;
[Link]("DIAGONAL ELEMENTS");
for(inti=0;i<n; i++) {

for(intj=0;j< n; j++) {
if(i==j||i+ j == n- 1) {
sum+=a[i][j];
[Link](a[i][j] + "\t");
}
else {
[Link]("\t");
}
}
[Link]();
}
[Link]("Sumofthediagonal elements = " + sum);
intb[]=newint[(n-2)*(n-2)];
int k = 0;
for(inti=1;i<n-1;i++){
for(intj=1;j<n-1;j++){
b[k++] = a[i][j];
}
}
for(inti=0;i<k-1;i++){
for(intj=0;j<k-i-1;j++) {
if (b[j] > b[j + 1]) {
int t = b[j];
b[j] = b[j+1];
b[j+1] = t;
}}}
k=0;
for(inti=1;i<n-1;i++){
for(intj=1;j<n-1;j++){
a[i][j] = b[k++];
}
}
for (int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
}

}
} OUTPUT : Enter sizeofthe
matrix 4 Enter elements in
the matrix: 8 9 6 3 4 5 6 7 8
2145
6 7 8 ORIGINAL
MATRIX

8 9 6 3
4 5 6 7
8 2 1 4
56 7 8

DIAGONAL ELEMENTS
8 3
5 6
2 1
5 8
Sum of the diagonal elements = 38
8 9 6 3
4 1 2 7
8 5 6 4
5 6 7 8
Question3 : Write a Java program to input a square matrix (n×n), display it,
convert it to 1D array, sort the 1D array in ascending order using bubble
sort, and display sorted array.

import [Link].*;
public class dda3 {
public static void main(String[] args) {
Scanner in=new Scanner([Link]);
[Link]("enter size nxn");
int n=[Link]();
int a[][]=new int[n][n];
[Link]("enter element in array");
for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {


a[i][j]=[Link]();
}
}
[Link]("ORIGINAL MATRIX");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](a[i][j] + "\t");
}
[Link]();
}
int[] array1D = new int[n * n];
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array1D[index] = a[i][j];
index = index + 1;
}
} [Link]();
[Link]("before arrangment");
for (int k = 0; k < [Link]; k++) {

[Link](array1D[k] + " ");


}
[Link]();
[Link]("after arrangment");
for (int i = 0; i < [Link] - 1; i++) {

for(intj=0;j<[Link]-i-1;j++) {
if (array1D[j] > array1D[j+1]) {
int t = array1D[j];
array1D[j] = array1D[j+1];
array1D[j+1] = t;
}
}
}
for (int k = 0; k < [Link]; k++) {
[Link](array1D[k] + " ");
}
}
}
OUTPUT :
Question4 : Write a Java program to input a square matrix (n×n), display it,
rotate it 90° clockwise in-place, and display the rotated matrix.

import [Link].*;
class dda4 {
public static void main(String[] args)
{
Scanner in=new Scanner([Link]);
[Link]("enter size nxn");
int n=[Link]();
int matrix[][]=new int[n][n];
[Link]("enter element in array");
for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {


matrix[i][j]=[Link]();
}
}
[Link]("Original matrix:");
for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < matrix[0].length; j++) {


[Link](matrix[i][j] + " ");
}
[Link]();
}
rotateMatrix(matrix);
}
publicstaticvoid rotateMatrix(int[][] matrix)
{
intn=[Link];
for(inti=0; i < n; i++) {
for(intj= i; j < n; j++) {
inttemp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(inti=0; i < n; i++) {
for(intj= 0; j < n / 2; j++) {
inttemp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
}
}
[Link]("Rotated matrix:");
for(inti=0; i < [Link]; i++) {
for(intj= 0; j < matrix[0].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
OUTPUT :
Question5 : Write a Java program to input size n, read two n×n matrices, display
them, multiply them, and print the result matrix.
Algorithm:

Step 1: Start program.


Step 2: Create Scanner object.

Step 3: Read size n.


Step 4: Print "FOR MATRIX 1 :".

Step 5: Create matrix1[][] of size n×n.


Step 6: Read n×n elements into matrix1.

Step 7: Print "FOR MATRIX 2 :".


Step 8: Create matrix2[][] of size n×n.

Step 9: Read n×n elements into matrix2.


Step 10: Print "Matrix 1:" and display matrix1 row-wise.

Step 11: Print "Matrix 2:" and display matrix2 row-wise.


Step 12: Call multiplyMatrices(matrix1, matrix2) and store result.

Step 13: Print "Result matrix:" and display result row-wise.

Step 14: In multiplyMatrices.

Step 15: Get rows1 = [Link], cols1 = matrix1[0].length, cols2 =


matrix2[0].length.

Step 16: Create result[][] of size rows1×cols2.

Step 17: Loop i from 0 to rows1-1.


Step 18: Loop j from 0 to cols2-1.

Step 19: Set result[i][j] = 0.


Step 20: Loop k from 0 to cols1-1.

Step 21: Add (matrix1[i][k] * matrix2[k][j]) to result[i][j].


Step 22: Return result.

Step 23: End program.

SOURCE CODE :

import [Link].*;

class dda5 {

public static void main(String[] args) {

Scanner in=new Scanner([Link]);

[Link]("enter size nxn");

int n=[Link]();

[Link]("FOR MATRIX 1 :");

int matrix1[][]=new int[n][n];

[Link]("enter element in array");

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

matrix1[i][j]=[Link]();

[Link]("FOR MATRIX 2 :");

int matrix2[][]=new int[n][n];

[Link]("enter element in array");

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

matrix2[i][j]=[Link]();
}

[Link]("Matrix 1:");

for(inti=0;i<[Link]; i++) {

for(intj=0;j< matrix1[0].length; j++) {

[Link](matrix1[i][j] + " ");

[Link]();

[Link]("Matrix 2:");

for(inti=0;i<[Link]; i++) {

for(intj=0;j< matrix2[0].length; j++) {

[Link](matrix2[i][j] + " ");

[Link]();

int[][]result=multiplyMatrices(matrix1, matrix2);

[Link]("Result matrix:");

for(inti=0;i<[Link]; i++) {

for(intj=0;j< result[0].length; j++) {

[Link](result[i][j] + " ");

[Link]();

}
}

publicstaticint[][]multiplyMatrices(int[][] matrix1, int[][] matrix2)

introws1=[Link];

intcols1=matrix1[0].length;

intcols2=matrix2[0].length; int[]

[]result=newint[rows1][cols2];

for(inti=0;i<rows1; i++) {

for(intj=0;j<cols2; j++) {

result[i][j] = 0;

for(intk=0;k< cols1; k++) {

result[i][j]=result[i][j] + (matrix1[i][k] * matrix2[k][j]);

return result; }}

VARIABLE DESCRIPTION
[Link]. DATA TYPE VARIABLE DESCRIPTION
1. Int n To store array size
2. Int matrix1[][] To create first array
3. Int i,j For loop
4. Int matrix2[][] To create second array
5. Int To store resultant array
result[][]
6. Int Torows1
store no. of 1st matrix row
7. Int Tocols1
store no. of 1st matrix column
8. Int Tocols2
store no. of 2nd matrix column
OUTPUT :
enter size nxn 3 FOR

MATRIX 1 : enter

element in array 8 7 4

5 6 3 2 4 5 FOR

MATRIX 2 : enter

element in array 9 8 7

65432
1 Matrix 1: 8 7

4 5 6 3 2 4 5

Matrix 2: 9 8 7

6 5 4 3 2 1

Result matrix:

126 107 88 90

76 62 57 46 35
Question1 : Write a Java program to input two words, check if they are
anagrams (ignoring case and spaces), and print the result.
import [Link].*;

public class s1
{

public static void main(String[] args)


{

Scanner in=new Scanner([Link]);


[Link]("enter two words");

String str1 = [Link]();


String str2 = [Link]();

boolean areAnagrams = areAnagrams(str1, str2);


[Link](str1 + " and " + str2 + " are anagrams: " + areAnagrams);

}
public static boolean areAnagrams(String s1, String s2) {

s1 = [Link]("\\s", "").toLowerCase();
s2 = [Link]("\\s", "").toLowerCase();

if ([Link]() != [Link]())
return false;

int[] count = new int[26];


for (int i = 0; i < [Link](); i++) {

count[[Link](i) - 'a']++;
}
for(inti= 0; i < [Link](); i++) {

count[[Link](i) - 'a']--;

if(count[[Link](i) - 'a'] < 0) {

return false;

returntrue;

OUTPUT :
QUESTION2 : Write a program to accept a sentence which may be
terminated by either '.', '?' or '!' only. The words may be separated by more
than one blank space and are in UPPER CASE.
Perform the following tasks:

[Link] the number of words beginning and ending with a vowel.


[Link] the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.
import [Link].*;

public class s2
{

public static void main(String args[])


{

Scanner in=new Scanner ([Link]);


String s1,s,el=" ",w=" ";char ch,f,l;int i,lw,ln,c;

int x=0;
[Link]("Enter a sentence");

s1=[Link]().trim();
s=[Link]();

ln=[Link]();
ch=[Link](ln-1);

if(ch=='.'||ch=='?'||ch=='!'){

String ss=[Link](0,ln-1);

StringTokenizer n=new StringTokenizer(ss);


c=[Link]();

String a[]=new String [c];


for(i=0;i<c;i++)

a[i]=[Link]();

for(i=0;i<c;i++) {

w=a[i]; lw=[Link](); f=[Link](0); l=[Link](lw-1);

if((f=='A' || f=='E' || f=='I' || f=='O' || f=='U' ) && (l=='A' || l=='E' ||

l=='O'||l=='U'||l=='I'))
{[Link](w+" ");

x++;}
else

el+=w+" ";
}

[Link](el+".");
[Link]("NUMBER OF WORDS BEGINNING AND
ENDINGWITHA VOWEL = " + x); }
else

[Link]("Invalid Input"); } }

OUTPUT :
Question3 : Write a Java program to input a string and count the number of
letters, digits, and special characters.

import [Link].*;
public class s3 {
publicstaticvoidmain(String[] args) {
Scannersc=new Scanner([Link]);
[Link]("Enter a string: ");
Stringinput=[Link]();

intletters=0,digits = 0, special = 0;

for(inti=0;i<[Link](); i++) {
charch=[Link](i);
if([Link](ch)) {
letters++;
}elseif([Link](ch)) {
digits++;
} else {
special++;
}
}

[Link]("Letters: " + letters);


[Link]("Digits: " + digits);
[Link]("Special Characters: " + special);
}
}
OUTPUT :
Question4 : Write a Java program to input two strings and check if the
second string is a rotation of the first.

import [Link].*;
public class s4 {
publicstaticvoidmain(String[] args) {
Scannersc=new Scanner([Link]);
[Link]("Enter first string: ");
Stringstr1=[Link]();
[Link]("Enter second string: ");
Stringstr2=[Link]();

if([Link]()!= [Link]()) {
[Link]("No, not a rotation.");
}
else {
Stringcombined = str1 + str1;
if([Link](str2)) {
[Link]("Yes, second string is a rotation of first.");
} else {
[Link]("No, not a rotation."); } } }}

OUTPUT :
Question5 : Write a Java program to input two strings and check if they are
isomorphic (one-to-one character mapping).
ALGORITHM :

Step 1: Start program.

Step 2: Create Scanner object.

Step 3: Read first string s1.


Step 4: Read second string s2.

Step 5: Call areIsomorphic(s1, s2).

Step 6: Print "Yes" if true, else "No".

Step 7: In areIsomorphic.

Step 8: If lengths differ, return false.

Step 9: Create two HashMaps: map1 (char in s1 → s2), map2 (char in s2 → s1).

Step 10: Loop i from 0 to [Link]()-1.

Step 11: Get c1 = [Link](i), c2 = [Link](i).


Step 12: If map1 has c1, check if mapped value equals c2; else return false.

Step 13: Else, put (c1, c2) in map1.


Step 14: If map2 has c2, check if mapped value equals c1; else return false.

Step 15: Else, put (c2, c1) in map2.


Step 16: After loop, return true.

Step 17: End program.


SOURCE CODE :

import [Link].*;
public class s5 {
publicstaticbooleanareIsomorphic(String s1, String s2) {
if([Link]()!=[Link]()) {
return false;
}

//forward:s1[i]→s2[i]
//backward:s2[i]→s1[i]
char[] fwd = new char[256]; //stores the image of each char in s1
char[] bwd = new char[256]; //stores the pre-image of each char in s2

for(inti=0;i<[Link](); i++) {
charc1=[Link](i);
charc2=[Link](i);

//firstoccurrence→ record the mapping


if (fwd[c1] == 0) {
fwd[c1] = c2;

}
//alreadyseen→must map to the same char
elseif(fwd[c1]!=c2) {
return false;
}
if(bwd[c2] == 0) {
bwd[c2] = c1; }
else if (bwd[c2] != c1) {
return false; } } return true;}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first string: ");
String s1 = [Link]();
[Link]("Enter second string: ");
String s2 = [Link]();

if(areIsomorphic(s1, s2))
[Link]("Yes, the strings are isomorphic.");
else
[Link]("No, the strings are not isomorphic.");
}
}

VARIABLE DESCRIPTION
[Link]. DATA TYPE VARIABLE DESCRIPTION
1. String s1 To store 1st word
2. String s2 To store 2nd word
3. Char fwd[] To store image of each character
4. Char bwd[] To store pre image of each character
5. Char c1 To extract and store each value of s1
6. Char c2 To extract and store each value of s2
7. Int i For loop
OUTPUT :
QUESTION 1:
Base Class: Employee (Parent Class)

Data Members:

n → stores number of employees


name[] → stores names of employees (String array)
salary[] → stores salary of employees (int array)
size → stores total number of employees

Member Functions:

1. Employee(int size) → parameterized constructor to initialize size, name[], and salary[]


2. void input() → input name and salary of each employee
3. void displayAll() → display all employee details in tabular form (Name Salary)

Derived Class: Bonus (Child Class – inherits from Employee)

Data Members:

ind → stores index of employee with highest salary

Member Functions:

1. Bonus(int size) → parameterized constructor (calls parent constructor using super(size))


2. void calcBonus() → calculates and displays 20% bonus for each employee
3. void findHighest() → finds the index of the employee with highest salary and assigns it to ind
4. void display() → overridden method to display:

o All employee details


o Bonus for each employee
o Name and salary of the employee with highest salary

import [Link].*;

class Employee {

String name[];

int salary[];
int size;

Employee(int n) {

size = n;

name=newString[size];

salary=newint[size];

void input() {

Scannersc=newScanner([Link]);

[Link]("Enter " + size + " employees (name salary):");

for(inti=0;i<size; i++) {

name[i]=[Link]();

salary[i]=[Link]();

void displayAll() {

[Link]("Name\tSalary");

for(inti=0;i<size; i++) {

[Link](name[i] + "\t" + salary[i]);

}
}

classBonus extends Employee {

int ind;

Bonus(int n) {

super(n);

ind=0;

voidcalcBonus() {

[Link]("Bonus (20%):");

for(int i = 0; i < size; i++) {

[Link](name[i] + ": " + (0.2 * salary[i]));

voidfindHighest() {

intmax = salary[0];

for(int i = 1; i < size; i++) {

if(salary[i] > max) {


max = salary[i];

ind = i;

[Link]("Highest Paid: " + name[ind] + " - " + salary[ind]);

public static void main(String[] args) {

Bonus b = new Bonus(3);

[Link]();

[Link]();

[Link]();

[Link](); }}

OUTPUT :
QUESTION2 :
Base Class: Student (Parent Class)

Data Members:

name → stores name of student (String)


m1 → stores Physics marks (int)
m2 → stores Chemistry marks (int)
m3 → stores Maths marks (int)

Member Functions:

1. Student(String n, int a, int b, int c) → parameterized constructor to initialize name and three subject
marks
2. void display() → displays name and marks in format:

Derived Class: Result (Child Class – inherits from Student)

Data Members:

status → stores result ("PASS" or "FAIL")

Member Functions:

1. Result(String n, int a, int b, int c) → parameterized constructor

o Calls parent constructor using super(n, a, b, c)


o Initializes status = "FAIL" by default

2. void check() → checks if student passed all subjects

o If m1 ≥ 35 && m2 ≥ 35 && m3 ≥ 35 → set status = "PASS"

3. void display() → overridden method to display:

o Call [Link]()
o Call check()
o Print Result: PASS or Result: FAIL

import [Link].*;

class Student {

String name;

int m1, m2, m3;


Student(String n, int a, int b, int c) {

name = n;

m1 = a;

m2 = b;

m3 = c;

void display() {

[Link]("Name: " + name);

[Link]("Marks: " + m1 + ", " + m2 + ", " + m3);

import [Link].*;

classResult extends Student {

String status;

Result(String n, int a, int b, int c) {

super(n, a, b, c);

status = "FAIL";

}
voidcheck() {

if(m1 >= 35 && m2 >= 35 && m3 >= 35)

status = "PASS";

voiddisplay() {

[Link]();

check();

[Link]("Result: " + status);

publicstatic void main(String[] args) {

Scanner in=new Scanner([Link]);

[Link]("enter name of first student");

String a=[Link](); [Link]("enter

phy,chem,maths marks"); intb=[Link]();

intc=[Link](); intd=[Link](); Result r1 = new

Result(a,b,c,d);

[Link]("enter name of second student");

String a1=[Link]();
[Link]("enter phy,chem,maths marks");

int b1=[Link]();

int c1=[Link]();

int d1=[Link]();

Result r2 = new Result(a1,b1,c1,d1);

[Link]();

[Link]("---");

[Link]();

OUTPUT :
QUESTION 3:
Base Class: Product (Parent Class)

Data Members:

pname → stores product name (String)


qty → stores quantity (int)
rate → stores price per unit (int)
amt → stores total amount (qty * rate)

Member Functions:

1. Product(String p, int q, int r) → parameterized constructor

o Initialize pname = p, qty = q, rate = r


o Calculate amt = qty * rate

2. void display() → displays product details:

Derived Class: Discount (Child Class – inherits from Product)

Data Members:

per → stores discount percentage (int)

Member Functions:

1. Discount(String p, int q, int r, int d) → parameterized constructor

o Calls parent constructor using super(p, q, r)


o Initialize per = d

2. void applyDiscount() → applies discount

o Update rate = rate - (rate * per / 100)


o Recalculate amt = qty * rate

3. void display() → overridden method to display:

o Print === Before Discount ===


o Call [Link]()
o Call applyDiscount()
o Print === After <per>% Discount ===
o Print updated product details (New Rate, New Amt)
class Product {

String pname;

int qty, rate, amt;

Product(String p, int q, int r) {

pname = p;

qty = q;

rate = r;

amt = qty * rate;

void display() {

[Link]("Product: " + pname);

[Link]("Qty: " + qty + ", Rate: " + rate + ", Amt: " + amt);

}}

import [Link].*;

class Discount extends Product {

int per;

Discount(String p, int q, int r, int d) {

super(p, q, r);

per = d;

void applyDiscount() {
rate= rate - (rate * per / 100);

amt= qty * rate; }

voiddisplay() {

[Link]("=== Before Discount ===");

[Link]();

applyDiscount();

[Link]("=== After " + per + "% Discount ===");

[Link]("Product: " + pname);

[Link]("Qty: " + qty + ", New Rate: " + rate + ", New Amt:
" + amt);

publicstatic void main(String[] args) {

Scanner in=new Scanner([Link]);

[Link]("ENTER PRODUCT NAME, QUANTITY,PRICE


ANDDISCOUNT");

String n=[Link]();

inta1=[Link]();

inta2=[Link]();

inta3=[Link]();

Discount d = new Discount(n,a1,a2,a3); [Link](); }}


OUTPUT :
QUESTION 4:
Base Class: Word (Parent Class)

Data Members:

str → stores the input word (String)

Member Functions:

1. void accept() →

o Prompts user: "Enter a word: "


o Reads input using Scanner and stores in str

2. void show() →

o Displays: Original: <str>

Derived Class: ReverseWord (Child Class – inherits from Word)

Data Members:

rev → stores reversed string (initially empty "")

Member Functions:

1. void reverse() →

o Reverses the string str character by character


o Stores result in rev

2. void show() → overridden method to display:

o Call [Link]() → prints original word


o Call reverse() → computes reverse
o Print Reversed: <rev>

import [Link].*;

class Word {

String str;
void accept() {

Scannersc=new Scanner([Link]);

[Link]("Enter a word: ");

str = [Link]();

void show() {

[Link]("Original: " + str);

classReverseWordextends Word {

String rev = "";

void reverse() {

for(inti=[Link]() - 1; i >= 0; i--) {

rev+=[Link](i);

void show() {
[Link]();

reverse();

[Link]("Reversed: " + rev);

public static void main(String[] args) {

ReverseWord rw = new ReverseWord();

[Link]();

[Link]();

OUTPUT :
QUESTION 5:
Base Class: Book (Parent Class)

Data Members:

title → stores book title (String)


copies → stores total available copies (int)
price → stores price per copy (int)

Member Functions:

1. Book(String t, int c, int p) → parameterized constructor

o Initialize title = t, copies = c, price = p

2. void display() → displays book details:

Derived Class: Issue (Child Class – inherits from Book)

Data Members:

 issueCopies → stores number of copies to be issued (int)

Member Functions:

1. Issue(String t, int c, int p, int ic) → parameterized constructor

o Calls parent constructor using super(t, c, p)


o Initialize issueCopies = ic

2. void issueBook() → issues the book

o If issueCopies <= copies →

Reduce copies -= issueCopies


Print: <issueCopies> copies issued successfully.

o Else → Print: Not enough copies!

3. void display() → overridden method to display:

o Print === Before Issue ===


o Call [Link]()
o Call issueBook()
o Print === After Issue ===
o Print updated details
ALGORITHM :
Base Class: Book
Step 1: Start program.

Step 2: Create Book class.

Step 3: Declare variables:

title (String)
copies (int)
price (int)

Step 4: Define constructor Book(String t, int c, int p)

Assign title = t
Assign copies = c
Assign price = p

Step 5: Define display() method

Print: "Title: " + title


Print: "Copies: " + copies
Print: "Price: " + price

Derived Class: Issue


Step 6: Create Issue class extending Book.

Step 7: Declare variable:

issueCopies (int)

Step 8: Define constructor Issue(String t, int c, int p, int ic)

Call super(t, c, p)
Assign issueCopies = ic

Step 9: Define issueBook() method

Check if issueCopies <= copies

o If true:
copies = copies - issueCopies
Print: issueCopies + " copies issued successfully."

o If false:
Print: "Not enough copies!"
Step 10: Define display() method (overridden)

Print: "=== Before Issue ==="


Call [Link]()
Call issueBook()
Print: "=== After Issue ==="
Print: "Title: " + title
Print: "Copies Left: " + copies
Print: "Price: " + price

SOURCE CODE :
import [Link].*;

classBook {

String title;

intcopies, price;

Book(String t, int c, int p) {

title = t;

copies = c;

price = p;

void display() {

[Link]("Title: " + title);

[Link]("Copies: " + copies);

[Link]("Price: " + price);

}
}

[Link].*;

classIssue extends Book {

intissueCopies;

Issue(String t, int c, int p, int ic) {

super(t, c, p);

issueCopies = ic;

voidissueBook() {

if(issueCopies <= copies) {

copies -= issueCopies;

[Link](issueCopies + " copies issued successfully.");

}else {

[Link]("Not enough copies!");

voiddisplay() {

[Link]("=== Before Issue ===");

[Link]();
issueBook();

[Link]("=== After Issue ===");

[Link]("Title: " + title);

[Link]("Copies Left: " + copies);

[Link]("Price: " + price);

public static void main(String[] args) {

Scanner in=new Scanner([Link]);

[Link]("ENTER BOOK TITLE,COPY,PRICE AND COPY TO


BEISSUED");

String n=[Link]();

int a1=[Link]();

int a2=[Link]();

int a3=[Link]();

Issue obj = new Issue(n,a1,a2,a3);

[Link]();

}
VARIABLE DESCRIPTION
[Link]. DATA TYPE VARIABLE DESCRIPTION
1. String To store
title book title
2. int Tocopies
store no. of copies
3. int To store
price book price
4. String To storet book title
5. int To storec no. of copies
6. int To store
p book price
7. int To store
ic no. of issued copies
8. int issuecopies To store no. of issued copies
9. String n To accept book title
10. int a1 To accept no. Of copies
11. int a2 To accept book price
12. int a3 To accept no. Of issue book

OUTPUT :
QUESTION 1:
Main Class: sq1

Data Members:

None (All logic in static methods and main)

Member Functions (Static):

1. static int[] nextGreater(int[] a) →

o Finds next greater element to the right for each element in array
o Uses stack to track candidates
o Returns result array where:
res[i] = next greater element to right of a[i]
If no greater element → -1

import [Link].*;

public class sq1

static int[] nextGreater(int[] a) {

int n = [Link]; int[] res =

new int[n]; int[] stk = new

int[n]; int top = -1; for (int i =

n - 1; i >= 0; i--) {

while (top >= 0 && stk[top] <= a[i])

top--;

res[i] = top < 0 ? -1 : stk[top];

stk[++top] = a[i];
}

return res;

publicstatic void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter 1 to start");

if([Link]() != 1) {

[Link]("Error not inserted 1");

return;

String y = "yes";

[Link]("Enter yes to enter numbers");

String s = [Link]();

while ([Link](y)) {

[Link]("Enter 4 numbers");

int[] nums = new int[4];

for (int i = 0; i < 4; i++)

nums[i] = [Link]();

[Link]("Input: " + [Link](nums));

[Link]("Output: " + [Link](nextGreater(nums)));

[Link]("want to continue than type yes else no");

s= [Link]();
}

[Link]("Thank you");

OUTPUT :
QUESTION2 :
Main Class: sq2

Data Members:

char[] arr → array to simulate stack/queue


top → pointer for stack top (-1 = empty)
capacity → size of array

Member Functions:

1. sq2(int size) → parameterized constructor

o Initialize capacity = size


o Create arr = new char[capacity]
o Set top = -1

import [Link].*;

publicclass sq2 {

char[] arr;

inttop;

intcapacity;

sq2(int size) {

capacity = size;

arr = new char[capacity];

top = -1;

public static void main(String[] args) {


Scannersc=newScanner([Link]);

[Link]("Enterastring: ");

Stringinput=[Link]().toLowerCase().replaceAll("\\s+", "");

int len = [Link]();

sq2 stack = new sq2(len);

sq2 queue = new sq2(len);

for (int i = 0; i < len; i++) {

char ch = [Link](i);

if([Link]<[Link] - 1) {

[Link]++;

[Link][[Link]]=ch;

if([Link]<[Link] - 1) {

[Link]++;

[Link][[Link]]=ch; } }

boolean issq2 = true;

int queueFront = 0;

while([Link]>=0&&queueFront <= [Link]) {

charfromStack=[Link][[Link]--];

charfromQueue=[Link][queueFront++];

if(fromStack!=fromQueue) {

issq2 = false;
break; }}

[Link](issq2 ? "The string is a PALINDROME." : "The


string is NOT a Palindrome.");

[Link](); }}

OUTPUT :
QUESTION3 :
Main Class: sq3

Data Members (in main):

int[] stk → simulates stack for evaluation


int[] que → simulates queue to store evaluation trace
top → stack pointer (-1 = empty)
front → queue front pointer
rear → queue rear pointer

import [Link].*;

public class sq3 {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter postfix (space-separated): ");

String[] tokens = [Link]().split(" ");

int n = [Link];

int[] stk = new int[n], que = new int[n];

int top = -1, front = 0, rear = -1;

for (String token : tokens) {

if ([Link]([Link](0))) {

int num = [Link](token);

stk[++top] = num;

que[++rear] = num;

} else {

int b = stk[top--], a = stk[top--];

switch (token) {
case "+" -> stk[++top] = a + b;

case "-" -> stk[++top] = a - b;

case "*" -> stk[++top] = a * b;

case "/" -> stk[++top] = a / b;

que[++rear] = stk[top];

[Link]("Result: " + stk[top]);

[Link]("Eval trace: ");

while(front <= rear) [Link](que[front++] + " ");

[Link]();

}}

OUTPUT :
QUESTION4 :
Main Class: sq4

Data Members (in main):

int[] price → stores stock prices for n days


int[] span → stores stock span for each day
int[] stk → simulates stack to store indices
int[] que → simulates queue to store prices in order
top → stack pointer (-1 = empty)
front → queue front pointer
rear → queue rear pointer

import [Link].*;

public class sq4 {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter days: ");

int n = [Link]();

int[] price = new int[n], span = new int[n];

int[] stk = new int[n], que = new int[n];

int top = -1, front = 0, rear = -1;

[Link]("Enter prices:");

for (int i = 0; i < n; i++) price[i] = [Link]();

for (int i = 0; i < n; i++) {

que[++rear] = price[i];

while (top >= 0 && price[stk[top]] <= price[i]) top--;

span[i] = top < 0 ? i + 1 : i - stk[top];


stk[++top] = i;

[Link]("Span: " + [Link](span));

[Link]("Prices in queue: ");

while (front <= rear) [Link](que[front++] + " ");

[Link]();

OUTPUT :
QUESTION5 :
Main Class: sq5

Data Members (in main):

int[] a → input array of size n


int[] res → stores maximum of each window of size k
int[] stk → monotonic decreasing queue of indices
int[] que → queue to store all elements in order
top → rear of deque (-1 = empty)
front → front of deque
rear → rear of input queue

ALGORITHM :

Step 1: Start program.


Step 2: Import [Link].*.

Step 3: Define class sq5.

Step 4: Define main(String[] args).

Step 5: Create Scanner sc.

Step 6: Print "Enter n, k: ".

Step 7: Read n.
Step 8: Read k.

Step 9: Create a[] of size n.


Step 10: Create res[] of size n-k+1.

Step 11: Create stk[] of size n.


Step 12: Create que[] of size n.

Step 13: Set top = -1.

Step 14: Set front = 0.

Step 15: Set rear = -1.

Step 16: Print "Enter array:".


Step 17: Loop i from 0 to n-1.

Step 18: Read a[i].

Step 19: Enqueue: que[++rear] = a[i].

Step 20: If stk[front] == i - k: front++.

Step 21: While top >= 0 and a[stk[top]] <= a[i]: top--.

Step 22: Push: stk[++top] = i.

Step 23: If i >= k - 1.

Step 24: res[i - k + 1] = a[stk[front]].

Step 25: End loop.

Step 26: Print "Max: " + [Link](res).

Step 27: Print "Window elements: ".

Step 28: Set front = rear - k + 2.

Step 29: While front <= rear:

Step 30: Print que[front++] + " ".

Step 31: Print newline.

Step 32: End program.

SOURCE CODE :

import [Link].*;

public class sq5 {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter n, k: ");

int n = [Link](), k = [Link]();


int[]a=newint[n],res=newint[n-k+1];

int[]stk=newint[n],que=newint[n];

int top = -1, front = 0, rear = -1;

[Link]("Enter array:");

for (int i = 0; i < n; i++) {

a[i] = [Link]();

que[++rear] = a[i];

while(top>=0&&a[stk[top]]<= a[i]) top--;

stk[++top] = i;

if (stk[front] == i - k) front++;

if(i>=k-1)res[i-k+1]=a[stk[front]];

[Link]("Max:"+[Link](res));

[Link]("Windowelements: ");

front = rear - k + 2;

while(front<=rear)[Link](que[front++] + " ");

[Link]();

}
VARIABLE DESCRIPTION
[Link]. DATA TYPE VARIABLE DESCRIPTION
1. int n Totalnumberofelementsinthe array
2. int k Size of the sliding window
3. int a[] Input array of n integers
4. int res[] Output:maximumofeverywindow of
5. size k
int que[] Queuethatstoresactualarrayelements
6. int stk[] Monotonicstack(holdsindices)
7. int top Stack pointer (-1 = empty)
8. int front Frontindexofdeque(oldestuseful
9. int rear index)
10. Rearindexofqueue(-1=empty)
int i
For loop

OUTPUT :
THE
END

You might also like