Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 108

KARPREKAR NUMBER

Question No: 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 check whether a number is a kaprekar number or not


PROGRAM:

import java.util.*;
public class karprekar
{
public 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;
}
public static void main(String args[])
{
Scanner in =new Scanner(System.in);
System.out.println("enter a number");
int n =in.nextInt();
if (check(n,(n*n)))
System.out.println("KARPREKAR");
else
System.out.println("NOT A KARPREKAR");
}
}

OUTPUT:
LUCKY NUMBER
QUESTION NO: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 print the lucky numbers in a given range

PROGRAM:

import java.util.*;

public class LuckyNumber

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;

System.out.println("\nLucky Number Operation:\n");

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++;

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

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

System.out.println();

System.out.print("\nHence, 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 print all the prime adam numbers within a specified range

Program:

import java.util.*;

public class AdamNumber

static int reverseDigits(int num) {

int rev = 0;

while (num > 0) {

rev = rev * 10 + num % 10;

num = num / 10;

return rev;

static int square(int num) {

return (num * num);

static boolean isAdamNumber(int num)

{
int a = square(num);

int b = square(reverseDigits(num));

if (a == reverseDigits(b))

return true;

return false;

static boolean fin(int i)

String f = "";

int c = 0,num;

boolean u = true;

if(isAdamNumber(i) != true)

u=false;

else

for(num =i-1; num>=2; num--)

if(i%num==0)

u=false;

break;

return u;
}

public static void main(String args[])

Scanner sc = new Scanner(System.in);

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

int num = sc.nextInt();

if (fin(num))

System.out.println(num+ " is an Prime Adam number.");

else

System.out.println(num+ " not a Prime Adam number.");

Output:

MOBIUS FUNCTION
QUESTION NO : 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 ) M(12) = 0 ( for 12 = 2 * 2 * 3
M(12) = 0 for 2 appears two times) M(17) = -1 ( for 17 = 17 M(17) = ( -1)1 = -1 )

AIM: To check a number by the Mobius function and return its value as specified above

PROGRAM:

import java.util.*;

public class mob {

static boolean isPrime(int n) {

if (n < 2)

return false;

for (int i = 2; i * i <= n; i++)

if (n % i == 0)

return false;

return true;

static int mobius(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 public void main(String[] args){

Scanner in = new Scanner(System.in);

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

int N =in.nextInt();

System.out.println("Mobius Functions M(N) at " +

" N = " + N + " is: " + mobius(N));

OUTPUT:

GOLDBACH
QUESTION NUMBER : 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 print all the odd prime pairs whose sum is equal to the number ‘N

PROGRAM:

import java.util.Scanner;

public class GoldbachNumber

public static boolean isPrime(int num) {

int c = 0;

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

if (num % i == 0) {

c++;

return c == 2;

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("ENTER THE VALUE OF N: ");

int n = in.nextInt();

if (n <= 9 || n >= 50) {

System.out.println("INVALID INPUT. NUMBER OUT OF RANGE.");


return;

if (n % 2 != 0) {

System.out.println("INVALID INPUT. NUMBER IS ODD.");

return;

System.out.println("PRIME PAIRS ARE:");

int a = 3;

int b = 0;

while (a <= n / 2) {

b = n - a;

if (isPrime(a) && isPrime(b)) {

System.out.println(a + ", " + b);

a += 2;

OUTPUT:
DATE PROGRAM
QUESTION NO: 6

Design a program to accept a day number (between 1 and 366), year (in 4 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 print the current date and future date by getting the corresponding values from the user.

PROGRAM:

import java.util.Scanner;

public class DateCalculator

public 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;

public 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 i = 0;

int daySum = 0;

for (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();

}
public 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 NUMBER : 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 display the mirror matrix of a matrix which is entered by the user.

PROGRAM:

import java.util.Scanner;

public class MirrorImage

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.print("Enter number of rows (m): ");

int m = in.nextInt();

System.out.print("Enter number of columns (n): ");

int n = in.nextInt();

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

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


System.out.println("Enter array elements");

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

System.out.println("Enter Row "+ (i+1) + " :");

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

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

System.out.println("Input Array:");

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

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

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

System.out.println();

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

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

newArr[i][n - 1 - j] = arr[i][j];

System.out.println("Mirror Image Array:");

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

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

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

System.out.println();
}

OUTPUT:

SADDLE POINT
QUESTION NUMBER: 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 inout for a matrix of order mxn and print the
saddle point of it.

AIM: To find and print the saddle point of a given matrix

PROGRAM:

import java.util.*;

public class FindSaddlePoint

static int [][] matrix;

static int m;

static void input()

Scanner in = new Scanner(System.in);

System.out.print("Enter the order of matrix ");

m = in.nextInt();

matrix= new int[m][m];

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

System.out.println();

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

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

System.out.print("Enter row "+(i+1)+" column "+(j+1)+" element: ");

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

}
System.out.println();

public static void main(String args[])

int k;

input();

int min = 0, max = 0;

int [][]index = new int[m][m];

System.out.print("The matrix is: \n");

int i,j;

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

for (j = 0; j < m; j++)

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

System.out.println();

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

min = matrix[i][0];

for (j = 0; j < m; j++)


{

if (min >= matrix[i][j])

min = matrix[i][j];

index[0][0] = i;

index[0][1] = j;

j = index[0][1];

max = matrix[0][j];

for (k = 0; k < m; k++)

if (max <= matrix[k][j])

max = matrix[i][j];

index[1][0] = k;

index[1][1] = j;

if (min == max)

if (index[0][0] == index[1][0] && index[0][1] == index[1][1])

System.out.print("\nSaddle point in the matrix is at index: (" + index[0][0] + ", " +


index[0][1] + ") : " + max + "\n");
}

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. Example :

AIM: To print a magic square of a given order ’n’

PROGRAM:

import java.util.*;

class Magic

static int[][] magic(int n)

int sq[][] = new int[n][n];

int num = 1;

int r = 0;

int c = n / 2;

while (num <= n*n)


{

sq[r][c] = num;

num++;

int nr = (r - 1 + n) % n;

int nc = (c + 1) % n;

if (sq[nr][nc] != 0)

r = (r + 1) % n;

else

r = nr;

c = nc;

return sq;

static void display(int[][] mat,int n)

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

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

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

System.out.println();

}
}

static void main()

Scanner in = new Scanner(System.in);

System.out.print("Enter the order of the magic square ");

int n = in.nextInt();

int sq[][] = magic(n);

System.out.println("Magic Square:");

display(sq,n);

OUTPUT:

CIRCULAR MATRIX
QUESTION NUMBER: 10

Circular matrix: WAP to get the order of a square matrix ‘n’ and get the input for elements
and arrange it in a circular manner. Finally, print the circular matrix. Example:

AIM: To print a circular matrix of order ‘n’

PROGRAM:

import java.util.*;

class CIRCULAR{

static void main() {

Scanner in = new Scanner(System.in);

System.out.print("Enter the order of the square matrix ");

int n = in.nextInt();

int cir[][] = circle(n);

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

display(cir,n);

static int[][] circle(int n) {

int s[][]= new int[n][n];

int num = 1;

int r = 0, c = 0;

int ro = 0, co = 1;

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

s[r][c] = num++;
if (c + co >= n || c + co < 0||r + ro >= n || r + ro < 0||s[r + ro][c + co] != 0) {

int t = co;

co = -ro;

ro =t;

r += ro;

c += co;

return s;

static void display(int a[][],int n) {

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

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

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

System.out.println();

}
OUTPUT:
TRANSPOSE MATRIX
QUESTION: 11

Given a matrix of size N X M, find the transpose of the matrix Transpose of a matrix is
obtained by changing rows to columns and columns to rows. In other words, transpose of
A[N][M] is obtained by changing A[i][j] to A[j][i].

AIM: To find and display the transpose of a given matrix

PROGRAM:

import java.util.*;

class transpose

static int m,n;

static int a[][] ;

static int b[][];

static void input() {

Scanner in = new Scanner(System.in);

System.out.print("Enter the number of rows: ");

m = in.nextInt();

System.out.print("Enter the number of columns: ");

n = in.nextInt();

a= new int[m][n];
b=new int[m][n];

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

System.out.println();

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

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

System.out.print("Enter row "+(i+1)+" column "+(j+1)+" element: ");

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

System.out.println();

static void change() {

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

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

b[i][j] = a[j][i];

static void display(int mat[][]) {

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

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

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

System.out.println();

}
}

static void main() {

input();

System.out.println();

System.out.println("Input matrix");

System.out.println();

display(a);

change();

System.out.println();

System.out.println("Transpose matrix");

System.out.println();

display(b);

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.

AIM: To get the order of the matrix and the matrix from the user and perform the above
tasks.

PROGRAM:

import java.util.*;

class SYMMETRIC {

static int m;

static int a[][] ;

static void input() {

Scanner in = new Scanner(System.in);

System.out.print("Enter the order of the matrix ");


m = in.nextInt();

a= new int[m][m];

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

System.out.println();

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

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

System.out.print("Enter row "+(i+1)+" column "+(j+1)+" element: ");

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

System.out.println();

static void sym() {

int c = 0;

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

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

if(a[i][j]==a[j][i])

c++;

if(c==9)

System.out.println("It is a symmetric matrix");

else

System.out.println("It is not a symmetric matrix");

}
static void display()

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

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

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

System.out.println();

static void sd() {

int c1=0,c2=0,v=0;

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

c1+=a[i][i];

for(int j = m-1;j>=0;j--) {

c2+=a[v][j];

v++;

System.out.println();

System.out.println("Sum of left diagonal: "+c1);

System.out.println("Sum of right diagonal: "+c2);

static void main() {

input();

System.out.println();
System.out.println("Orignal matrix:");

System.out.println();

display();

System.out.println();

sym();

sd();

OUTPUT:
MATRIX MULTIPLICATION
QUESTION: 13

AIM: To multiply the given 2 matrix and display the result

PROGRAM:

import java.util.*;

class MUL

static int[][] input(int m, int n, int i1)

Scanner in = new Scanner(System.in);

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

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

System.out.println();

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

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


System.out.print("Enter row "+(i+1)+" column "+(j+1)+" element: ");

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

System.out.println();

return a1;

static int[][] multi(int a1[][],int b1[][],int r1,int c1,int r2,int c2)

int p[][] = new int[r1][c2];

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

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

for(int k = 0; k < r2; k++){

p[i][j] = p[i][j] + a1[i][k] * b1[k][j];

return p;

static void display(int mat[][], int m, int n)

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

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


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

System.out.println();

static void main(){

int m1,n1,m2,n2,a[][],b[][];

Scanner in = new Scanner(System.in);

System.out.print("Enter the number of rows in matrix 1: ");

m1 = in.nextInt();

System.out.print("Enter the number of columns in matrix 1: ");

n1 = in.nextInt();

System.out.print("Enter the number of rows in matrix 2: ");

m2 = in.nextInt();

System.out.print("Enter the number of columns in matrix 2: ");

n2 = in.nextInt();

if(n1!=m2){

System.out.println("Matrices cannot be multipled");

System.exit(0);

System.out.println();

a = input(m1,n1,1);

b = input(m2,n2,2);

System.out.println("Matrix 1");

display(a,m1,n1);
System.out.println();

System.out.println("Matrix 2");

display(b,m2,n2);

int p1[][] = multi(a,b,m1,n1,m2,n2);

System.out.println();

System.out.println("Product matrix");

display(p1,m1,n2);

OUTPUT:
TEXT FILE SORTING
QUESTION NUMBER: 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, store it in a text file, sort it and store it in another txt file.

PROGRAM:

import java.io.*;

class TXT{

static void write(String n, String n1[]){

try{

FileWriter fw = new FileWriter(n);

BufferedWriter bw = new BufferedWriter(fw);

PrintWriter pw = new PrintWriter(bw);

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

pw.println(n1[i]);

pw.close();

catch(IOException e) {

System.err.println(e);

static void main()throws IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String names[] = new String[10];


System.out.println("Enter 10 names");

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

names[i] = in.readLine();

write("namex.txt",names);

Arrays.sort(names);

write("order.txt",names);

System.out.println();

System.out.println("The names have been sorted");

Output:
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 read product code from user and display the corresponding details of the product

PROGRAM:

import java.io.*;

import java.io.IOException;

class product

static void findpro(int p)

boolean EOF = false;

try{

boolean pf = false;

FileInputStream fr = new FileInputStream("ABC.dat");

DataInputStream ds = new DataInputStream(fr);

while(!EOF)

try{

int pc,up,q;

pc = ds.readInt();

up = ds.readInt();
q = ds.readInt();

if (pc == p) {

pf = true;

System.out.println("Product Code: " + pc);

System.out.println("Unit Price: " + up);

System.out.println("Quantity: " + q);

break;

catch(EOFException e1)

EOF = true;

if (!pf) {

System.out.println("Product with code " + p + " not found.");

catch(IOException e)

System.err.println(e);

static void main()throws IOException

{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter product code");

findpro(Integer.parseInt(in.readLine()));

OUTPUT:

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 convert a sentence to Caeser cipher

PROGRAM:

import java.util.Scanner;

public class CaesarCipher

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

System.out.println("Enter plain text:");

String str = in.nextLine();

int len = str.length();

if (len <= 3 || len >= 100) {

System.out.println("INVALID LENGTH");

return;

StringBuffer sb = new StringBuffer();

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

char ch = str.charAt(i);

if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {

sb.append((char)(ch + 13));

else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {

sb.append((char)(ch - 13));

}
else {

sb.append(ch);

String cipher = sb.toString();

System.out.println("The cipher text is:");

System.out.println(cipher);

OUTPUT:

WORD COUNT
QUESTION NUMBER: 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 count the number of words in a sentence

PROGRAM:

import java.util.*;

class COUNT

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);

OUTPUT:

SENTENCE REARRANGE
QUESTION NUMBER: 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 get a sentence and sort the words in ascending order of their length.

PROGRAM:

import java.util.*;

public class StringCheck

public static String sortString(String ipStr) {

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;

if (strArr[j].length() == strArr[j + 1].length()

&&(strArr[j].compareTo(strArr[j+1]) > 0))


{

String t = strArr[j];

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

strArr[j+1] = t;

} }

StringBuffer sb = new StringBuffer();

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

sb.append(strArr[i]);

sb.append(" ");

return sb.toString().trim();

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();

System.out.println();

if (str.charAt(len - 1) != '.'

&& str.charAt(len - 1) != '?'

&& str.charAt(len - 1) != '!') {

System.out.println("INVALID INPUT");

return;

String sortedStr = sortString(str.substring(0, len - 1));


System.out.println(str);

System.out.println(sortedStr);

OUTPUT:

ADDER PROGRAM
Question: 19
A class Adder has been defined to add any two accepted time. [10] 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

Aim: To add 2 times which is given by the user

Program:
import java.util.*;
public class adder
{
int a[];
adder()
{
a = new int [2];
}
void rt(String y)
{
Scanner in = new Scanner(System.in);
System.out.println("enter"+y+"hour");
a[0] = in.nextInt();
System.out.println("enter"+y+"minute");
a[1]=in.nextInt();
}
void addtime(adder x, adder y)
{
this.a[1] =x.a[1]+y.a[1];
this.a[0] =x.a[0]+y.a[0]+this.a[1]/60;
this.a[1]%=60;
}
void disptime()
{
System.out.println("hours="+ this.a[0]);
System.out.println("minutes="+ this.a[1]);
}
static void main()
{
adder ob = new adder();
ob.rt("first");
adder ob1 =new adder();
ob1.rt("second");
adder ob2 = new adder();
ob2.addtime(ob, ob1);
ob2.disptime();
}
}

OUTPUT:

COLLECTION PROGRAM
QUESTION NUMBER: 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 integer array
length of the array Members Function: Collection():default constructor Collection(int):
Parameterized constructor to assign the length Void inparri()to accept the array elements
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 sort a collection of elements in an array

PROGRAM:

import java.util.*;

class Collection {

static Scanner in = new Scanner(System.in);

static int arr[];

static int len;

Collection(){

len=0;

Collection(int len){

this.len=len;

arr = new int[len];

static void input(){

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

arr[i] = in.nextInt();

void arrange(){
int min,temp;

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

min=i;

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

if(arr[j]<arr[min])

min = j;

temp = arr[i];

arr[i] = arr[min];

arr[min] = temp;

void display(){

System.out.println("The sorted elements are : ");

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

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

}}

static void main(){

Collection ob = new Collection(100);

System.out.println("Enter 100 elements");

input();

ob.arrange();

ob.display();

}
OUTPUT:

MIXER PROGRAM
QUESTION NUMBER: 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: int 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 merge two sorted arrays and display it

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.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();

OUTPUT:
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 found
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 find an admission number from a list of 100 admission numbers using binary search.

Program:

import java.util.*;

class Admission {

static int[] Adno;

static int l = 10;

Admission() {

Adno = new int[l];

static void fl() {

Scanner in = new Scanner(System.in);

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

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

Adno[i] = in.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 in = new Scanner(System.in);

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

int sn = in.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();

Output:
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 reverse a given string and check whether it is a palindrome or not

PROGRAM:
import java.util.*;
public class Revstr
{
String str;
String Revst;
Revstr()
{
str="";
Revst="";
}
void getStr()
{
Scanner in = new Scanner(System.in);
System.out.println("enter a string");
str=in.next();
}
void recReverse(int i)
{
if(i==0) return;
else {
Revst = Revst+str.charAt(i -1);
recReverse(i-1);
}
}
void check()
{
System.out.println("orginal string:"+ str);
recReverse(str.length());
System.out.println("reversed string:"+ Revst);
if(str.equals(Revst))
System.out.println("string"+ str+" is a palindrome");
else
System.out.println("string"+ str+" is not a palindrome");
}
}
OUTPUT:

CHANGE PROGRAM
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 convert the cases of the caracters in a string and return it.

PROGRAM:

import java.util.*;

public class Change

static String str,newstr;

static int len;

static Scanner in = new Scanner(System.in);

Change()

str="";

newstr="";

len=0;

static void inputword()


{

System.out.println("ENTER A Word");

str=in.next();

len=str.length();

static char caseconvert(char ch)

if(ch>='A' && ch<='Z') {

ch=Character.toLowerCase(ch);

else if(ch>='a' &&ch<='z') {

ch=Character.toUpperCase(ch);

return ch;

static void recchange(int pos) {

char c=' ';

if(pos>-1) {

c=str.charAt(pos);

recchange(pos-1);

newstr+=caseconvert(c);

else

return;

}
static void display()

System.out.println("Original Word:"+str);

System.out.println("Changed Word:"+newstr);

static void main()

Change ob1=new Change();

ob1.inputword();

ob1.recchange(len-1);

ob1.display();

OUTPUT:
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 check whether a number is a happy number or not

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();

System.out.println();

}
Output:
ARMSTRONG NUMBER
QUESTION NO: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 check whether a number is an Armstrong number or not

PROGRAM:

import java.util.Scanner;

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.");

static void main() {

Scanner scanner = new Scanner(System.in);

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

int num = scanner.nextInt();

Arm ob = new Arm(num);

ob.fnPerform();

}
OUTPUT:
Perimeter and Area (Using inheritance)
Question: 27

A superclass Perimeter has been defined to calculate the perimeter of a parallelogram. Define
a subclass Area 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: Area1(...):
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 calculate area and perimeter of a paralleogram

Program:

class Perimeter {

double a;

double b;

Perimeter(double length, double breadth) {

a = length;

b = breadth;

double calculate() {

return 2 * (a + b);

void show() {
System.out.println("Length: " + a);

System.out.println("Breadth: " + b);

System.out.println("Perimeter: " + calculate());

import java.util.*;

class Area extends Perimeter {

double h;

double area;

Area(double length, double breadth, double height) {

super(length, breadth);

h = height;

void doArea() {

area = b * h;

void show() {

System.out.println("Height: " + h);

super.show();

System.out.println("Area: " + area);

}
static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Enter length: ");

double length = in.nextDouble();

System.out.print("Enter breadth: ");

double breadth = in.nextDouble();

System.out.print("Enter height: ");

double height = in.nextDouble();

Area ob = new Area(length, breadth, height);

ob.doArea();

ob.show();

Output:
Customer Details Program
Question: 28

A superclass Detail has been defined to store the details of a customer. Define a subclass Bill
to compute the monthly telephone charge of the customer as per the chart is given below:
Number of calls: 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. Page 82 of 107 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 calculate monthly telephone charge of a customer

Program:

import java.util.Scanner;

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);

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();

Output:
BANK PROGRAM
QUESTION NUMBER: 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=pamt 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: Bank program to accept or withdraw from an account.

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();

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();

} }}

OUTPUT:
INSERTION SORT
QUESTION: 30

WAP in Java to accept n elements from user and sort it using Insertion sort method.

AIM: To sort elements in array using insertions sort

PROGRAM:

import java.util.*;

public class InsertionSortExample {

public static void insertionSort(int array[]) {

int n = array.length;

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

int key = array[j];

int i = j-1;

while ( (i > -1) && ( array [i] > key ) ) {

array [i+1] = array [i];

i--;

array[i+1] = key;

public static void main(){

Scanner in = new Scanner (System.in);

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

int n = in.nextInt();

int a[]= new int[n];


System.out.println("Enter elements");

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

a[i]=in.nextInt();

System.out.println("Before Insertion Sort");

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

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

System.out.println();

insertionSort(a);

System.out.println("After Insertion Sort");

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

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

OUTPUT:
REGISTER PROGRAM
QUESTIONJ NO: 31

Register is an entity which can hold a aximum 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 add and remove students name from a register.

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] + " ");

}
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;

OUTPUT:
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: Queue program to add or delete elements from an array

PROGRAM:

import java.util.*;

class QU {

int q[];

int front;

int rear;

int maxSize;

QU(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();

static void main() {

Scanner in = new Scanner(System.in);

QU ob = new QU(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;

OUTPUT:
LINEAR QUEUE
QUESTION NUMBER: 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: Queue program to add and delete elements froma queue

PROGRAM:

import java.util.*;

class LQ {

int queue[];

int front;

int rear;

int maxSize;

LQ(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();

static void main() {

Scanner in = new Scanner(System.in);

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

int size = in.nextInt();

LQ ob= new LQ(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.");

}
OUTPUT:
EXCEPTION HANDLING
QUESTION: 34
Write a program in Java to explain the importance of exception handling. (Explicit)

AIM: To see the importance of exception handling while dividing a number with 0

PROGRAM:

import java.util.*;

class EXH{

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.");

}}}

OUTPUT:
INFIX-POSTFIX USING STACK
QUESTION: 35

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

AIM: To convert an infix to postfix using stack

PROGRAM:

import java.util.*;

class INP

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)

INP ob = new INP();

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;

public 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