0% found this document useful (0 votes)
303 views

Kaprekar Number

The program accepts a day number between 1 and 366, a year, and a number N between 1 and 100 from the user. It uses the inputs to generate the date corresponding to the day number and year. It then computes the date that is N days in the future and displays both dates. Any values outside the allowed ranges produce an error message.

Uploaded by

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

Kaprekar Number

The program accepts a day number between 1 and 366, a year, and a number N between 1 and 100 from the user. It uses the inputs to generate the date corresponding to the day number and year. It then computes the date that is N days in the future and displays both dates. Any values outside the allowed ranges produce an error message.

Uploaded by

ashwinsiva.2k23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 107

Kaprekar Number

Question: 1

Kaprekar number: When a number having ‘d’ digits is squared and the sum of the two
halves, left and right (in such a way that the left part has ‘d’ digits and the right part has ‘d’
or ‘d-1’ digits) in the square is equal to the number itself, it is called a Kaprekar number.
Example: 9, as 9x9=81 and 8+1=9.

Aim:
To accept a number and check whether the number is a kaprekar number or not.

Program:

import java.util.*;

class kaprekarNumber

static boolean check(int num, int n){

String s = Integer.toString(n);

if(s.length()>=2){

int mid = s.length()/2;

String f = s.substring(0,mid);

String t = s.substring(mid);

int n1 = Integer.valueOf(f) + Integer.parseInt(t);

if (num == n1)

return true;

else

return false;

else
return false;

static void main(String args[])

Scanner in = new Scanner(System.in);

System.out.println("Enter the number to be checked”);

int n = in.nextInt();

if(check(n,(n*n)))

System.out.println("Kaperkar number!");

else

System.out.println("Not a kaperkar number");

Output:
Lucky Number
Question: 2

Lucky number: In a sequence of natural numbers, if every second number is removed, and
then from the remaining numbers every third number is removed, and so on, some
numbers remain indefinitely in the list. Such numbers are called lucky numbers.
Example: 1,2,3,4,5,6,7,8,9,10.
After removing each second number, 1,3,5,7,9
After removing each third number, 1,3,7 => These are lucky numbers within range 10

Aim:
To accept a number and check whether the number is a Lucky number or not.

Program:
import java.util.*;
public class Lucky
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print(“Enter the number of elements: “);
int n=sc.nextInt();
int arr[]=new int[n];
int elements=n;
for(int i=0;i<n;i++)
{
arr[i]=i+1;
}
int del=1;
while(del<n)
{
for(int i=del; i<n; i+=del)
{
for(int j=i; j<n-1; j++)
{
arr[j]=arr[j+1];
}
n--;
}
del++;
}
System.out.print(“Hence, the Lucky Numbers Less than “+elements+” are: “);
for(int i=0; i<n; i++)
{
System.out.print(arr[i]+” “);
}
}
}
Output:
Prime Adam
Question: 3

Prime Adam: A Prime-Adam integer is a positive integer (without leading zeros)


which is a prime as well as an Adam number.
Prime number: A number which has only two factors, i.e. 1 and the number
itself.
Example: 2, 3, 5, 7 … etc.
Adam number: The square of a number and the square of its reverse are reverse to
each other.
Example: If n = 13 and reverse of 'n' = 31, then,
(13)2 = 169
(31)2 = 961 which is reverse of 169 thus
13, is an Adam number.
Accept two positive integers m and n, where m is less than n as user input.
Display all Prime-Adam integers that are in the range between m and n (both
inclusive) and display the output.

Aim:
To accept a number and check whether the number is a PrimeAdam number or not.

Program:

import java.util.Scanner;

class PrimeAdam

static int reverse(int num)

int rev = 0;

while (num != 0)

{
int d = num % 10;

rev = rev * 10 + d;

num = num / 10;

return rev;

static boolean isAdam(int num)

int sqNum = num * num;

int revNum = reverse(num);

int sqRevNum = revNum * revNum;

int rev = reverse(sqNum);

return rev == sqRevNum;

static boolean isPrime(int num)

int c = 0;

for (int I = 1; I <= num; i++)

if (num % I == 0)

c++;

}
}

return c == 2;

static void main(String args[])

Scanner in = new Scanner (System.in);

System.out.println(“Enter number to be checked”);

int n = in.nextInt();

if(isAdam(n)&& isPrime(n))

System.out.println(n + “ is a prime Adam number”);

else

System.out.println(n + “ is not a prime Adam number”);

Output:
Mobius Function
Question: 4

Mobius function: The MOBIUS function M(N) for a natural number N is defined as follows:
1. M(N) = 1 if N = 1
2. M(N) = 0 if any prime factor of N is contained in N more than once
3. M(N) = (-1)p if N is a product of ‘p’ distinct prime factors Example :
M(78) = -1 ( for 78 = 2 * 3 * 13 M(78) = ( -1)3 = -1 )
M(34) = 1 ( for 34 = 2 * 17 M(34) = ( -1)2 = 1 )
Aim:
To accept a number and check whether the number is a Lucky number or not.
Program:
import java.util.*;
class Mobius
{
static boolean isPrime(int n)
{
int n1,i,k = 0;
n1 = n/2;
if(n==0||n==1)
return false;
else
{
for(i = 2; i <= n1; i++)
if(n%i == 0)
k++;
if(k==0)
return false;
else
return true;
}
}
static int mobiusf(int n)
{
if(n==1)
return(1);
int p=0;
for (int i=1;i<=n;i++)
{
if (n%i==0 && isPrime(i))
{
if (n % (i * i) == 0)
return 0;
else
p++;
}
}
return (p%2==0) ? 1 : -1;
}

static void main(String args[])


{
Scanner in = new Scanner(System.in);
System.out.println("Enter the number to return the mobius number");
int n = in.nextInt();
System.out.println("M(n) = " +mobiusf(n));
}
}
Output:
GoldBach
Question: 5

A Goldbach number is a positive even integer that can be expressed as the


sum of two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example: 6 = 3 + 3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs,
i.e. 3 and 7, 5 and 5.
Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all
the odd prime pairs whose sum is equal to the number ‘N’.

Aim:
To accept a number and check weither the number is goldbash number or not.

Program:

import java.util.*;

class Goldbach

static void main(String args[])

Scanner sc= new Scanner(System.in);

int i, j, n, k, b=0, c=0, sum=0;

System.out.println(“Enter the Number: “);

int num=sc.nextInt();

if(num!>9&&num!<50)

System.out.println(“Number must be less than 50 and greater than 9.”);

