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

Computer Board Project

The document outlines various Java programs that check different properties of numbers, including Fascinating, Bouncy, Unique, Prime Automorphic, Lychrel, and Adam numbers, as well as functionalities for manipulating strings and grids. Each program includes an algorithm and a code implementation, detailing steps for input, processing, and output. The document serves as a comprehensive guide for understanding and implementing these numerical and string operations in Java.

Uploaded by

Prajith P
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 views112 pages

Computer Board Project

The document outlines various Java programs that check different properties of numbers, including Fascinating, Bouncy, Unique, Prime Automorphic, Lychrel, and Adam numbers, as well as functionalities for manipulating strings and grids. Each program includes an algorithm and a code implementation, detailing steps for input, processing, and output. The document serves as a comprehensive guide for understanding and implementing these numerical and string operations in Java.

Uploaded by

Prajith P
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
You are on page 1/ 112

Program 1:

Check whether the number is a Fascinating Number.

Algorithm:
Step 1: Start
Step 2: Accept a three digit number
Step 3: Get a string array which is filled with all unit digits
Step 4: Multiple the input number with 2 and 3
Step 5: Concatenate the two multiplied values with the input number
Step 6: Check every digits in the final concatenated is only present once in the
number
Step 7: After extracting a digit, make the position of the digit in the array as 0
Step 8: Finally if all the positions in the String Array is 0 then that means all the
digit are present only once in the final concatenated number, print the number is
Fascinating Number
Step 9: Stop
PROGRAM:

import java.util.*;
class Fascinating_number
{public static void main()
{Scanner sc= new Scanner(System.in);
System.out.println("Enter a Three Digit Number");
int n=sc.nextInt();
int c=0,f=0;
String k[]={"1","2","3","4","5","6","7","8","9"};
if(n>99&&n<1000)
{int p1=n*2;
int p2=n*3;
String s=n+""+p1+""+p2;
System.out.println(s);
for(int i=0;i<s.length();i++)
{char ch=s.charAt(i);
String h=Character.toString(ch);
for(int j=0;j<9;j++)
{if(k[j].equals(h))
{k[j]="0";
break;
}
}
}
for(int j=0;j<9;j++)
if(k[j].equals("0"))
c++;
if(c==9)
System.out.println("It is a Fascinating Number");
else
System.out.println("It is Not a Fascinating Number");
}
}
}

OUTPUT:
Program 2:
Check whether the number is a Bouncy Number.

Algorithm:
Step 1: Start
Step 2: Input a number and check whether it is a positive integer.
Step 3: Edge case: If the number has fewer than 3 digits, it cannot be bouncy.
Return false directly.
Step 4: Extract digits: Parse the number to its individual digits.
Step 5: Check trends:
 Track if the digits are increasing and/or decreasing.
 Use two flags to determine trends.
 Traverse the digits:
o If any pair of adjacent digits violates increasing or decreasing
conditions, update the respective flags.
Step 6: Determine result:
 If both flags are true, the number is bouncy.
 Otherwise, it’s not
Step 7: Stop
PROGRAM:

import java.util.*;
class Bouncy_number
{
static int increasingorder(int n)
{
int d=n%10;
int f=0;
while(n>0)
{
int digit=n%10;
if (digit>d)
f=1;
d=digit;
n=n/10;
}
return f;
}
static int decreasingorder(int n)
{
int d=n%10;
int f=0;
while(n>0)
{
int digit=n%10;
if (digit<d)
f=1;
d=digit;
n=n/10;
}
return f;
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number");
int n=sc.nextInt();
if(increasingorder(n)==0)
System.out.println("The number is in increasing order, so not a Bouncy
number");
else if(decreasingorder(n)==0)
System.out.println("The number is in decreasing order,so not Bouncy
number");
else
System.out.println("The number is a Bouncy number");
}
}
OUTPUT:
Program 3:
Check whether the number is a Unique Number.

Algorithm:
Step 1: Start
Step 2: Accept a number
Step 3: Enter all the single digits in an array, and to count the number of
occurrence of each digits another array is initialised with all 0
Step 4: Extracting each digits from the number and check the number of
occurrence of each digit with the help of the count array
Step 5: If each digit is present only once in the number then print the number is
UNIQUE Number
Step 6: stop
PROGRAM:

import java.util.*;
class Unique_Number
{public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
int cc=0;
int a[]={0,1,2,3,4,5,6,7,8,9};
int c[]={0,0,0,0,0,0,0,0,0,0};
while (n>0)
{int r=n%10;
for(int i=0;i<10;i++)
if(r==a[i])
c[i]++;
n=n/10;
}
for(int i=0;i<10;i++)
if(c[i]==0||c[i]==1)
cc++;
if(cc==10)
System.out.println("The number is an Unique Number");
else
System.out.println("The number is not an Unique Number");
}
}
OUTPUT:
Program 4:
Check whether the number is Prime Automorphic Number

Algorithm:
Step 1: Start
Step 2: Accept a number
Step 3: Check whether the number is Prime
Step 4: If the number is not prime then skip the upcoming steps and print the
number is not prime automorphic
Step 5: Store the number as String to find the length of the number
Step 6: Square the input number and if the last few digits with the length of the
input is same as the input number then print the number is prime automorphic
number
Step 7: Stop
PROGRAM:

import java.util.*;
class Prime_Automorphic_Number
{public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter a Number");
int n=sc.nextInt();
int c=0;
for(int i=2;i<n;i++)
if(n%i==0)
c++;
if(c==0)
{String s=Integer.toString(n);
int l=s.length();
int m=n*n;
if(m%Math.pow(10,l)==n)
System.out.println("The number is a Prime Automorphic number");
else
System.out.println("The number is a not Prime Automorphic
number");
}
else if(c!=0)
System.out.println("The Number is not Prime Number");
}
}
OUTPUT:
Program 5:
Check whether the number is Lychrel number

Algorithm:
Step 1: Start
Step 2: Input a number n and the number of cycles c.
Step 3: Initialize a flag f to 0.
Step 4: For c iterations:
Step 5: Add the reverse of n to n.
Step 7: Print the updated n.
Step 8: Check if the updated n is a palindrome.
Step 9: If yes, set f = 1 and break the loop.
Step 10: After the loop:
Step 11: If f == 0, print the number is Lychrel.
Step 12: Otherwise, print not lychrel.
Step 13: Stop
PROGRAM:

import java.util.*;
class Lychrel_number
{
static int reverse(int n)
{
int rev=0;
while(n>0)
{
int d=n%10;
rev=rev*10+d;
n=n/10;
}
return rev;
}

static boolean palin(int m)


{
if(reverse(m)==m)
return true;
else
return false;
}

public static void main()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number");
int n=sc.nextInt();
System.out.println("Enter number of cycles");
int c=sc.nextInt();
int f=0;
for(int i=1;i<=c;i++)
{
n=n+reverse(n);
System.out.println(n);
if(palin(n)==true)
{f=1;
break;
}
}
if(f==0)
System.out.println("It is a Lychrel Number");
else
System.out.println("It is not a Lychrel Number");
}
}
OUTPUT:
Program 6:
Print the Prime Factors of a Number

Algorithm:
Step 1: Start
Step 2: Create a function “prime” to check whether the number is prime or not
Step 3: In the main method accept a number
Step 4: Firstly find the factors of the number with a for loop by dividing every
number from 2 to that number and check whether each factors are prime with
the help of the function “prime”
Step 5: Print the factors which are prime
Step 6: Stop
PROGRAM:

import java.util.*;
class Prime_Factors
{static void prime(int a)
{ int c=0;
for(int i=2;i<a;i++)
if(a%i==0)
c++;
if (c==0)
System.out.println(a);
}

public static void main ()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Number");
int n=sc.nextInt();
System.out.println("The Prime Factors are:");
for (int i=2;i<=n;i++)
if(n%i==0)
prime(i);
}
}
OUTPUT:
Program 7:
Generate Adam numbers from given range

Algorithm:
Step 1: Start
Step 2: Create another function “rev” to reverse the input numbers
Step 3: Create a function “adam” and use the “rev” function to check whether
the number is Adam number or not
Step 4: In the main method accept the range of the numbers between which the
adam numbers is to be generated
Step 5: In a for loop check every numbers within the range is adam number
using “adam” function
Step 6: Print the adam numbers present between the given
Step 7: Stop
PROGRAM:

import java.util.*;
class Adam_number
{ static int rev(int a)
{ int rev=0;
while(a>0)
{rev=rev*10+(a%10);
a=a/10;
}return rev;}
static void adam(int s)
{ int k=s*s;
int l =rev(k);
int m=(int)Math.sqrt(l);
int n=rev(m);
if (n==s)
System.out.println(s);}
public static void main ()
{ Scanner sc=new Scanner (System.in);
System.out.println("Enter the range of number in which the Adam number
to be generated");
int n=sc.nextInt();
int m=sc.nextInt();
System.out.println("The Adam numbers are:");
for (int i=Math.min(n,m);i<=Math.max(n,m);i++)
adam(i);
}
}
OUTPUT:
Program 8:
Remove the repeated words in a sentence

Algorithm:
Step 1: Start
Step 2: Accept a sentence from the user
Step 3: Add a blank space at the end of the sentences so as every space could be
taken as a delimiter to count the number of words present in the sentence
Step 4: Separate each word and store it in the array if the same word is not
present in the array
Step 5: Print the array in which each elements is present for only one time
Step 7: Stop
PROGRAM:

import java.util.*;
class Repeated_Words
{public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter the Passage");
String s=sc.nextLine();
int c=0;
String s1="";
s=s+" ";
for(int i=0;i<s.length();i++)
{char ch=s.charAt(i);
if(ch==' ')
c++;
}
String ss[]=new String[c];
int k=0,f=0;
for(int i=0;i<s.length();i++)
{char ch=s.charAt(i);
if(ch!=' ')
{s1=s1+ch;
}
else if(ch==' ')
{for(int j=0;j<c;j++)
{if(s1.equals(ss[j]))
break;
if(s1.equals(ss[j])==false)
f++;
}
if(f==c)
{ss[k]=s1;
k++;
}
s1="";
f=0;
}
}
for(int i=0;i<k;i++)
{System.out.print(ss[i]+" ");
}
}
}

OUTPUT:
Program 9:
Rotation of a sentence

Algorithm:
Step 1: Start
Step 2: Accept a sentence from the user
Step 3: Add a blank space at the end of the sentences so as every space could be
taken as a delimiter to count the number of words and separate each word
present in the sentence
Step 4: Store each word in an array
Step 5: First word is taken to the last every time for, how many words present in
the sentence, times
Step 6: print each sentence during the rotation
Step 7: Stop
PROGRAM:

import java.util.*;
class Rotate
{public static void main()
{Scanner sc= new Scanner (System.in);
System.out.println("Enter the sentence");
String s=sc.nextLine();String s1="";String sss=s;
s=s+" ";int c=0;String t="";int k=0;
for(int i=0;i<s.length();i++)
if (s.charAt(i)==' ')
c++;
String ss[]=new String[c];
for(int i=0;i<s.length();i++)
{if(s.charAt(i)!=' ')
s1=s1+s.charAt(i);
else if(s.charAt(i)==' ')
{ss[k]=s1;
s1="";
k++;
}
}
for (int j=0;j<k;j++)
{s1="";
for (int i=0;i<k-1;i++)
{t=ss[i];
ss[i]=ss[i+1];
ss[i+1]=t;

}
for (int i=0;i<k;i++)
s1=s1+" "+ss[i];
System.out.println(s1);
if(s1.equals(sss))
break;
}
}
}

OUTPUT:
Program 10:
Print the Potential of a string

Algorithm:
Step 1: Start
Step 2: Accept a string from user
Step 3: Split each words from the String
Step 4: Find the sum of the (ASCII value of each character in a word -64) in
sum variable
Step 5: Print sum for potential of each word in the string
Step 6: Find the sum of potential of all the words present in the String in
variable sum1
Step 7: Print sum1 for potential of entire String
Step 8: Stop
PROGRAM:

import java.util.*;
class Potential
{public static void main()
{Scanner sc= new Scanner (System.in);
System.out.println("Enter the String");
String s=sc.nextLine();
s=s+" ";
String s1="";
int sum=0,sum1=0;
for(int i=0;i<s.length();i++)
{char ch=s.charAt(i);
if(ch!=' ')
s1=s1+ch;
else if(ch==' ')
{for(int j=0;j<s1.length();j++)
sum=sum+(s1.charAt(j)-64);
System.out.println(s1+" "+sum);
sum1=sum1+sum;
s1="";
sum=0;
}
}System.out.println("The potential of the entire Sentence is "+sum1);
}
}
OUTPUT:
Program 11:
Word grid

Algorithm
Step 1: Start
Step 2: Input Grid Dimensions
o Prompt the user to enter the number of rows (r) and columns (c).
Step 3: Initialize the Grid
o Create a 2-dimensional character array (grid[r][c]).
o Populate the grid by taking row-by-row input from the user.
Step 4: Display Menu
o Show the options:
1. Display Grid
2. Search for a Word
3. Exit
Step 5: Process User Choice
o If choice = 1:
 Display the grid by iterating through each cell and printing
the characters in a tabular format.
o If choice = 2:
 Prompt the user for a word to search.
 Perform a horizontal search:
 For each row, check all substrings of length equal to
the word.
 Perform a vertical search:
 For each column, check all substrings of length equal
to the word.
 If the word is found in either direction, display its starting
position.
 Otherwise, print "Word not found."
o If choice = 3:
 Exit the program.
o If the choice is invalid, show an error message.
Step 6: Repeat Menu
o Continue displaying the menu until the user selects "Exit."
Step 7: Stop

PROGRAM:

import java.util.*;
public class Word_Grid
{
static char[][] grid;
static int rows, cols;
public static void initializeGrid(int r, int c) {
rows = r;
cols = c;
grid = new char[rows][cols];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the grid row by row (words in Uppercase
only):");
for (int i = 0; i < rows; i++) {
String rowInput = sc.next();
for (int j = 0; j < cols; j++) {
grid[i][j] = rowInput.charAt(j);
}
}
}
public static void displayGrid() {
System.out.println("Word Grid:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
public static boolean searchWord(String word) {
int wordLength = word.length();
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= cols - wordLength; j++) {
StringBuilder horizontalWord = new StringBuilder();
for (int k = 0; k < wordLength; k++) {
horizontalWord.append(grid[i][j + k]);
}
if (horizontalWord.toString().equals(word)) {
System.out.println("Found word \"" + word + "\" horizontally at ("
+ i + ", " + j + ")");
return true;
}
}
}
for (int i = 0; i <= rows - wordLength; i++) {
for (int j = 0; j < cols; j++) {
StringBuilder verticalWord = new StringBuilder();
for (int k = 0; k < wordLength; k++) {
verticalWord.append(grid[i + k][j]);
}
if (verticalWord.toString().equals(word)) {
System.out.println("Found word \"" + word + "\" vertically at (" + i
+ ", " + j + ")");
return true;
}
}
}
System.out.println("Word \"" + word + "\" not found.");
return false;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int r = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int c = scanner.nextInt();
initializeGrid(r, c);
while (true)
{
System.out.println("\nMenu:");
System.out.println("1. Display Grid");
System.out.println("2. Search for a Word");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice)
{
case 1:
displayGrid();
break;
case 2:
System.out.print("Enter the word to search: ");
String word = scanner.next();
searchWord(word);
break;
case 3:
System.out.println("Exiting the program. Goodbye!");
scanner.close();
return;
default:
System.out.println("Invalid choice! Please try again.");
}
}
}
}
OUTPUT:
Program 12:
Count the number of Anagram words

Algorithm:
Step 1: Start
Step 2: Input and Split:
 Read the input string and split it into words.
Step 3: Sort Characters of Each Word:
 For each word, sort its characters alphabetically to normalize it. This
makes it easier to compare if two words are anagrams.
Step 4: Store Normalized Words:
 Store these sorted versions (normalized words) in an array.
Step 5: Identify Anagrams:
 Compare every normalized word with the others in the array. If two
normalized words are the same, the corresponding original words are
anagrams.
Step 6: Count and Print:
 For each pair of words identified as anagrams, print them and increment a
counter.
 Print the total count of anagram pairs.
Step 7: Stop
PROGRAM:

import java.util.*;
class ANAGRAMS
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.println("enter the string...");
String s= sc.nextLine();
String str[]=s.split(" ");
String AR[]=new String[str.length];
for(i=0;i<AR.length;i++)
{
String st="";
for(char c='A';c<='Z';c++)
{
for(j=0;j<str[i].length();j++)
{
char ch=str[i].charAt(j);
if(ch==c)
st=st+ch;
}
}
AR[i]=st;
st="";
}
for(i=0;i<AR.length;i++)
System.out.println(AR[i]);
int count=0;
for(i=0;i<AR.length;i++)
{
String m=AR[i];String word=str[i];
for(j=i+1;j<AR.length;j++)
{
if(AR[j].equals(m)==true)
{
System.out.println(word+" "+str[j]+" are anagrams");
count++;
}
}
}
System.out.println("count="+count);
}
}

OUTPUT:
Program 13:
Encryption and decryption of String

Algorithm:
Step 1: Start
Step 2: Enter the string and get the number of letters to be moved in both
encryption and decryption
Step 3: For encryption, extract each character and increase the ASCII value of
character the number of times the user gave as input. If the character is in
uppercase then if the character number has crossed 90 then decrease it by 26. If
the character is lowercase then if the character number has crossed 122 then
decrease by 26.
Step 4: Now concatenate each changes character and print it as the encrypted
word
Step 5: For decryption, extract each character and decrease the ASCII value of
character the number of times the user gave as input. If the character is in
uppercase then if the character number is less than 65 then increase it by 26. If
the character is lowercase then if the character number is less than 97 then
increase by 26.
Step 6: Now concatenate each changes character and print it as the decrypted
word
Step 7: Do both encryption and decryption in switch case
Step 8: Stop
PROGRAM:

import java.util.*;
class Encyrtion_Decyrtion //In encryption the letter is substitued by the nth
letter of user's choice; and the opposite in decryption:
{public static void main()
{Scanner sc= new Scanner (System.in);
System.out.println("Enter the String");
String s=sc.nextLine();
String s1="";
System.out.println("In encryption the letter is substitued by the nth letter of
user's choice; and the opposite in decryption");
int n=sc.nextInt();
System.out.println("Press 1 for Encryption \nPress 2 for Decryption");
int ch=sc.nextInt();
switch(ch)
{case 1:
for (int i=0;i<s.length();i++)
{char c=(char)((s.charAt(i)));
int h=(int)c+n;
char cc=(char)h;
if (Character.isUpperCase(c))
{if(h>90)
cc=(char)(cc-26);
}
else if(Character.isLowerCase(c))
{if(h>122)
cc=(char)(cc-26);
}
s1=s1+cc;
}
System.out.println(s1);
break;
case 2:
for (int i=0;i<s.length();i++)
{char c=(char)((s.charAt(i)));
int h=(int)c-n;
char cc=(char)h;
if (Character.isUpperCase(c))
{if(h<65)
cc=(char)(cc+26);
}
else if(Character.isLowerCase(c))
{if(h<97)
cc=(char)(cc+26);
}
s1=s1+cc;

}
System.out.println(s1);
break;
}
}
}
OUTPUT:
Program 14:
Display the future date

Algorithm:
Step 1: Start
Step 2: Enter the input month, date and year
Step 3: Enter the number of days to go ahead
Step 4: Check whether the year is leap year or not, if leap year add 29 days after
Feburary else add only 28 days after Feburary
Step 5: As we have checked how many days has being passed in that year, now
add the number of days to go ahead with it
Step 6: Now reduce every month’s days by subtracting with the number of days
in that particular month
Step 7: After reducing print the resultant month and date after moving ahead
Step 8: Print the year
Step 9: Stop
PROGRAM:
import java.util.*;
class Future_Date
{public static void main()
{Scanner sc=new Scanner (System.in);
System.out.println("Enter the input Month");
String mon=sc.nextLine();int no=0;
mon=mon.toLowerCase();int f=0;
System.out.println("Enter the input Date");
int date=sc.nextInt();
System.out.println("Enter the input Year");
int year=sc.nextInt();
System.out.println("Enter the Number of Days to go ahead");
int d_to_s=sc.nextInt();
mon=mon.trim();
if(year%4==0)
f=1;
if(mon.equals("january"))
no=date;
else if(mon.equals("feburary"))
no=date+31;
else if(mon.equals("march")&&f==1)
no=date+31+29;
else if(mon.equals("march")&&f!=1)
no=date+31+28;
if(mon.equals("april")&&f==1)
no=date+31+29+31;
else if(mon.equals("april")&&f!=1)
no=date+31+28+31;
if(mon.equals("may")&&f==1)
no=date+31+29+31+30;
else if(mon.equals("may")&&f!=1)
no=date+31+28+31+30;
if(mon.equals("june")&&f==1)
no=date+31+29+31+30+31;
else if(mon.equals("june")&&f!=1)
no=date+31+28+31+30+31;
if(mon.equals("july")&&f==1)
no=date+31+29+31+30+31+30;
else if(mon.equals("july")&&f!=1)
no=date+31+28+31+30+31+30;
if(mon.equals("august")&&f==1)
no=date+31+29+31+30+31+30+31;
else if(mon.equals("august")&&f!=1)
no=date+31+28+31+30+31+30+31;
if(mon.equals("september")&&f==1)
no=date+31+29+31+30+31+30+31+31;
else if(mon.equals("september")&&f!=1)
no=date+31+28+31+30+31+30+31+31;
if(mon.equals("october")&&f==1)
no=date+31+29+31+30+31+30+31+31+30;
else if(mon.equals("october")&&f!=1)
no=date+31+28+31+30+31+30+31+31+30;
if(mon.equals("november")&&f==1)
no=date+31+29+31+30+31+30+31+31+30+31;
else if(mon.equals("november")&&f!=1)
no=date+31+28+31+30+31+30+31+31+30+31;
if(mon.equals("december")&&f==1)
no=date+31+29+31+30+31+30+31+31+30+31+30;
else if(mon.equals("december")&&f!=1)
no=date+31+28+31+30+31+30+31+31+30+31+30;
int nod=no+d_to_s;
int nody=no+d_to_s;
int n=1;
while(((year%4==0&&nod<=366)||(year%4!=0&&nod<=365))==false)
{if(year%4==0&&nod>366)
{year=year+1;
nod=nod-366;
}
else if(year%4!=0&&nod>365)
{year=year+1;
nod=nod-365;
}
}
if(nod>31)
{while(nod>30)
{ if(n<=7)
{ if (n%2!=0)
{nod=nod-31;
n++;
}
else if(n%2==0)
{if (n==2&&year%4==0)
nod=nod-29;
else if(n==2&&year%4!=0)
nod=nod-28;
else
nod=nod-30;
n++;
}
}
else if(n>7&&n<=12)
{if(n%2==0)
{nod=nod-31;
n++;
}
else if (n%2!=0)
{nod=nod-30;
n++;
}
}
}
if (n==2&&year%4==0&&nod>29)
{ nod=nod-29;n++;}
else if (n==2&&year%4!=0&&nod>28)
{nod=nod-28;n++;}
}
if(nod!=0)
{if(n==1)
System.out.print("January\t"+nod);
if(n==2)
System.out.print("Feburary "+nod);
if(n==3)
System.out.print("March\t"+nod);
if(n==4)
System.out.print("April\t"+nod);
if(n==5)
System.out.print("May\t"+nod);
if(n==6)
System.out.print("June\t"+nod);
if(n==7)
System.out.print("July\t"+nod);
if(n==8)
System.out.print("August\t"+nod);
if(n==9)
System.out.print("September\t"+nod);
if(n==10)
System.out.print("October\t"+nod);
if(n==11)
System.out.print("November\t"+nod);
if(n==12)
System.out.print("December\t"+nod);
}
else
{if((n-1)==1)
System.out.print("Jaunary\t"+31);
if((n-1)==2)
System.out.print("Feburary\t"+31);
if((n-1)==3)
System.out.print("March\t"+31);
if((n-1)==4)
System.out.print("April\t"+31);
if((n-1)==5)
System.out.print("May\t"+31);
if((n-1)==6)
System.out.print("June\t"+31);
if((n-1)==7)
System.out.print("July\t"+31);
if((n-1)==8)
System.out.print("August\t"+31);
if((n-1)==9)
System.out.print("September\t"+31);
if((n-1)==10)
System.out.print("October\t"+31);
if((n-1)==11)
System.out.print("November\t"+31);
if((n-1)==12||(n-1)==0)
System.out.print("December\t"+31);
}
System.out.println("\t"+year);
}
}
OUTPUT:
Program 15:
Print date for the given number of days

Algorithm:
Step 1: Start
Step 2: Enter the number of days and the year
Step 3: Check whether the year is leap year or not. If leap year and no of days
exceeds 366 reduce the days by 366 and increase the year to next year else if not
leap year and no of days exceeds 365 reduce the days by 365 and increase the
year to next year.
Step 4: Compare each month with the no of days and reduce it with 30 or 31
accordingly.
Step 5: After finding the date, now find the month
Step 6: Print the <Date> <Month> <Year>
Step 7: Stop
PROGRAM:

import java.util.*;
class Date_of_Year
{public static void main()
{Scanner sc= new Scanner (System.in);
System.out.println("Enter the number of Days");
int nod=sc.nextInt();int nody=nod;
System.out.println("Enter the Year");
int year=sc.nextInt();
int n=1;
while(((year%4==0&&nod<=366)||(year%4!=0&&nod<=365))==false)
{if(year%4==0&&nod>366)
{year=year+1;
nod=nod-366;
}
else if(year%4!=0&&nod>365)
{year=year+1;
nod=nod-365;
}
}
if(nod>31)
{while(nod>30)
{ if(n<=7)
{ if (n%2!=0)
{nod=nod-31;
n++;
}
else if(n%2==0)
{if (n==2&&year%4==0)
nod=nod-29;
else if(n==2&&year%4!=0)
nod=nod-28;
else
nod=nod-30;
n++;
}
}
else if(n>7&&n<=12)
{if(n%2==0)
{nod=nod-31;
n++;
}
else if (n%2!=0)
{nod=nod-30;
n++;
}
}
}
if (n==2&&year%4==0&&nod>29)
{ nod=nod-29;n++;}
else if (n==2&&year%4!=0&&nod>28)
{nod=nod-28;n++;}
}
if(nod!=0)
{if(n==1)
System.out.print("January\t"+nod);
if(n==2)
System.out.print("Feburary "+nod);
if(n==3)
System.out.print("March\t"+nod);
if(n==4)
System.out.print("April\t"+nod);
if(n==5)
System.out.print("May\t"+nod);
if(n==6)
System.out.print("June\t"+nod);
if(n==7)
System.out.print("July\t"+nod);
if(n==8)
System.out.print("August\t"+nod);
if(n==9)
System.out.print("September\t"+nod);
if(n==10)
System.out.print("October\t"+nod);
if(n==11)
System.out.print("November\t"+nod);
if(n==12)
System.out.print("December\t"+nod);
}
else
{if((n-1)==1)
System.out.print("Janu ary\t"+31);
if((n-1)==2)
System.out.print("Feburary\t"+31);
if((n-1)==3)
System.out.print("March\t"+31);
if((n-1)==4)
System.out.print("April\t"+31);
if((n-1)==5)
System.out.print("May\t"+31);
if((n-1)==6)
System.out.print("June\t"+31);
if((n-1)==7)
System.out.print("July\t"+31);
if((n-1)==8)
System.out.print("August\t"+31);
if((n-1)==9)
System.out.print("September\t"+31);
if((n-1)==10)
System.out.print("October\t"+31);
if((n-1)==11)
System.out.print("November\t"+31);
if((n-1)==12||(n-1)==0)
System.out.print("December\t"+31);
}System.out.println("\t"+year);
}
}
OUTPUT:
Program 16:
Calendar generator

Algorithm:
Step 1: START
Step 2: Input Validation:
o Prompt the user to enter a year (year).
o If year < 1900, display an error message and terminate the
program.
Step 3: Determine if Leap Year:
o Use the isLeapYear(year) function:
 A year is a leap year if:
 (year % 4 == 0 AND year % 100 != 0) OR (year %
400 == 0).
 If isLeapYear is true, set the days of February to 29;
otherwise, set it to 28.
Step 4: Calculate the Starting Day of the Year:
o Use the getStartingDayOfYear(year) function:
 Initialize totalDays = 0.
 Loop through all years from 1900 to year - 1:
 Add 366 to totalDays if the year is a leap year;
otherwise, add 365.
 Compute the starting day of the year as startDay = totalDays
% 7.
 (0 = Sunday, 1 = Monday, ..., 6 = Saturday).
Step 5: Print Calendar for Each Month:
o Loop through all 12 months:
1. Display the month name.
2. Print the weekday headers (Sun Mon Tue Wed Thu Fri Sat).
3. Print leading spaces for the first week of the month (based on startDay).
4. Loop through all days in the current month:
 Print each day and align it properly.
 Update startDay = (startDay + 1) % 7.
 If startDay == 0 (Saturday), print a new line.
Step 7: Reset for Leap Year:
o After printing the calendar, reset February's days back to 28 for any
future use.
Step 8: Stop

PROGRAM:

import java.util.Scanner;
public class Calendar
{
static int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static String[] months = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};

public static boolean isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static int getStartingDayOfYear(int year) {
int totalDays = 0;

for (int i = 1900; i < year; i++) {


totalDays += isLeapYear(i) ? 366 : 365;
}

return totalDays % 7;
}
public static void printCalendar(int year) {

if (isLeapYear(year)) {
daysInMonth[1] = 29;
} else {
daysInMonth[1] = 28;
}

int startDay = getStartingDayOfYear(year);


System.out.println("Calendar for the year " + year + ":");
for (int i = 0; i < 12; i++) {
System.out.println("\n" + months[i]);
System.out.println("Mon Tue Wed Thu Fri Sat Sun");

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


System.out.print(" ");
}

for (int day = 1; day <= daysInMonth[i]; day++) {


System.out.printf("%3d ", day);
startDay = (startDay + 1) % 7;

if (startDay == 0) {
System.out.println();
}
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year (after 1900): ");
int year = scanner.nextInt();

if (year < 1900) {


System.out.println("Year must be after 1900!");
} else {
printCalendar(year);
}
}
}
OUTPUT:
Program 17:
Mirror Image of Array

Algorithm:
Step 1: Start
Step 2: Enter the size of the matrix and fill the matrix with elements
Step 3: Create a variable to store the row size and it is reduced everytime so as
to give the values to prior positions to form mirror matrix
Step 4: Create two for loop:
Outer- Column
Inner- Row
Step 5: Row loop goes till size/2 time iterations so that each time the elements is
changed to it’s mirror position in the array
Step 6: Print the final matrix
Step 7: Stop
PROGRAM:

import java.util.*;
class Mirror_Matrix
{public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Matrix");
int n=sc.nextInt();
int t=0;
int a[][]=new int[n][n];
System.out.println("Enter the Matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
a[i][j]=sc.nextInt();
for(int i=0;i<n;i++)
{int k=n-1;
for(int j=0;j<n/2;j++)
{ t=a[i][j];
a[i][j]=a[i][k];
a[i][k]=t;
k=k-1;
}
}
System.out.println("The Mirrored Matrix is:");
for(int i=0;i<n;i++)
{for(int j=0;j<n;j++)
System.out.print(a[i][j]);
System.out.println();
}
}
}

OUTPUT:
Program 18:
Fill the Array in spiral manner

Algorithm:
Step 1: Start
Step 2: Enter the size of the matrix
Step 3: Use a variable k=1 that increases every time its value has been assigned
Step 4: Store the before position from the last position of both row and column
Step 5: Now by using do while loop first fill the boundary positions
Step 6: Increase the lower limit variable by one and decrease the upper limit
variables by one
Step 7: Print the mtrix
Step 8: Stop
PROGRAM:

import java.util.*;
class Spiral_Matrix
{public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Matrix");
int n=sc.nextInt();
int a[][]=new int[n][n];
int k=1,i,j,c1=0,c2=n-1,r1=0,r2=n-1;
do
{ for(i=c1;i<=c2;i++)
a[r1][i]=k++;
for(j=r1+1;j<=r2;j++)
a[j][c2]=k++;
for(i=c2-1;i>=c1;i--)
a[r2][i]=k++;
for(j=r2-1;j>=r1+1;j--)
a[j][c1]=k++;
c1++;
c2--;
r1++;
r2--;
}while(k<=n*n);
System.out.println("Spiral filled Matrix:");
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
System.out.print(a[i][j]+”\t”);
System.out.println();
}
}
}

OUTPUT:
Program 19:
Print the Saddle point of a 2 dimensional array

Algorithm:
Step 1: Start
Step 2: Enter the size of the array
Step 3: give values to the matrix
Step 4: First take an element from a row and check whether it is the smallest in
that row. If it is the smallest then check whether it is the largest in its column
Step 5: Take each element and repeat the process
Step 6: Print the number which is smallest in the row and largest in the column
Step 7: Stop
PROGRAM:

import java.util.*;
class Saddle_point
{public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Matrix");
int n=sc.nextInt();
int m=sc.nextInt();
int f=0;
int a[][]=new int[n][m];
System.out.println("Enter the Matrix");
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=sc.nextInt();
for(int i=0;i<n;i++)
{ for(int j=0;j<m;j++)
{int min=a[i][j];int max=a[i][j];
for(int h=0;h<m;h++)
{if(a[i][h]<min)
min=a[i][h];
}
if(min==a[i][j])
{
for(int p=0;p<n;p++)
{if(a[p][j]>max)
max=a[p][j];
}
}
if(max==min)
{ System.out.println("Saddle point is:"+a[i][j]);
f=1;
break;
}else
continue;
}
if(f==1)
break;
}
if(f==0)
System.out.println("No Saddle Point");
}
}

OUTPUT:
Program 20:
Suduko

Algorithm:
Step 1: START
Step 2: Grid Generation:
 Create a 3x3 Sudoku grid with numbers 1, 2, 3 where each number
appears once in each row and column.
 Start by filling the grid with a predefined base row {1, 2, 3}.
 Generate subsequent rows by shifting the base row.
 Shuffle the rows and columns randomly to ensure different Sudoku grids.
Step 3: Puzzle Creation:
 Clone the solution grid into a puzzleGrid.
 Randomly remove 6 elements from the puzzle grid (set them to 0) to
create the puzzle.
Step 4: Game Play:
 Display the puzzle grid to the user with 0 representing empty cells.
 Prompt the user to enter a row, column, and number (between 1 and 3) to
fill an empty cell.
 If the user fills a correct cell, update the grid; otherwise, print an error
message.
 After each move, check if the puzzle grid matches the solution grid.
 If the grid is solved, display a success message and the final solved grid.
Step 5: Validation:
 Check if the puzzle grid is fully filled.
 Compare the user's grid with the solution to verify correctness.
Step 6: End Condition:
 The game ends when the grid is solved correctly.
PROGRAM:

import java.util.*;
class sudoko
{
public static int[][] generateGrid(int[][]grid)
{
int[] baseRow = {1, 2, 3};
for (int i = 0; i < 3; i++)
{
int shift = i;
for (int j = 0; j < 3; j++)

{
grid[i][j] = baseRow[(j + shift) % 3];
}
}
for (int i = 0; i < 3; i++)
{
int randomRow = (int) (Math.random() * 3);

for (int j = 0; j < 3; j++)


{
int temp = grid[i][j];
grid[i][j] = grid[randomRow][j];
grid[randomRow][j] = temp;
}
}
for (int j = 0; j < 3; j++)
{
int randomCol = (int) (Math.random() * 3);

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


int temp = grid[i][j];
grid[i][j] = grid[i][randomCol];
grid[i][randomCol] = temp;
}
}
return(grid);
}
static void removeElements(int[][] grid)
{
Random rand = new Random();
int removed = 0;
while (removed < 6)
{
int row = (int)(Math.random() * 3);;
int col = (int)(Math.random() * 3);;

if (grid[row][col] != 0)
{
grid[row][col] = 0;
removed++;
}
}
}
public static void printSudoku(int[][] grid)
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (grid[i][j] == 0) {
System.out.print(". ");
} else {
System.out.print(grid[i][j] + " ");
}
}
System.out.println();
}
}
public static boolean isCorrect(int[][] originalGrid, int[][] userGrid)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (userGrid[i][j] != 0 && userGrid[i][j] != originalGrid[i][j]) {
return false;
}
}
}
return true;
}
public static boolean isArrayFull(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if (array[i][j] == 0) {
return false;
}
}
}
return true;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int[][] grid = new int[3][3];
int[][] solutionGrid = generateGrid(grid);
int[][] puzzleGrid = new int[3][3];

for (int i = 0; i < solutionGrid.length; i++)


{
for (int j = 0; j < solutionGrid[i].length; j++)
{
puzzleGrid[i][j] = solutionGrid[i][j];
}
}
removeElements(puzzleGrid);
System.out.println("Welcome to the 3x3 Sudoku Game!");
System.out.println("Fill in the empty cells with numbers 1-3.");
while(isArrayFull(puzzleGrid)==false)
{
boolean solved = false;
while (!solved)
{
System.out.println("Current Sudoku Grid:");
printSudoku(puzzleGrid);
System.out.println("Enter row (0-2), column (0-2), and number (1-3)
separated by spaces:");
int row = scanner.nextInt();
int col = scanner.nextInt();
int num = scanner.nextInt();
if (puzzleGrid[row][col] == 0 && num >= 1 && num <= 3)
{
puzzleGrid[row][col] = num;
} else
{
System.out.println("Invalid input or position already filled. Try
again.");
}
if (isCorrect(solutionGrid, puzzleGrid))
{
solved = true;
System.out.println("Congratulations! You solved the Sudoku!");
printSudoku(puzzleGrid);
}
else
{
System.out.println("Wrong choice. Try again.");
puzzleGrid[row][col] = 0;
}
}
}
}
}
OUTPUT:
Program 21:
NCR calculation using Recursion

Algorithm:
Step 1: Start
Step 2: Enter the values for N and R
Step 3: if R was greater than N then NCR could not be calculated
Step 4: Find the factorial of N, R and N-R using the “fact” function
Step 5: “fact” is a recursive function. To find factorial using recursion, every
number from that number to one is to be multiplied. When the recursive number
reaches 1 return 1 so that all the number would be multiplied giving the factorial
Step 6: To find NCR, use formula, NCR=R!/(N!*(R-N)!)
Step 7: Stop
PROGRAM:

import java.util.*;
class NCR
{
static int fact(int n)
{
if(n>1)
{
return(n*fact(n-1)) ;
}
else
{
return (1);
}
}

public static void main()


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter values for N and R");
int num=sc.nextInt();
int r=sc.nextInt();
if(r>num)
{System.out.println("Math Error");
System.exit(0);
}
int k=num-r;
int R=fact(num);
int NUM=fact(r);
int K=fact(k);
double factorial=(R/(NUM*K));
System.out.println("NCR of "+num+" and "+r+" is "+factorial);
}
}

OUTPUT:
Program 22:
Palindrome word and number generation

Algorithm:
Step 1: Start
Step 2: Print “for palindrome number press A and palindrome word press B”
Step 3: Using switch case confirm whether to generate palindrome word or
number from the user
Step 4: For palindrome number ask the user for range
Step 5: Give the limits of the range in a for loop and reverse each number in the
while loop
Step 6: If the number is equal to the reversed number then print it, else
concatenate the reversed number with the original number by excluding the first
number of the reversed number and print it
Step 7: For palindrome word ask the user or input word
Step 8: Reverse the word using a for loop
Step 9: If the reversed word is equal to the input word then print it, else
concatenate the reversed word with the original word by excluding the first
letter of the reversed word using substring function and print it
Step 10: Stop
PROGRAM:

import java.util.*;
class Palindrome_num_word
{
public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("If u want to convert a number into Palindrome number
Press 'A' \nIf u want to convert a word into Palindrome word Press 'B'");
char ch=sc.next().charAt(0);
switch(ch)
{case 'A':
System.out.println("Enter the number range");
int n=sc.nextInt();
int m=sc.nextInt();
for(int i=n;i<=m;i++)
{int a=i;
int b=a;
int c=0;
int rev=0;
while(b>0)
{rev=rev*10+b%10;
b=b/10;
c++;
}
if(rev==a)
System.out.println(a);
else
{
rev=rev%(int)Math.pow(10,c-1);
a=a*(int)Math.pow(10,c-1)+rev;
System.out.println(a);
}
}
break;
case 'B':
System.out.println("Enter the word");
String s=sc.next();
String rev="";
for(int i=0;i<s.length();i++)
rev=s.charAt(i)+rev;
if(rev.equals(s))
System.out.println(s);
else
System.out.println(s+""+rev.substring(1));
break;
}
}
}
OUTPUT:
Program 23:
HCF and LCM of two number using recursion

Algorithm:
Step 1: Start
Step 2: Enter the numbers
Step 3: To find HCF pass the 2 numbers to ”findHCF” function
Step 4: In that function check whether the 2nd number is equal to zero
Step 5: Till the 2nd number becomes zero return the 2nd number and 1st
number%2nd number values
Step 6: If the 2nd number passing becomes zero then return the first number
Step 7: Return the HCF value of the numbers
Step 8: To find the LC pass three value to the “findLCM” function, 2 numbers
and the greatest number between the two numbers
Step 9: Inside the function check whether the 2 numbers are divisible by the
greatest number
Step 10: If both the numbers are divisible then return the greatest number as
LCM else again call the function with the values of 2 numbers and the (greatest
number+1)
Step 11: Return the LCM value of the two numbers
Step 12: Print the HCF and LCM of the two numbers
Step 13: Stop
PROGRAM:

import java.util.*;
class HCF_LCM
{static int findHCF(int a, int b)
{
if (b == 0) {
return a;
}
return findHCF(b, a % b);
}
public static int findLCM(int a, int b, int multiple)
{
if (multiple % a == 0 && multiple % b == 0)
{
return multiple;
}
return findLCM(a, b, multiple + 1);
}
public static void main()
{Scanner sc=new Scanner(System.in);
System.out.println("Enter the numbers");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int hcf = findHCF(num1, num2);
int lcm = findLCM(num1, num2, Math.max(num1, num2));
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
System.out.println("HCF of " + num1 + " and " + num2 + " is: " + hcf);
}
}

OUTPUT:
Program 24:
Students Marks Management using Inheritance

Algorithm:
Step 1: Start
Step 2: Input the number of students
1. Start the program.
2. Prompt the user to input the total number of students (totalStudents).
3. Create an array of StudentManagement objects of size totalStudents.

Step 3: Initialize student details


1. For each student i (from 0 to totalStudents - 1):
o Create a StudentManagement object.
o Prompt the user to input:
 Roll number.
 Name.
 Number of subjects.
 Marks for each subject.
o Store these details in the object.
Step 4: Display menu
o Display the following menu repeatedly until the user chooses to
exit:
o mathematics
o Copy code
Step 5: Process user choice
1. If the user chooses option 1 (Search Student by Roll Number):
o Prompt the user to enter a roll number (searchRollNumber).
o Initialize a flag found to false.
o For each student in the array:
 Check if the roll number matches searchRollNumber.
 If a match is found:
 Display the student's details (roll number, name, and
marks).
 Set found to true and break the loop.
o If no match is found (found == false), display "No student found
with Roll Number: searchRollNumber."
2. If the user chooses option 2 (Exit):
o Display "Exiting the program. Goodbye!" and terminate the
program.
3. If the user enters an invalid choice:
o Display "Invalid choice! Please try again."
Step 6: Stop

PROGRAM:

import java.util.Scanner; // Parent class to initialize student details


class Student
{
protected String[] studentNames;
protected int[][] studentMarks;
protected int[] rollNumbers;
protected int totalStudents;
public Student(int totalStudents)
{
this.totalStudents = totalStudents;
studentNames = new String[totalStudents];
studentMarks = new int[totalStudents][];
rollNumbers = new int[totalStudents];
}
public void initializeStudents()
{
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < totalStudents; i++) {
System.out.println("Enter details for student " + (i + 1));
System.out.print("Enter Roll Number: ");
rollNumbers[i] = scanner.nextInt();
scanner.nextLine(); // Consume the newline
System.out.print("Enter Name: ");
studentNames[i] = scanner.nextLine();
System.out.print("Enter number of subjects: ");
int subjects = scanner.nextInt();
studentMarks[i] = new int[subjects];
System.out.println("Enter marks for " + subjects + " subjects:");
for (int j = 0; j < subjects; j++) {
System.out.print("Mark " + (j + 1) + ": ");
studentMarks[i][j] = scanner.nextInt();
}
}
}
}
// Child class to access student details using roll number
class StudentManagement extends Student
{
public StudentManagement(int totalStudents)
{
super(totalStudents);
}
public void displayStudentByRollNumber(int rollNumber) {
boolean found = false;
for (int i = 0; i < totalStudents; i++) {
if (rollNumbers[i] == rollNumber) {
found = true;
System.out.println("Details for Roll Number " + rollNumber + ":");
System.out.println("Name: " + studentNames[i]);
System.out.print("Marks: ");
for (int mark : studentMarks[i]) {
System.out.print(mark + " ");
}
System.out.println();
break;
}
}
if (!found) {
System.out.println("Student with Roll Number " + rollNumber + " not
found.");
}
}
}
// Main class to manage the program flow
public class StudentMarkManagement
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int totalStudents = scanner.nextInt();
StudentManagement studentManagement = new
StudentManagement(totalStudents);
studentManagement.initializeStudents();
while (true)
{
System.out.println("\nMenu:");
System.out.println("1. Display Student Details by Roll Number");
System.out.println("2. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

switch (choice)
{
case 1:
System.out.print("Enter Roll Number to search: ");
int rollNumber = scanner.nextInt();
studentManagement.displayStudentByRollNumber(rollNumber);
break;
case 2:
System.out.println("Exiting the program. Goodbye!");
return;
default:
System.out.println("Invalid choice! Please try again.");
}
}
}
}
OUTPUT:
Program 25:
STACK and QUEUE implementation

Algorithm:
Step 1: Start
Step 2: Have s[], sp, q[], f, r and size as data members
Step 3: Print “S-Stack Implementation; Q-Queue implementation”
Step 4: To push a data into stack, call the function “pushdata”
Step 5: Check for underflow
Step 6: Increase the stack pointer
Step 7: Push the data into the stack
Step 8: To pop a data in a stack, call the function “popdata”
Step 9: Check for underflow
Step 10: Pop out the element
Step 11: Reduce to stack pointer
Step 12: Display the stack
Step 13: To insert a data into a queue, call the function “insertqueue”
Step 14: Check for overflow
Step 15: If the Queue is empty then make both front and rear pointer 0 else
increase the rear pointer by 1
Step 16: Insert the element to the queue
Step 17: To delete a data into a queue, call the function “deletequeue”
Step 18: Check for underflow
Step 19: Delete the element from the front position of the queue
Step 20: If front and rear pointer are equal make both the pointer to -1, else
increase the front pointer by 1
Step 21: Display the queue
Step 22: Stop
PROGRAM:

import java.util.*;
class stackqueue
{
int s[]=new int[20];
int sp;
int q[]=new int[20];
int f=-1,r=-1,size=20;

void pushdata(int item)


{if(sp==(20-1))
System.out.println("Stack Overflows");
else
{sp++;
s[sp]=item;
}
}

void popdata()
{int v;
if(sp==-1)
System.out.println("Stack Underflows");
else
{v=s[sp];
System.out.println("Popped out element is "+v);
sp--;
}
}

void display()
{if(sp==-1)
System.out.println("Stack is Empty");
else
{System.out.println("SP-----> |"+s[sp]+"|");
System.out.println(" ____");
for(int i=sp-1;i>0;i--)
{System.out.println(" |"+s[i]+"|");
System.out.println(" ____");
}
}
}

void insertqueue(int item)


{if(r==size-1)
System.out.println("Queue Overflows");
else
{if(f==-1 && r==-1)
{f=0;
r=0;
}
else
r=r+1;
q[r]=item;
}
}

void deletequeue()
{if(f==-1&& r==-1)
System.out.println("Queue Underflows");
else
{int val=q[f];
if(f==r)
{f=-1;
r=-1;
}
else
f=f+1;
}
}

void display2()
{if(f==-1&& r==-1)
System.out.println("Queue Underflows");
else
{System.out.println("Elements of the queue:");
for(int j=f;j<=r;j++)
System.out.print(q[j]+" ");
}
}
public static void main()
{Scanner sc=new Scanner(System.in);
stackqueue ob=new stackqueue();
System.out.println("Press 'S' for Stack Implementation and Press 'Q' for
Queue Implementation");
String ch=sc.next();
switch(ch)
{case "S":
System.out.println("Enter how many numbers to be added to the
Stack");
int kn=sc.nextInt();
int a[]=new int[kn];
System.out.println("Enter the Elements");
for(int i=0;i<kn;i++)
{a[i]=sc.nextInt();
ob.pushdata(a[i]) ;
}ob.display();
System.out.println("If you want to continue to pop a data Press 'c' else
Press 'n'");
String cc=sc.next();
if(cc.equals("c"))
{
ob.popdata();
ob.display();
break;
}
else
break;
case "Q":
System.out.println("Enter how many numbers to be added to the
Queue");
int hn=sc.nextInt();
int b[]=new int[hn];
System.out.println("Enter the Elements");
for(int i=0;i<hn;i++)
{b[i]=sc.nextInt();
ob.insertqueue(b[i]) ;
}
ob.display2();
System.out.println("\nIf you want to continue to Delete an
Element Press 'c' else Press 'n'");
String ccc=sc.next();
if(ccc.equals("c"))
{ob.deletequeue();
ob.display2();
}

}
}
}
OUTPUT:

You might also like