else{
k=num;

int arr1[]=new int[num];

int arr2[]=new int[num];

if(num%2!=0)

System.out.println(“Invalid Input, Number is Odd.”);

else

for(i=1;i<=num;i++)

for(j=1;j<=i;j++)

if(i%j==0)

c++;

if((c==2)&&(i%2!=0))

arr1[b]=i;

arr2[b]=i;

b++;

c=0;

System.out.println(“Odd and Prime Pairs are: “);


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

for(j=i;j<b;j++)

sum=arr1[i]+arr2[j];

if(sum==k)

System.out.print(arr1[i]+” , “+arr2[j]);

System.out.println();

System.out.println(k+” is a Goldbach number.”);

Output:
Date Calculate
Question: 6

Design a program to accept a day number (between 1 and 366), year (int digits) from the
user to generate and display the corresponding date. Also, accept ‘N’ (1 <= N <= 100) from
the user to compute and display the future date corresponding to ‘N’ days after the
generated ate.Display an error message if the value of the day number, year and N are not
within the limit or not according to the condition specified

Aim:
To accept a number and year and compute the date of the following number.

Program:

import java.util.Scanner;

class DateCalculator

static boolean isLeapYear(int y) {

boolean ret = false;

if (y % 400 == 0) {

ret = true;

else if (y % 100 == 0) {

ret = false;

else if (y % 4 == 0) {
ret = true;

else {

ret = false;

return ret;

static String computeDate(int day, int year) {

int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

String monthNames[] = {“JANUARY”, “FEBRUARY”, “MARCH”,

“APRIL”, “MAY”, “JUNE”,

“JULY”, “AUGUST”, “SEPTEMBER”,

“OCTOBER”, “NOVEMBER”, “DECEMBER”};

boolean leap = isLeapYear(year);

if(leap) {

monthDays[1] = 29;

int daySum = 0;

for int i = 0; i < monthDays.length; i++) {

daySum += monthDays[i];

if (daySum >= day) {

break;
}

int date = day + monthDays[i] – daySum;

StringBuffer Sb = new StringBuffer();

Sb.append(date);

Sb.append(“TH “);

Sb.append(monthNames[i]);

Sb.append(“, “);

Sb.append(year);

return Sb.toString();

static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print(“DAY NUMBER: “);

int dayNum = in.nextInt();

System.out.print(“YEAR: “);

int year = in.nextInt();

System.out.print(“DATE AFTER (N DAYS): “);

int n = in.nextInt();

if (dayNum < 1 || dayNum > 366) {

System.out.println(“DAY NUMBER OUT OF RANGE”);


return;

if (n < 1 || n > 100) {

System.out.println(“DATE AFTER (N DAYS) OUT OF RANGE”);

return;

String dateStr = computeDate(dayNum, year);

int nDays = dayNum + n;

int nYear = year;

boolean leap = isLeapYear(year);

if (leap && nDays > 366) {

nYear = nYear + 1;

nDays = nDays – 366;

else if (nDays > 365) {

nYear = nYear + 1;

nDays = nDays – 365;

String nDateStr = computeDate(nDays, nYear);

System.out.println();
System.out.println(“DATE: “ + dateStr);

System.out.println(“DATE AFTER “ + n

+ “ DAYS: “ + nDateStr);

Output:
Mirror Matrix
Question: 7

Write a program in Java to enter natural numbers in a double dimensional array m x n


(where m is the number of rows and n is the number of columns). Display the new matrix
in such a way that the new matrix is the mirror image of the original matrix.

Aim:
To accept a element in double dimensional array and display the orginal matrix and mirror
matrix

Program:

import java.util.*;

class HelloWorld {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println(“Enter no. of rows”);

int m = in.nextInt();

System.out.println(“Enter no. of columns”);

int n = in.nextInt();

int mat[][]= new int[m][n];

System.out.println(“Enter the elements of the matrix”);

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

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

mat[i][j]= in.nextInt();
}

System.out.println(“Original Matrix:”);

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

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

System.out.print(mat[i][j]+ “\t”);

System.out.println();

System.out.println();

System.out.println(“Mirror matrix:”);

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

for(int j=(n-1);j>-1;j--)

System.out.print(mat[i][j]+ “\t”);

System.out.println();

}
Output:
Saddle Point
Question: 8

Saddle point: Saddle point of a matrix is the lowest element in row, which is also the
maximum element in the column. WAP to get in out for a matrix of order mxn and print the
saddle point of it.

Aim:
To accept a order of matrix mxn and get the input for elements, then find and print the saddle
point of the matrix.

Program:

import java.util.*;

class HelloWorld {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter no. of rows");

int m = in.nextInt();
System.out.println("Enter no. of columns");

int n = in.nextInt();

int mat[][]= new int[m][n];

System.out.println("Enter the elements of the matrix");

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

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

mat[i][j]= in.nextInt();

System.out.println("Original Matrix:");

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

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

System.out.print(mat[i][j]+ "\t");

System.out.println();

System.out.println();

System.out.println("Saddle Point: " + mat[m-1][0]);

Output:
Magic Square
Question: 9

Magic square: A square matrix is said to be a magic square if the sum of each row, each
column and each diagonal is the same. WAP to accept the order of matrix ‘n’ and create a
magic square and finally display it.

Aim:
To accept a order of matrix n and create a magic square and finally display it.

Program:
public class MagicSquare
{
public void makeSquare(int s)
{
int magicSqr[][] = new int[s][s];
int r = s / 2;
int c = s – 1;
for (int no = 1; no <= s * s;)
{
if (r == -1 && c == s)
{
c = s – 2;
r = 0;
}
else
{
if (c == s)
{
c = 0;
}
if (r < 0)
{
r = s – 1;
}
}
if (magicSqr[r][c] != 0)
{
c = c – 2;
r = r + 1;
continue;
}
else
{
magicSqr[r][c] = no;
no = no + 1;
}
c = c + 1;
r = r – 1;
}
System.out.println(“The Magic Square for “ + s + “: \n”);
System.out.println(“Sum of each column or row “ + s * (s * s + 1) / 2 + “: \n”);
for (r = 0; r < s; r++)
{
for (c = 0; c < s; c++)
{
System.out.print(magicSqr[r][c] + “ “);
}
System.out.println();
}
}

public static void main(String[] argvs)


{
Scanner in = new Scanner(System.in);
System.out.println(“Enter no. of rows”);
Int n = in.nextInt();
MagicSquare obj = new MagicSquare();
obj.makeSquare(n);
}
}
Output:
Circular Matrix
Question: 10

Aim:
To accept a order of matrix n and get the input for elements and arrage it in a circular manner.

Program:
import java.util.*;
class circu {

static int MAX = 100;


public static void spiralFill(int m, int n, int a[][]) {
int val = 1;
int k = 0, l = 0;
while (k < m && l < n) {
for (int i = l; i< n; ++i) {
a[k][i] = val++;
}
k++;
for (int i = k; i < m; ++i) {
a[i][n – 1] = val++;
}
n--;
if (k < m) {
for (int i= n – 1; i >= l; --i) {
a[m – 1][i] = val++;
}
m--;
}
if (l < n) {
for (int i = m – 1; i >= k; --i) {
a[i][l] = val++;
}
l++;
}
}
}

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
System.out.println(“Enter no. of rows”);
int m = in.nextInt();
System.out.println(“Enter no. of columns”);
int n = in.nextInt();
int a[][] = new int[MAX][MAX];
spiralFill(m, n, a);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + “ “);
}
System.out.println();
}
}
}
Output:
Transpose Matrix
Question: 11

Aim:
To accept a order of matrix n and get the input for elements and find the transpose of the
matrix

Program:

import java.util.*;

class HelloWorld {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println(“Enter no. of rows”);

int m = in.nextInt();

System.out.println(“Enter no. of columns”);

int n = in.nextInt();

int mat[][]= new int[m][n];


System.out.println(“Enter the elements of the matrix”);

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

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

mat[i][j]= in.nextInt();

System.out.println(“Original Matrix:”);

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

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

System.out.print(mat[i][j]+ “\t”);

System.out.println();

System.out.println();

System.out.println(“Tranposed Matrix: “);

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

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

System.out.print(mat[j][i]+ “\t”);

System.out.println();

}
Output:
Symmetric Matrix
Question: 12

Write a program to declare a square matrix A[][] of order MxM where ‘M’ is the number of
rows and the number of coloumns, such that Must be greater than 2 and less than 10.
Accept the value of M as user input. Display an appropriate message for invalid input.
Allow the user to input integers into this matrix. Perform the following tasks:
A) Display the original matrix.
B) Check if the given matrix is Symmetric or not. A square matrix is said to be
Symmetric, if the element of the ith row and the jth column is equal to the element
of jth row and the ith column.
C) Find the sum of the elements of left diagonal and the sum of the elements if right
diagonal of the matrix and display them. Example :
Aim:
To accept a order of matrix n and get the input for elements and check if the matrix is
symmetric or not and find sum of its diagonals

Program:
import java.io.*;
class Symm
{
int left=0,right=0,m,I,j, arr[][];
boolean bool=false;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeValues() throws Exception
{
System.out.println(“Enter the value of ‘m’;”);
m=Integer.parseInt(br.readLine());
if(m>=10)
{
System.out.println(“Matrix size is out of range”);
return;
}
arr=new int[m][m];
for(i=0;i<m; i++)
{
for(j=0;j<m;j++)
{
System.out.println(“value:”);
arr[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println(“Original Matrix\n”);
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
System.out.print(“ “+arr[i][j]);
}
System.out.println();
}
for(i=0;I < m ; i++)
{
for(j=0;j<m; j++)
{
if(arr[i][j]!=arr[j][i])
{
bool=true;
break;
}
}
if(bool==true)
break;
}
if(bool)
System.out.println(“The given matrix is not symmetric”);
else
System.out.println(“The given matrix is symmetric”);
for(i=0;i<m ; i++)
{
for(j=0;j<m; j++)
{
if(i==j)
left=left+arr[i][j];
if(i+j==m-1)
right=right+arr[i][j];
}
}
System.out.println(“Sum of the left diagonal=”+left);
System.out.println(“Sum of the right diagonal=”+right);
}

public static void main(String args[])throws Exception


{
Symm ob=new Symm();
ob.takeValues();
}
}
Output:
Matrix Multiplication
Question: 13

WAP in Java to get two matrices of order mxn and pxq, and check for multiplication
compatibility. If they are compatible, multiply both and display the product matrix. Else,
display an appropriate message that the matrices are non-compatible.

Aim:
To input two different matrices and check for the multiplication compatibility and if they
are compatible then want to multiply both and display the product matrix
Program:
Import java.util.*;
public class MatrixMultiplicationExample {

public static void main(String args[]) {


int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print(“Enter number of rows in first matrix: “);
row1 = s.nextInt();
System.out.print(“Enter number of columns in first matrix: “);
col1 = s.nextInt();
System.out.print(“Enter number of rows in second matrix: “);
row2 = s.nextInt();
System.out.print(“Enter number of columns in second matrix: “);
col2 = s.nextInt();
if (col1 != row2) {
System.out.println(“Matrix multiplication is not possible”);
return;
}
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
System.out.println(“\nEnter values for matrix A : “);
for (int I = 0; I < row1; i++) {
for (int j = 0; j < col1; j++)
a[i][j] = s.nextInt();
}
System.out.println(“\nEnter values for matrix B : “);
for (int I = 0; I < row2; i++) {
for (int j = 0; j < col2; j++)
b[i][j] = s.nextInt();
}
System.out.println(“\nMatrix multiplication is : “);
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
c[i][j] = 0;
for (int k = 0; k < col1; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + “ “);
}
System.out.println();
}
}
}

Text File Sorting


Question: 14
WAP to accept 10 names and store it in a text file names names.txt. Sort the names
alphabetically and store it in another text file with the name order.txt.

Aim:
To accept 10 names and store in a text file in names.txt and sort the name alphabetically and
store it in another text file orde.txt

Program:
import java.io.*;
class Txt_Sort {
public static void main(String[] args)
{
Scanner in = new Scanner(“System.in);
System.out.println(“Enter no. of entries”);
int n = in.nextInt();
String names[] = new names[n];
System.out.println(“Enter the names”);
for(int i=0;i<n;i++)
names = in.next;
String temp;
for (int i = 0; i < n; i++) {
for (int j = I + 1; j < n; j++) {
if (names[i].compareTo(names[j]) > 0) {
Temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.println( “The names in alphabetical order are: “);
for (int i = 0; i < n; i++) {
System.out.println(names[i]);
}
}
}

Product Code
Question: 15

A binary file named "ABC.DAT" contains the product code, unit price and quantity for
number of items. Write a method to accept a product code 'p' and check the availability of
the product and display with an appropriate message. The method declaration is as
follows. void findpro(int p)

Aim:
To accept number items and store their product code, uint price and quantity and then check
the availability of the product and want to display appropriate message

Program:

import jaava.util.*;

import java.io.*;

class product

int pc,q,up;

Scanner sc=newScanner(System.in);

public void main()

input();
findpro(int p);

public void input ()

System.out.print(“Enter product Detail as pc,p and up”);

pc=sc.nextint();

q=sc.nextint();

up=sc.nextint();

public void findpro( int n)

try

File reader fr=new File Reader(“ABBC.DAT”);

BufferedReader br=BufferedReader(fr);

do

pc = be.readline();

while(pc==””)

System.out.println(on);
System.out.printin(q);

System.out.printin(up);

Catch(Exception e)

System.out.println(e);

Caesar Cipher
Question: 16

Caesar cipher: Caesar cipher is an encryption method which rotates each letter by 13
places. The symbols are left unchanged.
Example: INPUT: Hello! How are you? OUTPUT: Uryyb! Ubj ner lbh?

Aim:
To accept a String and encrypt the string by rotating each letter by 13 places.

Program:
import java.util.*;
class CaesarCipher
{
static char encrypt(int n){
if(n>=65 && n<=78 || n>=97 && n<=110)
n+=13;
else if(n>=78 && n<=90 || n>=110 && n<=122)
n-=13;
return (char)n;
}

static String word(String s){


String str ="";
for(int i=0;i<s.length();i++){
char c = encrypt((int)s.charAt(i));
str += c;
}
return str;
}

static void main(String args[]){


Scanner in = new Scanner(System.in);
System.out.println("Enter the String to encrypt");
String sent = in.nextLine();
String str="";
StringTokenizer s = new StringTokenizer(sent);
int count = s.countTokens();
for(int i=0;i<count;i++){
str += word(s.nextToken()) + " ";
}
System.out.println("String : " +str);
}
}

Word Count
Question: 17

Word count: Accept a paragraph of text and count the number of words in each sentence,
separated by ‘.’, ‘!’ or ‘?’. Example: Apple is a fruit. It is sweet! Number of words in ‘Apple
is a fruit’: 4. Number of words in ‘It is sweet!’: 3

Aim:
To accept a paragraph and count the number of words in each sentence.

Program:
import java.util.*;
class wordc
{
static int wc(String y)
{
int c = 0;
for(int i = 0;i<y.length();i++)
{
if(y.charAt(i)==' ')
c++;
}
return c;
}
static void sep(String s)
{
String t = "";
for(int i = 0;i<s.length();i++)
{
char c = s.charAt(i);
int u = (int)c;
t+=c;
if(u==33||u==46||u==63)
{
System.out.println("No of words in "+t+": " +wc(t));
t="";
}
}
}
static void main()
{
Scanner in = new Scanner (System.in);
System.out.println("ENTER A STRING");
String y = in.nextLine();
sep(y);
}

Sentence Rearrange
Question: 18

Write a program to accept a sentence which may be terminated by either ‘.’ , ‘?’ or ‘!’ only.
The words are to be separated by a single blank space and are in UPPER CASE.
Perform the following tasks:
(a) Check for the validity of the accepted sentence only for the terminating
character.
(b) Arrange the words in ascending order of their length. If two or more words
have the same length, then sort them alphabetically.
(c) Display the original sentence along with the converted sentence.

Aim:
To accept a paragraph and rearrange the words according to their length.

Program:

import java.util.*;

public class SenArr

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println(“Enter a sentence:”);

String str = in.nextLine();

int len = str.length();

if (str.charAt(len – 1) != ‘.’) {

System.out.println(“Invalid Input!”);

System.out.println(“Sentence should end with full stop.”);

return;

if (Character.isLowerCase(str.charAt(0))) {

System.out.println(“Invalid Input!”);
System.out.println(“Sentence should start with upper case letter.”);

return;

String ipStr = Character.toLowerCase(str.charAt(0)) + str.substring(1, len –


1);

StringTokenizer st = new StringTokenizer(ipStr);

int wordCount = st.countTokens();

String strArr[] = new String[wordCount];

for (int I = 0; I < wordCount; i++) {

strArr[i] = st.nextToken();

for (int I = 0; I < wordCount – 1; i++) {

for (int j = 0; j < wordCount – I – 1; j++) {

if (strArr[j].length() > strArr[j + 1].length()) {

String t = strArr[j];

strArr[j] = strArr[j+1];

strArr[j+1] = t;

strArr[0] = Character.toUpperCase(strArr[0].charAt(0)) +
strArr[0].substring(1);
System.out.println(“Sorted String:”);

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

System.out.print(strArr[i]);

if (i == wordCount – 1) {

System.out.print(“.”);

else {

System.out.print(“ “);

Adder Program
Question: 19

A class Adder has been defined to add any two accepted time.
Example: Time A-6 hours 35 minutes Time B-7 hours 45 minutes. Their sum is-14 hours 20
minutes (where 60 minutes 1 hour) The details of the members of the class are given
below:
Class name: Adder
Data member instance variable:
a[]: integer array to hold two elements (hours and minutes) Member
functions/methods.
Adder constructor to assign 0 to the array elements
void readtime() to enter the elements of the array
void addtime(Adder X, Adder Y) adds the time of the two parameterized objects X and Y
and stores the sum in the current calling object
void disptime(): displays the array elements with an appropriate message (i.e. hours and
minutes).
Specify the class Adder giving details of the constructor, void readtime(), void addtimes
and void disptime(). Define the main() function to create objects and call the functions
accordingly to enable the task.

Aim:
To accept two different times in string format and print the sum of the time

Program:
import java.io.*;
class Adder {
inta[];
Adder()
{
a = new int[2];
}
void readtime() throws IOException {
InputStreamReader x = new InputStreamReader(System.in);
BufferedReader y = new BufferedReader(x);
System.out.println(“Time: ”);
System.out.println(“Enter hour:”);
a[0] = Integer.parseInt(y.readLine());
System.out.println(“Enter minute :”);
a[1] = Integer.parseInt(y.readLine());
}
void addtime(Adder X, Adder Y) {
int hour1 = X.a[0];
int min1 = X.a[1];
int hour2 = Y.a[0];
int min2 = Y.a[1];
int hourSum = hour1 + hour2;
int minSum = min1 + min2;
a[0] = hourSum + (minSum/60);
a[1] = minSum%60;
}

void disptime() {
System.out.println(“Their sum is-“)
System.out.println(“hours =” + a[0] +” minutes =” + a[1]);
}

public static void main(String args[ ]) throws IOException {


Adder obj 1 = new Adder();
Adder obj2 = new Adder();
Adder sumObj = new Adder();
obj1.readtime();
obj2.readtime();
sumObj.addtime(obj1, obj2);
sumObj.disptime();
}
}

Collection Program
Question: 20

A class collection contains an array of 100 integers, Using the following class
descriptions create an array with some common elements from two integers
arrays. Some of the members of the class are given below:
Class name Collection

Data members

arr[]

len length of the array

Members/Function

Collection() default constructor

Collection(int) Parameterized constructor to assign the length of the array. to accept the
array elements, returns a Collection containing the common elements of current Collection
object and the collection object passed as a parameter.

Void arrange() sort the array elements of the object containing common elements in
ascending order using any sorting technique.

Void display() display the array elements.

Aim:

To accept 100 integer from the user and sort the integer using any sorting technique

Program:

import java.io.* ;

public class Collection {

int arr[];

int size ;

public Collection( ) {

arr = new int[100] ;

Size = 0;
}

public Collection(int size) {

arr = new int[size] ;

Size = size ;

Public void display( ) {

For(int I = 0 ; I < size ; i++){

System.out.print(arr[i] +””);

System.out.println( ) ;

public void arrange( ){

for(int i = size – 1 ; i >= 0 ; i--) {

int HIndex = i ;

for(int j = i ; j >= 0 ; j--){

if(arr[j] > arr[HIndex])

HIndex = j ;

int temp = arr[i] ;


arr[i] = arr[HIndex] ;

arr[HIndex] = temp ;

Public static void main(){

InputStreamReader isr= new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

System.out.println(“Enter

Mixer Program
Question: 21

A class Mixer has been defined to merge two sorted integer arrays in ascending order.
Some of the members of the class are given below:
Classname:Mixer
Data members/instance variables: I
nt arr[ ]: to store the elements of an array
int n: to store the size of the array
Member functions:
Mixer(int nn): constructor to assign n=nn
void accept(): to accept the elements of the array in ascending order
without any duplicates
Mixer mix(Mixer A) : to merge the current object array elements with the
parameterized array elements and return the resultant object
void display(): to display the elements of the array
Specify the class Mixer, giving details of the constructor(int), void accept( ),
Mixer mix(Mixer) and void display() . Define the main() function to create
an object and call the function accordingly to enable the task.

Aim:
To accept to different arrays and merge them using object.

Program:

import java.util.Scanner;

class Mixer {

int[] arr;

int n;

Mixer(int nn) {

n = nn;

arr = new int[n];

void accept() {

Scanner in = new Scanner(System.in);

System.out.println("Enter " + n + " elements in ascending order without


duplicates:");
arr[0] = in.nextInt();

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

int num = in.nextInt();

if (num > arr[i - 1]) {

arr[i] = num;

} else {

System.out.println("Please enter a larger number.");

i--;

Mixer mix(Mixer A) {

Mixer result = new Mixer(n + A.n);

int i = 0, j = 0, k = 0;

while (i < n && j < A.n) {

if (arr[i] < A.arr[j]) {

result.arr[k++] = arr[i++];

} else {

result.arr[k++] = A.arr[j++];

}
}

while (i < n) {

result.arr[k++] = arr[i++];

while (j < A.n) {

result.arr[k++] = A.arr[j++];

return result;

void display() {

System.out.print("Merged Array: ");

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

System.out.print(arr[i] + " ");

System.out.println();

}
static void main() {

Scanner in = new Scanner(System.in);

System.out.println();

System.out.print("Enter the size of the first array: ");

int size1 = in.nextInt();

Mixer m1 = new Mixer(size1);

m1.accept();

System.out.print("Enter the size of the second array: ");

int size2 = in.nextInt();

Mixer m2 = new Mixer(size2);

m2.accept();

Mixer mm = m1.mix(m2);

mm.display();

Admission Program
Question: 22

A class Admission contain the admission numbers of 100 students. Some of the data
members/member functions are given below:
Class name: Admission
Data member/instance variable:
Adno[ ]: Integer array to store admission numbers
Member functions/methods:
Admission(): constructur to initialize the array elements void fillArray(): to accept the
element of the array in ascending order int binSearch(int I. int u, int v): to search for a
particular admission number(v) using binary search and recursive technique and return 1 if
Specify the class Admission giving details of the constructor, void fillArrray() and int
hinSearch(int. int, int). Define the main() function to create an object and call the functions
accordingly to enable task.

Aim:
To accept the data of 100 students and perform binary search in the array

Program:

import java.util.*;

class Admission {

static int[] Adno;

static int l = 10;

Admission() {

Adno = new int[l];

static void fl() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the admission numbers in ascending order:");

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

Adno[i] = scanner.nextInt();

}
static int bs(int n) {

int l = 0,r=9;

while (l <= r) {

int m = l + (r - l) / 2;

if (Adno[m] == n)

return 1;

if (Adno[m] < n)

l = m + 1;

else

r = m - 1;

return -1;

static void main()

Admission ob = new Admission();

ob.fl();

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the admission number to search: ");

int sn = scanner.nextInt();

int r = ob.bs(sn);
if (r == 1) {

System.out.println("Admission number " + sn + " found.");

} else {

System.out.println("Admission number " + sn + " not found.");

System.out.println();

REVERSE STRING
(USING RECURSION)
Question: 23

A class Revstr defines a recursive function to reverse a string and check whether it is a
palindrome. The details of the class are given below:
Class name : Revstr
Data members
Str : stores the string.
Revst : stores the reverse of the string. Member functions
void getStr() : to accept the string.
void recReverse(int) : to reverse the string using recursive technique.
void check() : to display the original string, its reverse and whether the string is a
palindrome or not.
Specify the class Revstr giving details of the functions void getStr(), void recReverse(int)
and void check()

Aim:
To accept a String and reverse it using recursion technique.
Program:

Change Program
(Using recursion)
Question: 24

Design a class Change to perform string related operations. The details of the class are
given below:
Data members/instance variables :
str : stores the word,
newstr : stores the changed word,
len : stores the length of the word
Member functions :
Change( ) : default constructor,
Void inputword( ) : to accept word,
Char caseConvert(char ch) : converts the case of the character and returns
it,
Void recchange(int) : extracts characters using recursive technique and
changes its case using caseconvert( ) and forms a new word,
Void display( ) : displays both the words
Specify the class Change, going details of the Constructor( ), and member
functions void inputword( ),char caseconvert(char ch),void recchange(int)
and void display(). Define the main() function to create an object and call
the functions accordingly to enable the above change in the given word.

Aim:
To input a string from the user and convert the lowercase letters to uppercase and vise versa
using recursion

Program:

import java.util.*;

class revstr
{

static String str;

static String revst="";

static void getstr()

Scanner in = new Scanner(System.in);

System.out.println("Enter a string");

str = in.nextLine();

static void recreverse(int r)

if(r==0)

return;

else{

revst+=str.charAt(--r);

recreverse(r);

static void check()


{

System.out.println("Input String: " +str);

System.out.println("Reversed String: " +revst);

if(str.equals(revst))

System.out.println("It is palindrome string");

else

System.out.println("It is not palindrome string");

System.out.println();

static void main()

getstr();

recreverse(str.length());

check();

Happy Number
(Using recursion)
Question: 25

A happy number is a number in which the eventual sum of the square of the digits of the
number is equal to 1.
Example:
28=2^2+8^2=4+64=68
68=6^2+8^2=36+64=100
100=1^2+0^2+0^2=1 +0+0=1
Hence,28 is a happy number.
Example:12 =1^2+2^2=1+4=5
Hence, 12 is not a happy number.
Design a class Happy to check if a given number is a happy number.Some of the member of
the class are given below:
Classname:Happy
Data members/ instance variables:
n: stores the number Member
functions:
Happy(): constructor to assign 0 to n
void getnum(int nn): to assign the parameter value to the number n=nn int
sum_sq_digits(int x): returns the sum of the square of the digit of the
number x. using the recursive technique
void ishappy(): checks if the given number is a happy number by calling the
function sum_sq_digits (int) and displays an appropriate message Specify
the class Happy giving details of the constructor( ), void getnum(int) , int
sum_sq_digits(int) and void ishappy() . Also define a main() functionc to
create an object and call the methods to check for happy number.

Aim:
To input a number from the user and check weither the number is happy number or not using
recursion

Program:

import java.util.*;

class Happy {

private int n;

Happy() {

N = 0;
}

void getnum(int nn) {

N = nn;

int sum_sq_digits(int x) {

if (x == 0) {

return 0;

else{

int digit = x % 10;

return digit * digit + sum_sq_digits(x / 10);

void ishappy() {

int num = n;

while (num>9) {

num = sum_sq_digits(num);

if (num == 1) {

System.out.println(n + “ is a happy number.”);


}

else {

System.out.println(n + “ is not a happy number.”);

static void main() {

Scanner in = new Scanner(System.in);

System.out.print(“Enter a number: “);

int num = in.nextInt();

Happy Ob = new Happy();

Ob.getnum(num);

Ob.ishappy();

Armstrong Number
Question: 26

An Armstrong number is such that the sum of the cube of the digits of the number is the
number itself.
Example 153= 13+53+33
Design a class Arm to perform the given task. Some of the members of the class are given
below:
Class name : Arm
Data member/Instance variables : no :
integer to store the number
sum : integer to store the sum of the cube of the digits Member
methods:
Arm(….): to initialize member data no, and assign 0 to sum.
long fnPower(int a, int b) : to calculate a^b using recursive function void
fnPerform() : to verify and print whether the member data is an
Armstrong number or not.
Specify the class Arm, giving the details of the above member data and methods.
Also define the main() to create an object and call the relevant methods accordingly
to enable the task

Aim:
To input a number and check weither the number is armstrong number or not using recursion

Program:

import java.util.`*;

class Arm {

int no;

int sum;

Arm(int num) {

no = num;

sum = 0;

long fnPower(int base, int exponent) {


if (exponent == 0) {

return 1;

return base * fnPower(base, exponent – 1);

void fnPerform() {

int temp = no;

int numDigits = (int) Math.log10(no) + 1;

while (temp > 0) {

int digit = temp % 10;

sum += fnPower(digit, numDigits);

temp /= 10;

If (sum == no) {

System.out.println(no + “ is an Armstrong number.”);

} else {

System.out.println(no + “ is not an Armstrong number.”);

public static void main() {


Scanner in = new Scanner(System.in);

System.out.print(“Enter a number: “);

int num = in.nextInt();

Arm ob = new Arm(num);

ob.fnPerform();

Perimeter and Area


(using inheritance)
Question: 27

A superclass Perimeter has been defined to calculate the perimeter of a parallelogram.


Define a subclass Arca to compute the area of the parallelogram by using the required
data members of the super class. The details are given below:
Class name: Perimeter
Data members/instance variables
a: to store the length in decimal,
b: to store the breadth in decimal
Member functions:
Perimeter(...); parameterized constructor to assign values to data members.
double calculate: calculate and return the perimeter of a parallelogram as 2 (length +
breadth).
void show(): to display the data members along with the perimeter of the parallelogram
Class name: Area
Data members/instance variables:
h: to store the height in decimal.
area: to store the area of the parallelogram.
Member functions:
Areal...): parameterized constructor to assign values to data members of both the classes
void doArea(): compute the area as (breadth height)
void show(): display the data members of both classes along with the area and perimeter
of the parallelogram.
Specify the class Perimeter giving details of the constructor, double calculate() and void
show(). Using the concept of inheritance, specify the class Area giving details of the
constructor, void do Area() and void show().

Aim:
To accept the length, breadth and height and print the area and the perimeter of the
parallelogram using inheritance

Program:

Customer Details Program


Question: 28

A superclass Detail has been defined to store the details of the customer. Define a subclass
Bill to compute the monthly telephone charge of the customer as per the chart is given
below:
Number of calls:
Rate 1 – 100: Only rental charge
101 – 200: 60 paise per call + rental charge
201 – 300: 80 paise per call + rental charge Above 300:
1 rupee per call + rental charge
The details of both the classes are given below:
Class name: Detail
Data members/instance variables:
name: to store the name of the customer
address: to store the address of the customer
telno: to store the phone number of the customer
rent: to store the monthly rental charge
Member functions:
Detail (…): parameterized constructor to assign values to data members
void show (): to display the details of the customer
Class name: Bill Data
members/instance variables:
n: to store the number of calls
amt: to store the amount to be paid by the customer
Member functions: Bill (…): parameterized constructor to assign values to data
members of both classes and to initialize amt = 0.0
void cal(): calculate the monthly telephone charge as per the chart is given
above
void show(): displays the details of the customer and amount to be paid.
Specify the class Detail giving details of the constructor, and void show().
Using the concept of inheritance, specify the class Bill giving details of the
constructor(), void cal() and void show()

Aim:
To store the details of the customer and compute the monthly telephone charge of the
customer

Program:

import java.util.*;

class Detail {

String name;

String address;

String telno;

double rent;

Detail(String n, String a, String t, double r) {

name = n;
address = a;

telno = t;

rent = r;

void show() {

System.out.println(“Name: “ + name);

System.out.println(“Address: “ + address);

System.out.println(“Phone Number: “ + telno);

System.out.println(“Monthly Rental Charge: “ + rent);

import java.util.*;

class Bill extends Detail {

int n;

double amt;

Bill(String n, String a, String t, double r, int num) {

super(n, a, t, r);

this.n=num;

amt = 0.0;
}

void cal() {

If (n <= 100) {

amt = rent;

} else if (n <= 200) {

Amt = rent + 0.6 * (n – 100);

} else if (n <= 300) {

amt = rent + 0.8 * (n – 100);

} else {

amt = rent + (n – 300);

void show() {

super.show();

System.out.println(“Number of Calls: “ + n);

System.out.println(“Amount to be Paid: “ + amt);

public static void main() {

Scanner in = new Scanner(System.in);


System.out.print(“Enter customer name: “);

String name = in.nextLine();

System.out.print(“Enter customer address: “);

String address = in.nextLine();

System.out.print(“Enter phone number: “);

String telno = in.nextLine();

System.out.print(“Enter monthly rental charge: “);

double rent = in.nextDouble();

System.out.print(“Enter number of calls: “);

int numCalls = in.nextInt();

Bill ob = new Bill(name, address, telno, rent, numCalls);

ob.cal();

ob.show();

Bank Program
Question: 29

A super class Bank has been defined to store the details of a customer.
Define a sub-class
Account that enables transactions for the customer with the bank. The
details of both the classes are given below:
Class name : Bank
Data member/instance variable:
name : stores the name of the customer
accno : stores the account number
p : stores the principal amount in decimals
Member functions/methods:
Bank(…) : parameterized constructor to assign values to the instance variables
void display( ) : displays the details of the customer
Class name: Account
Data member/instance variable:
amt : stores the transaction amount in decimals
Member functions/methods:
Account(…) : parameterized constructor to assign values to the instance
variables of both the classes
void deposit( ) : accepts the amount and updates the principal as p=p + amt
void withdraw( ) : accepts the amount and updates the principal as p=p+amt If
the withdrawal amount is more than the principal amount, then display the
message “INSUFFICIENT BALANCE”. If the principal amount after withdrawal is
less than 500, then a penalty is imposed by using the formula p=p-(500-p)/10
void display( ) : displays the details of the customer Assume that the super class
Bank has been defined.
Using the concept of Inheritance, specify the class Account giving details of the
constructor(…), void deposit( ),void withdraw( ) and void display( ).

Aim:
Using inheritance store the details of the customer in the bank and wanted to compute the
withdraw amount and the deposit amount

Program:

class Bank {
String name;

int accno;

double p;

Bank(String n, int acc, double principal) {

name = n;

accno = acc;

p = principal;

void display() {

System.out.println(“Name: “ + name);

System.out.println(“Account Number: “ + accno);

System.out.println(“Principal Amount: “ + p)

import java.util.*;

class Account extends Bank {

Private double amt;

Account(String n, int acc, double principal, double amount) {

super(n, acc, principal);

amt = amount;
}

void deposit() {

p += amt;

void withdraw() {

if (amt > p) {

System.out.println(“INSUFFICIENT BALANCE”);

else {

p -= amt;

if (p < 500) {

p -= (500 – p) / 10;

void display() {

super.display();

}
public static void main() {

Scanner in = new Scanner(System.in);

System.out.println(“Enter customer name”);

String n = in.nextLine();

System.out.println(“Enter account number”);

int ac = in.nextInt();

System.out.println(“Enter principle”);

int p = in.nextInt();

System.out.println(“Enter 1 to withdraw \n2 to deposit”);

int ch = in.nextInt();

if(ch==1)

System.out.println(“Enter amount to be withdraw”);

int a = in.nextInt();

Account customerAccount = new Account(n,ac,p,a);

System.out.println();

System.out.println(“Before Transactions:”);

customerAccount.display();

customerAccount.withdraw();

System.out.println();

System.out.println(“After Transactions:”);

customerAccount.display();
}

if(ch==2)

System.out.println(“Enter amount to be deposit”);

int a = in.nextInt();

Account customerAccount = new Account(n,ac,p,a);

System.out.println();

System.out.println(“Before Transactions:”);

customerAccount.display();

System.out.println();

customerAccount.deposit();

System.out.println(“After Transactions:”);

customerAccount.display();

Insertion Sort
Question: 30

WAP in Java to accept n elements from user and sort it using Insertion sort
method.
Aim:
To accept n element from the user and sort them using insertion sort techinque

Program:

import java.util.*;

Class Insertion

static int arr[];

public static void input()

Scanner in = new Scanner(System.in);

System.out.print(“Enter the number of elements: “);

int n = in.nextInt();

arr = new int[n];

System.out.println(“Enter “ + n + “ elements:”);

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

arr[i] = in.nextInt();

public static void insertionSort() {

int n = arr.length;
for (int i = 1; i < n; i++) {

int k = arr[i];

int j = I – 1;

while (j >= 0 && arr[j] > k) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = k;

public static void display()

for (int I = 0;i<arr.length;i++) {

System.out.print(arr[i] + “ “);

public static void main() {

Scanner in = new Scanner(System.in);

input();

System.out.println(“Orignal array:”);
display();

insertionSort();

System.out.println(“\nSorted array:”);

display();

Register Program
Question: 31

Register is an entity which can hold a maximum of 100 names. The register enables the user
to add and remove names from the topmost end only. Define a class Register with the
following details:

Class name: Register


Data members/instance variables:
stud[]: array to store the names of the students.
cap: stores the maximum capacity of the array.
top: to point the index of the top end.
Member functions:
Register(int max): constructor to initialize the data members cap =
max, top = -1 and create the string array.

Aim:
To create a register which can maximum hold upto 100 names. And the register enables the
user to add and remove names from the topmost end only.

Program:
import java.util.*;

class Register {

String stud[];

int cap;

int top;

Register(int max) {

cap = max;

stud = new String[cap];

top = -1;

boolean isEmpty() {

return top == -1;

boolean isFull() {

return top == cap – 1;

void push(String name) {

If (isFull()) {

System.out.println(“Register is full. Cannot add more names.”);


return;

stud[++top] = name;

System.out.println(name + “ added to the register.”);

String pop() {

if (isEmpty()) {

System.out.println(“Register is empty. Cannot remove names.”);

return null;

String rn = stud[top];

stud[top] = null;

top--;

System.out.println(rn + “ removed from the register.”);

return rn;

void display()

for (int I = 0;i<top+1;i++) {

System.out.print(stud[i] + “ “);
}

public static void main() {

Scanner in = new Scanner(System.in);

Register ob = new Register(100);

boolean v = true;

while(v)

System.out.println(“\nEnter 1 to add names”);

System.out.println(“Enter 2 to delete a name”);

System.out.println(“Enter 3 to display the register”);

System.out.println(“Enter 4 to exit”);

int ch = in.nextInt();

if(ch==1)

System.out.println(“Enter name to be added”);

String na ;

ob.push(in.next());

System.out.println();

If(ch==2)

Ob.pop();
if(ch==3)

ob.display();

if(ch==4)

v=false;

return;

Queue Program
Question: 32

Queue is a linear data structure which enables the user to add elements from the rear end
and remove elements from the front end only, using the concept of FIFO Note:. Since
insertion and deletion both takes place from different ends, we have to keep record of the
index of both the front as well as the rear end. Consider a queue implemented using an
array q[] index of the front element is stored in the variable' front and index of the last
element is stored in the variable rear.

Aim:
To create a queue linear data structure and enables the user to add elements from the rear
end and remove the element s from the front end only, using the councept of fifo note

Program:

import java.util.*;
Class Queue {

int q[];

int front;

int rear;

int maxSize;

Queue (int size) {

maxSize = size;

q = new int[maxSize];

front = -1;

rear = -1;

boolean isEmpty() {

return front == -1;

boolean isFull() {

Return rear == maxSize – 1;

void eq(int item) {

If (isFull()) {
System.out.println(“Queue is full. Cannot add elements.”)

return;

If (isEmpty()) {

front = 0;

q[++rear] = item;

int dq() {

If (isEmpty()) {

System.out.println(“Queue is empty. Cannot delete elements.”);

return -1;

int item = q[front];

front++;

If (front > rear) {

front = rear = -1;

System.out.println(item + “ has been removed successfully”);

return item;
}

Void display() {

If (isEmpty()) {

System.out.println(“Queue is empty.”);

return;

System.out.println(“Queue elements:”);

for (int I = front; I <= rear; i++) {

System.out.print(q[i] + “ “);

System.out.println();

public static void main() {

Scanner in = new Scanner(System.in);

Queue ob = new Queue(5);

boolean v = true;

while (v) {

System.out.println(“Enter 1 to add numbers”);

System.out.println(“Enter 2 to delete a number”);

System.out.println(“Enter 3 to display the queue”);


System.out.println(“Enter 4 to exit”);

int ch = in.nextInt();

if (ch == 1) {

System.out.println(“Enter number to be added:”);

ob.eq(in.nextInt());

} else if (ch == 2) {

ob.dq();

} else if (ch == 3) {

ob.display();

} else if (ch == 4) {

v = false;

return;

Linear Queue
Question: 33

Write a java program to perform the following functions function in a linear queue.
IsEmpt() check the queue is empty
isFull() check queue is full
display() display the elements in the queue
enqueue() insert an element in the queue
dequeue() remove the element from the queue

Aim:
To create a linear queue data structure and enables the user to add elements from the rear
end and remove the elements

Program:
import java.util.*;
class Linear {
int queue[];
int front;
int rear;
int maxSize;
Linear(int size) {
maxSize = size;
queue = new int[maxSize];
front = -1;
rear = -1;
}
boolean isEmpty() {
return front == -1;
}

boolean isFull() {
return rear == maxSize – 1;
}
void enqueue(int item) {
if (isFull()) {
System.out.println(“Queue is full. Cannot enqueue.”);
return;
}
if (isEmpty()) {
front = 0;
}
queue[++rear] = item;
System.out.println(“Enqueued: “ + item);
}

int dequeue() {
if (isEmpty()) {
System.out.println(“Queue is empty. Cannot dequeue.”);
return -1;
}
int item = queue[front];
if (front == rear) {
front = rear = -1;
}
else {
front++;
}
System.out.println(“Dequeued: “ + item);
return item;
}
void display() {
if (isEmpty()) {
System.out.println(“Queue is empty.”);
return;
}
System.out.print(“Queue elements: “);
for (int I = front; I <= rear; i++) {
System.out.print(queue[i] + “ “);
}
System.out.println();
}

public static void main() {


Scanner in = new Scanner(System.in);
System.out.print(“Enter the size of the queue: “);
int size = in.nextInt();
Linear ob= new Linear(size);
while (true) {
System.out.println(“\nEnter 1 to enqueue”);
System.out.println(“Enter 2 to dequeue”);
System.out.println(“Enter 3 to display”);
System.out.println(“Enter 4 to check if empty”);
System.out.println(“Enter 5 to check if full”);
System.out.println(“Enter 6 to exit”);
int ch = in.nextInt();
Switch (ch) {
case 1:
System.out.print(“Enter element to enqueue: “);
int enqElement = in.nextInt();
ob.enqueue(enqElement);
break;
case 2:
int deqElement = ob.dequeue();
if (deqElement != -1) {
System.out.println(“Dequeued element: “ + deqElement);
}
break;
case 3:
ob.display();
break;
case 4:
System.out.println(“Queue is empty: “ + ob.isEmpty());
break;
case 5:
System.out.println(“Queue is full: “ + ob.isFull());
break;
case 6:
System.out.println(“Exiting…”);
System.exit(0);
default:
System.out.println(“Invalid ch. Try again.”);
}
}
}
}
Exception Handling
(Explicit)
Question: 34

WAP in Java to explain the importance of exception handling. (Explicit)

Aim:
To explain the importance of the exception handling by explicitly creating a exception

Program:

import java.util.*;

class Explicit {

public static void main() {

Scanner in = new Scanner(System.in);

System.out.print(“Enter a numerator: “);

int n = in.nextInt();

System.out.print(“Enter a denominator: “);

int d = in.nextInt();

try {

System.out.println(“Result: “ + (n/d));

catch (ArithmeticException e) {

System.out.println(“Exception caught: Division by zero.”);


}

Infix-Postfix
(using stack)
Question: 35

WAP in Java to convert an infix to postfix expression using stack.

Aim:
To accept expression and want to change the infix to postfix expression using stack

Program:

import java.util.*;

class ItoP

char a[]=new char[10];

int top=-1;

void push(char c)

Try {

a[++top]= c;

}
catch(StringIndexOutOfBoundsException e)

System.out.println(“Stack full, no room to push, size=10”);

System.exit(0);

char pop()

return a[top--];

boolean isEmpty()

return (top==-1);

char peek()

return a[top];

}
static String toPostfix(String infix)

ItoP ob = new ItoP();

char symbol;

String postfix = “”;

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

symbol = infix.charAt(i);

if(Character.isLetter(symbol))

postfix = postfix + symbol;

else if (symbol==’(‘)

ob.push(symbol);

else if (symbol==’)’) {

while (ob.peek() != ‘(‘) {

postfix = postfix + ob.pop();

ob.pop();

else {

while (!ob.isEmpty() && !(ob.peek()==’(‘) && prec(symbol) <= prec(ob.peek()))

postfix = postfix + ob.pop();

ob.push(symbol);

}
}

while (!ob.isEmpty())

postfix = postfix + ob.pop();

return postfix;

static int prec(char x)

if (x == ‘+’ || x == ‘-‘)

return 1;

if (x == ‘*’ || x == ‘/’ || x == ‘%’)

return 2;

return 0;

static void main() {

Scanner in = new Scanner(System.in);

System.out.print(“\nEnter the infix expression you want to convert: “);

String infix = in.nextLine();

System.out.println(“Postfix expression for the given infix expression is:” +


toPostfix(infix));

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy