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

Computer Project

Uploaded by

kartiklovesyou69
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Computer Project

Uploaded by

kartiklovesyou69
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 160

Acknowledgement

First and foremost I would like to thank my Computer Science teacher, Mrs. Jyoti
Nigam for guiding me over the past four years, helping me to master the basics of
the Java Programming Language and understanding the essence of Coding.
Secondly, I would like to thank her for giving me this project to work on, which
has undeniably helped me in a thorough recollection and perfection of all the
related topics. I would also like to thank our Principal who has constantly
motivated all of us for working hard even during the tough times of the pandemic.
Lastly I would like to thank my parents for always supporting me.
TABLE OF CONTENT

S. TOPIC NAME
No
1 Arra
y
2 Strin
g
3 Object Programming
4 Recursive Programming
5 Data Structure
6 Practical Related Programming

*All programs are based on the above mentioned topics.


1. Array

Question 1: Write a program to accept a square matrix and calculate the sum of its
diagonal(both left and right) elements.

PROGRAM-
import java.util.*;
class diagonal//To calculate the sum of diagonal elements in a matrix
{
int mat[][]=new int[100][100];
int r,c,sum=0;
Scanner sc=new Scanner(System.in);
diagonal(int RR,int CC)
{

r=RR;
c=CC;
}

public void accept()


{
System.out.println("Enter elements row wise");
for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
mat[i][j]=sc.nextInt();
}
}
}
public void display()
{
System.out.println("THE ENTERED
MATRIX"); for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public void diagonal()
{
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(i==j||((i+j)==r))
sum=sum+mat[i][j];
}
}
System.out.println("SUM OF THE DIAGONAL ELEMENTS IS "+sum);
}
public static void main(int rows,int columns)
{
diagonal obj=new diagonal(rows,columns);
obj.accept();
obj.display();
obj.diagonal();
}
}

OUTPUT-
Enter elements row wise
0
1

2
3
4
5
6
7
8
THE ENTERED MATRIX
012
345

678
SUM OF THE DIAGONAL ELEMENTS IS 24

------------------*------------------*------------------*-----------------
Question 2:Write a Program to accept a matrix and print it after transposing.
Program-
import java.util.*;
class transpose
{

int mat[][]=new int[100][100];


int r,c;
Scanner sc=new Scanner(System.in);
transpose(int RR,int CC)
{

r=RR;
c=CC;
}

public void accept()


{
System.out.println("Enter elements row wise");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
mat[i][j]=sc.nextInt();
}
}
}
public void display()
{
System.out.println("THE ENTERED
MATRIX"); for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public void transposing()
{
int i,j,t;
System.out.println("The New Matrix after transposing");
for(i=0;i<r;i++)
{
for(j=(i+1);j<c;j++)
{
t=mat[i][j]; mat[i]
[j]=mat[j][i]; mat[j]
[i]=t;
}

}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public static void main(int rows,int columns)
{
transpose obj=new transpose(rows,columns);
obj.accept();
obj.display();
obj.transposing();
}
}

OUTPUT-
Enter elements row wise
1
2

3
4
5
6
7
8
9
THE ENTERED MATRIX
123
456

789
The New Matrix after transposing
147
258

369

------------------*------------------*------------------*-----------------
Question 3:Write a program to accept a matrix and then print it in cyclic
form.

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

int mat[][]=new int[100][100];


int r,c;
Scanner sc=new Scanner(System.in);
cyclic(int RR,int CC)
{

r=RR;
c=CC;
}

public void accept()


{
System.out.println("Enter elements row wise");
for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
mat[i][j]=sc.nextInt();
}
}
}
public void display()
{
System.out.println("THE ENTERED
MATRIX"); for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public void CYCLIC()
{
int j,i,t;
System.out.println("Matrix in cyclic form");
for(j=0;j<c;j++)
{

for(i=0;i<(r-1);i++)
{
t=mat[i][j]; mat[i]
[j]=mat[i+1][j];
mat[i+1][j]=t;
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public static void main(int rows,int columns)
{
cyclic obj=new cyclic(rows,columns);
obj.accept();
obj.display();
obj.CYCLIC();
}

OUTPUT:
Enter elements row wise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
THE ENTERED MATRIX
1234
5678

9 10 11 12
13 14 15 16
17 18 19 20
Matrix in cyclic form
5678
9 10 11 12

13 14 15 16
17 18 19 20
1234

------------------*------------------*------------------*-----------------
Question 4: Write a program to accept a matrix and then print it in reversed or
mirrored form.

Program:
import java.util.*;
class reversingthematrix
{
int mat[][]=new int[100][100];
int r,c;
Scanner sc=new Scanner(System.in);
reversingthematrix(int RR,int CC)
{

r=RR;
c=CC;
}

public void accept()


{
System.out.println("Enter elements row wise");
for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
mat[i][j]=sc.nextInt();
}
}
}
public void display()
{
System.out.println("THE ENTERED
MATRIX"); for(int i=0;i<r;i++)
{

for(int j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public void mirror()
{
int i,j,k=(c-1);
for(i=0;i<r;i++)
{
for(j=0;j<(c/2);j++)
{
int t=mat[i][j];
mat[i][j]=mat[i][k-j];
mat[i][k-j]=t;
}

}
System.out.println("The reversed matrix");
for(i=0;i<r;i++)
{

for(j=0;j<c;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
public static void main(int rows,int columns)
{
reversingthematrix obj=new reversingthematrix(rows,columns);
obj.accept();
obj.display();
obj.mirror();
}
}
OUTPUT-
Enter elements row wise
1
2

3
4
5
6
7
8
9
THE ENTERED MATRIX
123
456

789
The reversed matrix
321
654

987

------------------*------------------*------------------*-----------------
QUESTION 5:Write a program to accept an array and then arrange it in
ascending form using bubble sort technique.

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

public static void ascending()


{
int ar[]=new int[100];
int i,j,s,t,p,size;
Scanner sc=new Scanner(System.in);

System.out.println("ENTER SIZE OF THE SINGLE DIMENSIONAL


ARRAY");
size=sc.nextInt();
System.out.println("ENTER ELEMENTS OF THE SINGLE DIMENSIONAL
ARRAY");
for(p=0;p<size;p++)
{
ar[p]=sc.nextInt();
}
for(i=0;i<(size-1);i++)
{
for(j=0;j<(size-(i+1));j++)
{
if(ar[j]>ar[j+1])
{
t=ar[j];
ar[j]=ar[j+1];
ar[j+1]=t;
}

}
}
System.out.print("Array arrranged in ascending form: ");
for(p=0;p<size;p++)
{
System.out.print(ar[p]+" ");
}
}
}

OUTPUT:
ENTER SIZE OF THE SINGLE DIMENSIONAL ARRAY
5
ENTER ELEMENTS OF THE SINGLE DIMENSIONAL ARRAY
11
43

21
11
2
Array arrranged in ascending form: 2 11 11 21 43
------------------*------------------*------------------*------------------
Question 6: Write a Program to print a matrix in spiral form.

Program-
import java.util.*;
class spiral
{

public static void main()


{
Scanner sc=new Scanner(System.in);
int row,i=0,j=0,n=1,c;
int mat[][]=new int[100][100];

System.out.println("Enter then number of rows/columns in the squared matrix");


row=sc.nextInt();
c=row;
while(n<=(row*row))
{

for( ;j<c;j++)
{
mat[i][j]=n;
n++;
}
i++;
j--;
for( ;i<c;i++)

{
mat[i][j]=n;
n++;
}

i--;
j--;
for( ;j>=(row-c);j--)
{
mat[i][j]=n;
n++;
}

c--;
j++;
i--;
for( ;i>=(row-c);i--)

{
mat[i][j]=n;
n++;
}

i++;
j++;
}
for(i=0;i<row;i++)
{
for(j=0;j<row;j++)
{
System.out.print(mat[i][j]+"\t");
}
System.out.println();
}
}
}
OUTPUT-
Enter then number of rows/columns in the squared matrix
6

1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11

QUESTION 7 :WRITE A PROGRAM TO PRINT AND CHECK ISBN NUMBER.

import java.util.*;
class ISBN_No

Scanner ob = new Scanner(System.in);

String a;

int x, s, y, len, i;

char ch;

public void check()

System.out.println("Enter 10 digit code ");

a=ob.nextLine();

len=a.length();

if(len<10 || len>10)

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

else

s=0;

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

ch=a.charAt(i);

if(ch = = 'X') x = 10;

else x = Integer.valueOf(ch)-48;
s = s + (10-i) * x;

y=s%11;

System.out.println("SUM = " + s);

if(y==0)
System.out.println("LEAVES NO REMAINDER – VALID ISBN CODE");

else
System.out.println("LEAVES REMAINDER – INVALID ISBN CODE");

public static void main(String arg[])

ISBN_No obj = new ISBN_No();

obj.check();

}
OUTPUT:
INPUT CODE:0201530821
OUTPUT:SUM=99
LEAVES NO REMAINDER-VALID ISBN NUMBER
QUESTION 8:WRITE A PROGRAM TO CHECK FOR SYMMETRIC MATRIX
import java.util.*;

class SymmetricMatrix
{

int a[ ][ ];

int b[ ][ ];

int i, j, m, s, ld, rd;

Scanner ob=new Scanner(System.in);

public void show( )

System.out.println("Enter size of an Array from 2 to 20 ");

m=ob.nextInt( );

if(m>1 && m<=10)

a=new int[m][m];

b=new int[m][m];

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

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

System.out.print("Enter value for a[i][j] ");


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

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

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

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

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

System.out.println( );

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

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

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

System.out.println( );
}

System.out.println( );

s=0;

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

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

if(a[i][j]!=b[i][j]) s++;

if(s==0) System.out.println("THE GIVEN MATRIX IS


SYMMETRIC");

else System.out.println("THE GIVEN MATRIX IS NOT


SYMMETRIC");
}

public static void main(String arg[ ])

SymmetricMatrix obj = new SymmetricMatrix();

obj.show( );

}
INPUT:M=3
1 2 3
2 4 5
3 5 6
OUTPUT:ORIGINAL MATRIX
1 2 3
2 4 5
3 5 6

THE GIVEN MATRIX IS SYMMETRIC

QUESTION 9:WRITE A PROGRAM TO MIRROR A MATRIX


import java.util.*;

class MatrixImage

int a[ ][ ];

int i, j, m;

Scanner ob=new Scanner(System.in);

public void show( )

System.out.println("Enter size of an Array from 2 to 20 ");

m=ob.nextInt( );

if(m>1 && m<=20)

{
a=new int[m][m];

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

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

System.out.print("Enter value for a[i][j] ");

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

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

System.out.println( );

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

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

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

System.out.println( );

System.out.println( );
System.out.println("Image Matrix is ");

System.out.println( );

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

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

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

System.out.println( );

else System.out.println("SIZE OUT OFF RANGE");

public static void main(String arg[])

MatrixImage obj = new MatrixImage( );

obj.show();

}
INPUT:m=3
4 16 12
8 2 14
6 1 3
OUTPUT:ORIGINAL MATRIX
4 16 12
8 2 14
6 1 3
MIRROR IMAGE MATRIX
12 16 4
14 1 8
3 1 6

QUESTION 10:WRITE A PROG RAM TO CHECK WHETHER A DATE IS


VALID OR NOT.
import java.util.*;
class ValidDate
{
public static void main(String arg[])
{
int a[ ]={31,28,31,30,31,30,31,31,30,31,30,31};
int d,m,y,s,i;
Scanner br =new Scanner(System.in);
s=0;
System.out.println("Enter day : ");
d=br.nextInt( );
System.out.println("Enter month : ");
m=br.nextInt( );
System.out.println("Enter year : ");
y=br.nextInt( );
if(y%4==0) a[1]=29;
if(m>12 || d>a[m-1])
System.out.println("INVALID DATE");
else
{
for(i=0;i<m-1;i++)
s=s+a[i];
s=s+d;
System.out.println("Total number of days : " + s);
}
}
}
INPUT:05
01
2010
OUTPUT:VALID DATE
2. String

Question 1:Write a program to enter a sentence in mixed case and display the new
sentence after deleting all the vowels.
Program:
import java.util.*;
class dvowels
{

public static void main()


{
Scanner sc= new Scanner(System.in);
int i,p,q;
char ch;

String st,st2=" ";


System.out.println("Enter a sentence");
st=sc.nextLine();
p=st.length();
for(i=0;i<p;i++)
{

ch=st.charAt(i);

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='
U')
continue;
st2=st2+ch;
}
q=st2.length();
System.out.println("New String formed after removal of all vowels:"+st2);

}
}
Output:
Enter a sentence
Hello World
New String formed after removal of all vowels: Hll Wrld
------------------*------------------*------------------*-----------------
Question 2-

Class name: TheString


Data members/instance variables:
str: to store a string.
len: integer to store the length of the string.
wordCount: integer to store the number of words.
cons: integer to store the number of consonants.
Member functions/methods:

TheString(): default constructor to initialize the data members.


The String(String ds): parameterized constructor to assign str = ds.
void countFreq(): to count the number of words and the number of consonants
and store them in wordCount and cons respectively.
void display(): to display the original string, along with the number of words and
the number of consonants.
Specify the class TheString giving the details of the constructors, void countFreq()
and display(). Define the main() function to create an object and call the functions
accordingly to enable the task*/

Program-
import java.util.*;
class TheString
{

String str;
int len,wordcount,cons;
TheString()
{

str="";
len=0;
wordcount=0;
cons=0;
}

TheString(String ds)
{
str=ds;
}
void countFreq()
{
char c;
str=str.toUpperCase();
str=str+' ';
len=str.length();
for(int i=0;i<len;i++)
{

c=str.charAt(i);
if(c==' ')
wordcount++;
else
if(c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
continue;
else
cons++;
}

}
void display()
{
System.out.println("Original String:"+str);
System.out.println("Frequency of Words:"+wordcount);
System.out.println("Frequency of consonants:"+cons);
}

public static void main()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Sentence:");
String s=sc.nextLine();
TheString ob=new TheString(s);
ob.countFreq();
ob.display();

}
}

Output-
Enter a Sentence:
hello world
Original String:HELLO WORLD
Frequency of Words:2 Frequency
of consonants:7

------------------*------------------*------------------*-----------------
Question 3-Write a program to accept a sentence which may be terminated by
either '.','?' or '!' only. The words may be seperated
by more than one blank space and are in UPPER CASE.
Perform the following tasks:
(a) Find the number of words beginning and ending with a vowel.
(b) Place the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.*/

Program-
import java.util.*;
class VowelWords
{
public static void main()
{
Scanner in = new Scanner(System.in);
String sent,s1="",s2="",s3="",s4="";
int n,i,t,p;
char d;
System.out.println("Enter a sentence in terminated by a (.)or(?)or(!)");
sent=in.nextLine();
sent.toUpperCase();
p=sent.length();
char c=sent.charAt(p-1);
if(c=='.'||c=='!')
{
sent=sent.substring(0,p-1);
StringTokenizer s=new StringTokenizer(sent);
n=s.countTokens();
t=0;
for(i=1;i<=n;i++)
{
s1=s.nextToken();
c = s1.charAt(0);
d = s1.charAt(s1.length()-1);
if((c=='A'||c=='E'||c=='I'||c=='O'||c=='U')&& (d=='A'||d=='E'||d=='I'||
d=='O'||d=='U'))
{
s2=s2+' '+s1;
t++;
}
else
s3=s3+' ' +s1;
}
s4=s2+' '+s3;
System.out.println("Number of words beginning and ending with
vowels = "+t);
System.out.println("The new sentence:");
System.out.println(s4);
}
else
System.out.println("Invalid Input");
}
}

Output-
Enter a sentence in terminated by a (.)or(?)or(!)
AN AEROPLANE IS FLYING IN THE SKY.
Number of words beginning and ending with vowels = 1
The new sentence:
AEROPLANE AN IS FLYING IN THE SKY.

------------------*------------------*------------------*-----------------

Question 4:The words that are made with the combinations of the letters present in
the original word are called Anagram.
Write a program to accept two words and check whether they are Anagram or
not.
Program:
import java.util.*;
class Anagram
{
public static void main()
{
int p1,p2,i,j,as1,as2,s1=0, s2=0;
String str1, str2, str3="",str4="";
char chr1, chr2;
Scanner in=new Scanner(System.in);
System.out.println("Enter first word");
str1=in.next();
str1=str1.toUpperCase();
System.out.println("Enter second word");
str2=in.next();
str2=str2.toUpperCase();
p1=str1.length();
p2=str2.length();
if(p1==p2)
{
for(i=65;i<=90;i++)
{
for(j=0;j<p2;j++)
{
chr1=str1.charAt(j);
chr2=str2.charAt(j);
as1=(int)chr1;
as2=(int)chr2;
if(as1==i)
{
str3=str3+chr1;
s1=s1+as1;
}
if(as2==i)
{
str4=str4+chr2;
s2=s2+as2;
}
}
}
if(str3.equals(str4)&&(s1==s2))
System.out.println(str1+" and "+str2+" are Anagram words");
else
System.out.println(str1+" and "+str2+" are not Anagram words");
}
else
System.out.println("Wrong Input!! Re-enter words for Anagram");
}
}
Output:
Enter first word
good
Enter second word
mood
GOOD and MOOD are not Anagram words
Enter first word
flow
Enter second word
wolf
FLOW and WOLF are Anagram words
------------------*------------------*------------------*-----------------
Question 6:
A class Rearrange has been defined to modify a word by bringing all the vowels in
the word at the beginning followed by the consonants.
Some of the members of the class are given below:

Class name: Rearrange


Data members/instance variables:
word: to store a word.
newWord: to store the rearranged word.
Member functions/methods:
Rearrange(): default constructor.
void readWord(): to accept the word in uppercase.
void freq_vow_con(): finds the frequency of vowels and consonants in the word
and displays them with an appropriate message.
void arrange(): rearranges the word by bringing the vowels at the beginning
followed by consonants.
void display(): displays the original word along with the rearranged word.

Specify the class Rearrange, giving details of the constructor, void readWord(),
void freqVowelCon(), void arrange() and void display(). Define the main()
function to create an object and call the functions accordingly to enable the task.
Program:

import java.util.*;
class Rearrange
{

String wrd,newwrd;
Rearrange()
{

wrd="";newwrd="";
}
void readword()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a word");
wrd = s.next();
wrd = wrd.toUpperCase();

}
void freq_vow_con()
{
int l=wrd.length(), v=0, c=0;
for(int i=0;i<l;i++)
{

char ch=wrd.charAt(i);
if(Character.isLetter(ch))
{
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') v+
+;
else

c++;
}
}
System.out.println("No.of vowels"+v+"\n No.of Consonants"+c);
}
void arrange()
{
int l=wrd.length();
char ch;
String w1="",w2="";
for(int i=0;i<l;i++)
{

ch=wrd.charAt(i);
if(Character.isLetter(ch))
{

if(ch=='A'||ch=='E'||ch=='O'||ch=='I'||ch=='U')
w1 = w1 + ch;
else

w2 =w2 + ch;
}
}
newwrd = w1+w2;
}
void display()
{
System.out.println("original word:"+ wrd);
System.out.println("New word:" + newwrd);
}

public static void main()


{
Rearrange R = new Rearrange();
R.readword();
R.freq_vow_con();
R.arrange();

R.display();
}
}

Output:
Enter a word
original
No.of vowels4
No.of Consonants4
original word:ORIGINAL
New word:OIIARGNL

------------------*------------------*------------------*-----------------
Question7:
A class swapSort has been defined to perform string related operations on a word
input. Some of the members of the class are as follows
Class Name swapSort

Data members/instance variables


wrd: to store a word
len: integer to store length of the word
swapwrd: to store the swapped word
Sortwrd: to store the sorted word
Member functions\Methods
SwapSort( ) default constructor to initialize data members with
legal initial values
void readword( ) to accepts a word in UPPER CASE

void swapchar( ) to interchange/swap the first and last characters of


the word in ‘wrd’ and stores the new word in
‘swapwrd’

void sortword( ) sorts the character of the original word in


alphabetical order and stores it in ‘sortwrd’
void display( ) displays the original word, swapped word and the
sorted word.
Specify the class SwapSort, giving the details of the constructor( ), void
readword( ), void swapchar( ), void sortword( ) and void display( ). Define the
main( ) function to create an object and call the functions accordingly to
enable
the task.

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

String wrd,swapwrd,sortwrd;
int len;
SwapSort()
{
wrd = swapwrd = sortwrd = "";
len = 0;
}

void readword()
{
Scanner S = new Scanner (System.in);
System.out.println("Enter string in
uppercase"); wrd = S.next();
len = wrd.length();

wrd =wrd.toUpperCase();
}
void swapchar()
{
char C1 = wrd.charAt(0);
char C2 = wrd.charAt(wrd.length()-1);
swapwrd = C2 + wrd.substring(1,len-1)+C1;
}

void sortwrd()
{ int C; sortwrd = "";
for(char ch = 'A'; ch<='Z'; ch++)
{ C=0;
for(int i=0;i<len;i++)
{
if(ch==wrd.charAt(i))
C++;
}

if(C>0)
sortwrd += ch;
}
}
void display()
{
System.out.println("Original word"+wrd);
System.out.println("Swapped word:" +swapwrd);
System.out.println("Sorted word:"+ sortwrd);
}

public static void main ()


{
SwapSort s = new SwapSort();
s.readword();
s.swapchar();

s.sortwrd();
s.display();
}
}

Output:
Original wordGOODNESS
Swapped word:SOODNESG
Sorted word:DEGNOS

------------------*------------------*------------------*-----------------

Question 8: Write a program in Java to accept any three letter word and print all
the probable three letter combinations. No letter should be repeated within the
output.

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

public static void main()


{
String str;
int i,j,k,p;
Scanner in=new Scanner(System.in);
System.out.println ("Enter a three letter word");
str=in.nextLine();
p=str.length();

System.out.println ("The required combinations of the word:");


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

for(j=0;j<p;j++ )
{
for(k=0;k<p;k++ )
{
if(i!=j&&j!=k&&k!=i) System.out.println(str.charAt(i)+""+str.charAt(j)
+""+str.charAt(k));
}

System.out.println();
}
}
}
}

Output:
Enter a three letter word
top
The required combinations of the word:

top

tpo

otp

opt

pto

pot

------------------*------------------*------------------*-----------------
Question 9 : Write a program to accept a sentence which maybe terminated by
either '.'or '?' only. The wordss are to be seperated by a single
blank space. Print an error message if the input does not terminate with '.' or '?'.
You can assume that no word in the sentence
exceeds 15 characters, so that you get a proper formatted output.
Perform the following tasks:
(a) Convert the first letter of each word to uppercase.

(b) Find the number of vowels and consonants in each word and display
them with proper headings along with the words.
Program :
import java.util.*;
class Display
{

public static void main()


{
String s,st,str="",p;
char c,ch;
int i,j,m,n,t=0,vol,con;

Scanner in=new Scanner(System.in);


System.out.println("Enter a sentence terminated by '.'or '?'");
s=in.nextLine();
m=s.length();
if(s.charAt(m-1)=='.' || s.charAt(m-1)=='?')
{
for(i=0;i<m;i++)
{
c=s.charAt(i);
if(c==' '||c=='.'||c=='?')
{
p=s.substring(t,i); st=Character.toUpperCase(p.charAt(0))
+p.substring(1); str=str+' '+st;
t=i+1;
}
}
System.out.println(str);
p="";
System.out.println("Words\t"+"Vowels\t"+"Consonants");
str=str.trim();
str=str+' ';
m=str.length();
for(i=0;i<m;i++)
{

c=str.charAt(i);
if(c!=' ')
p=p+c;

else
{
n=p.length();vol=0;
for(j=0;j<n;j++)
{

ch=p.charAt(j);
if(ch=='A'|| ch=='I'|| ch=='O'|| ch=='U'|| ch=='a'|| ch=='e'|| ch=='i'|| ch=='o'||
ch=='u')
vol++;
}
con=n-vol; System.out.println(p+"\t"+vol+"\
t"+con);
p="";
}
}
}
else
System.out.println("Invalid Input");
}
}
Output:
Enter a sentence terminated by '.'or '?'
hello everyone.
Hello Everyone

Words Vowels Consonants


Hello 2 3
Everyone 35

------------------*------------------*------------------*-----------------
QUESTION 10:WRITE A PROGRAM TO COUNT FREQUENCY OF WORDS.

import java. util . *;


class s1
{
public void main ()
{
Scanner sc = new Scanner(System . in );
int i ,l , f=0;
String str; char ch ;
System.out.println(" Enter sentence ");
str =sc. nextLine();
str= str + " " ;
l= str . length () ;
for( i=0 ; i<l ; i++)
{
ch= str. charAt(i);
if ( ch== ' ')
f++;
}
System.out.println("Frequency of words=" + f );
}
}

OUTPUT:Enter sentence

I AM A GOOD BOY.
Frequency of words=5
3. Object Oriented Programming

Question1:
Design a class with the following details:
Class Name: Angle
Data Members:
Deg, min : integer variables to store degree and minutes.

Member functions:
Angle() - Constructor to assign 0 to deg,min
void inputangle() - to input values of deg and min.
void dispangle() - to print values of deg and min with proper messages.
Angle sumofangle(Angle T1, Angle T2) - to find the sum of angles T1 and T2 by
using above method of adding angles and return the sum of angles

Program:

import java.util.*;
class Angle
{
int deg,min;
Angle()
{
deg=0;
min=0;
}
void inputangle()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter value of degree");
deg=sc.nextInt();
System.out.println("Enter value of minutes");
min=sc.nextInt();
}
void dispangle()
{
System.out.println("Value of Degree="+deg);
System.out.println("Value of Minutes="+min);
}
public Angle sumofangle(Angle T1,Angle T2)
{
Angle R=new Angle();
R.deg= T1.deg+T2.deg;
R.min= T1.min+T2.min;
if(R.min>=60)
{
R.min-=60;
R.deg++;
}
return R;
}
public static void main()
{
Angle obj1=new Angle();
Angle obj2=new Angle();
Angle obj3=new Angle();
System.out.println("Enter value in Object 1");
obj1.inputangle();
System.out.println("Enter value in Object
2"); obj2.inputangle();
System.out.println("Value of Object 1");
obj1.dispangle();
System.out.println("Value of Object 2");
obj2.dispangle();
System.out.println();
obj3=obj3.sumofangle(obj1,obj2);
System.out.println("Value of Object 3");
obj3.dispangle();
}
}
Output:

Enter value in Object 1


Enter value of degree
25
Enter value of minutes
52
Enter value in Object 2
Enter value of degree
36
Enter value of minutes
76
Value of Object 1
Value of Degree=25
Value of Minutes=52
Value of Object 2
Value of Degree=36
Value of Minutes=76

Value of Object 3
Value of Degree=62
Value of Minutes=68
------------------*------------------*------------------*------------------
Question 2: A class Shift contains a two-dimensional integer array of order (m ×
n) where the maximum values of both m and n is 5. Design the class Shift to
shuffle the matrix (i.e. the first row becomes the last, the second row becomes the
first and so on). The details of the members of the class are given below:
Class name: Shift
Data members/instance variables:
mat[][]: stores the array element.
m: integer to store the number of rows.
n: integer to store the number of columns.
Member functions/methods:
Shift(int mm, int nn): parameterized constructor to initialize the data members m
= mm and n = nn.
void input(): enters the elements of the array.
void cyclic(Shift P): enables the matrix of the object P to shift each row upwards
in a cyclic manner and store the resultant matrix in the current object.
void display(): displays the matrix elements.

Specify the class Shift giving details of the constructor, void input(), void
cyclic(Shift) and void display(). Define the main() function to create an object and
call the methods accordingly to enable the task of shifting the array elements.

Program:
import java.util.*;
class Shift
{
Scanner sc=new Scanner(System.in);
int mat[][]=new int[5][5];
int m,n;
Shift(int mm,int nn)
{
m=mm;
n=nn;
mat=new int[m][n];

}
void input()
{
int i,j;
System.out.println("Enter elements of array");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
mat[i][j]=sc.nextInt();
}
}
}
void display()
{
int i,j;
System.out.println("Entered Array:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(mat[i][j]+" ");
}
System.out.println();
}
}
void cyclic(Shift p)
{
int i,j;
for(i=0;i<p.m;i++)
{

for(j=0;j<p.n;j++)
{
if(i==0)
this.mat[m-1][j]=p.mat[i][j];
else
this.mat[i-1][j]=p.mat[i][j];

}
}
}
public void main(int r,int c)
{
S
h
i
f
t
(
r
,
c
)
;

}
S
Output:
S h

h i

i f

f t

t
o

o b

b j

j 2

1 =

= n

n e

e w

w
S
h
i matr
f ix
t obj1
( ");
r obj1.
, displ
c ay();
) obj2.
; cycli
System.out.p c(obj
rintln("\n 1);
Enter matrix Syst
in obj1"); em.o
obj1.input(); ut.pr
Syst intln
em.o ("\n
ut.pr matr
intln ix
("\ obj2
f"); ");
Syst obj2.
em.o displ
ut.pr ay();
intln }
("\n

matrix obj1
Entered Array:
1234
5678

9 10 11 12
13 14 15 16

matrix obj2
Entered Array:
5678
9 10 11 12

13 14 15 16
1234
------------------*------------------*------------------*------------------

Question4: 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:
Class name: 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 num): constructor to assign n = num.
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, void accept(), Mixer
mix(Mixer) and void display(). Define the main() function to create an object and
call the functions accordingly to enable the task.

Program:
import java.util.*;
class Mixer
{
int arr[];
int n;
Scanner in = new Scanner(System.in);
Mixer(int nn)
{

n=nn;
arr=new int[n];
}
void accept()
{
System.out.println("Enter elements of both the arrays in ascending order:");
for(int i=0;i<n;i++)
arr[i]=in.nextInt();
}
Mixer mix(Mixer A)
{
Mixer t = new Mixer(n+A.n);
for(int i=0;i<A.n;i++)
t.arr[i]=A.arr[i];
for(int j=0;j<n;j++)
t.arr[A.n+j]=arr[j];
return(t);
}

void display()
{
System.out.println("Merged elements:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
}

public static void main()


{
Scanner sc=new Scanner(System.in);
int L1;
int L2;
System.out.println("Enter length of array 1");
L1=sc.nextInt();
System.out.println("Enter length of array 2");
L2=sc.nextInt();
Mixer ob1 = new Mixer(L1);
Mixer ob2 = new Mixer(L2);
Mixer ob3 = new Mixer(L1+L2);
ob1.accept();
ob2.accept();
ob3=ob2.mix(ob1);
ob3.display();
}

}
Output:
Enter length of array 1
4
Enter length of array 2
5
Enter elements of both the arrays in ascending order:
1
2

3
4
Enter elements of both the arrays in ascending order:
5
6

7
8
9
Merged elements:
123456789

------------------*------------------*------------------*------------------
Question5:
The co-ordinates of a point P on a two-dimensional plane can be represented by
P(x,y) with x as the x co-ordinate and y as the y co-ordinate. The co- ordinates of
midpoint of two points P1(x1,y1) and P2(x2,y2) can be calculated as P(x,y)
where: x=x1+x2/2, y=y1+y2/2 .
Design a class Point with the following details:
Class name : Point
Data members
x : stores the x co-ordinate
y : stores the y co-ordinate
Member functions:
Point() : constructor to initialize x=0 and y=0

void readPoint() : accepts the co-ordinates x and y of a point


Point midpoint(Point A, Point B): calculates and returns the midpoint of the two
points A and B.
void displaypoint() : displays the co-ordinates of a point
Specify the class Point giving details of the constructor( ), member functions
void readPoint(), Point midpoint(Point, Point) and void displaypoint() along with
the main function to create an object and call the functions accordingly to
calculate the midpoint between any two given points.
Program: import
java.util.*; class
Point
{

int x,y;
Point ()
{
x=0;
y=0;
}

void readpoint()
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the value of coordinate of x");
x=sc.nextInt();
System.out.println("Enter the value of coordinate of y");
y=sc.nextInt();
}

void displaypoint()
{
System.out.println("Coordinate x value="+x);
System.out.println("Coordinate y value="+y);
}
Point midpoint(Point A,Point B)
{
Point R=new Point();
R.x=(A.x+B.x)/2;
R.y=(A.y+B.y)/2;

return R;
}
public static void main ()
{
Point obj1 =new Point();
Point obj2 =new Point();
Point obj3 =new Point();
System.out.println("Enter value in object 1");
obj1.readpoint();
System.out.println("Enter value in object 2");
obj2.readpoint();
System.out.println("\f");
System.out.println("value of object1");
obj1.displaypoint();
System.out.println("value of object2");
obj1.displaypoint();
obj3=obj3.midpoint(obj1,obj2);
System.out.println("Position of Mid Point:");
obj3.displaypoint();
}
}

Output:
value of object1
Coordinate x value=2
Coordinate y value=4
value of object2
Coordinate x value=6
Coordinate y value=4
Position of Mid Point:
Coordinate x value=4

Coordinate y value=4
------------------*------------------*------------------*------------------
Question 7: A class Mix has been defined to mix two words, character by character,
in the following manner:
The first character of the first word is followed by the first character of the second
word and so on. If the words are of different length, the remaining characters of the
longer word are put at the end.
Class name: Mix
Data members/instance variables:
wrd: to store a word.
len: to store the length of the word.
Member functions/methods:
Mix(): default constructor to initialize the data members with legal initial values.
void feedWord(): to accept the word in uppercase.
void mixWord(Mix p, Mix q): mixes the words of objects p and q as stated above
and stores the resultant word in the current object.
void display(): displays the word.
Specify the class Mix giving details of the constructor, void feedWord(), void
mixWord(Mix, Mix) and void display(). Define the main() function to create
objects and call the functions accordingly to enable the task.

Program:
import java.util.*;
class Mix
{
Scanner sc = new Scanner (System.in);
String wrd;
int len;
Mix()
{
len=0;
wrd="";
}
void feed_word()
{
wrd=sc.nextLine();
wrd= wrd.toUpperCase ();
len=wrd.length();
}
void mix_wrd(Mix p,Mix q)
{
int i,j,t;
if (p.len<q.len)
t=p.len;
else
t=q.len;
for(i=0;i<t;i++)
{
wrd=wrd+p.wrd.charAt(i)+q.wrd.charAt(i);
if (p.len!=q.len)
{if(p.len>q.len)
wrd=wrd+p.wrd.substring(t);
else
wrd=wrd+q.wrd.substring(t);
}
len=p.len+q.len;
}
}
void display()
{
System.out.println(wrd);
}
public static void main()
{
Mix obj1=new Mix();
Mix obj2=new Mix();
Mix obj3=new Mix();
System.out.println("enter first word in capital letters");
obj1.feed_word();
System.out.println("enter second word in capital letters");
obj2.feed_word();
System.out.println("First Word");
obj1.display();
System.out.println("Second Word");
obj2.display();
obj3.mix_wrd(obj1,obj2);
System.out.println("resultant string");
obj3.display();
}
}
Output:
enter first word in capital letters
HELLO
enter second word in capital letters
WORLD
First Word
HELLO
Second Word
WORLD
resultant string
HWEOLRLLOD

enter first word in capital letters


MARVELLOUS
enter second word in capital letters
MAZEL
First Word
MARVELLOUS
Second Word
MAZEL
resultant string
MMLLOUSAALLOUSRZLLOUSVELLOUSELLLOUS
------------------*------------------*------------------*-----------------
QUESTION 8:Define an abstract class Bank and a sub class Transaction with the
details given below:

Abstract Class name: Bank


Data members/instance variables:
Balance: to store the initial balance.

Member functions/methods:
Abstract void Deposit(): an abstract function declaration
Abstract void Withdraw():an abstract function declaration

Abstract Class name: Transaction


Data members/instance variables:
depamt: to store the amount to deposit.
Wamt: to store the amount to withdraw.

Member functions/methods:
Abstract void Deposit(): an abstract function declaration
Abstract void Withdraw():an abstract function declaration
Void show(): displays the deposit withdrawal and current balance amount.

abstract class Bank


{
double balance; abstract void Deposite();
abstract void Withdraw();
}

import java.util.*;
class Transaction extends Bank
{
Scanner sc = new Scanner(System.in);

double depamt,Wamt;
Transaction(double b)
{
balance = b;
}
void Deposite()
{
System.out.println("Enter deposite amount "); depamt = sc.nextDouble();
System.out.println(" deposit Amount "+depamt); System.out.println("Amount
before deposit amount "+balance); balance +=depamt;
System.out.println("Amount after deposit amount "+balance);
}
void Withdraw()
{
System.out.println("Enter withdrawal amount "); Wamt = sc.nextDouble();
System.out.println(" Withdrawal Amount "+ Wamt); System.out.println("Amount
before deposit amount "+balance);

if(balance-Wamt>=500)
{
balance -=Wamt;
System.out.println("Amount after deposit amount "+balance);
}
else
System.out.println("Insufficient fund ");
}
public void Show()
{
Deposite(); Withdraw();
}

public static void main( double bal)


{
Transaction obj = new Transaction(bal);
obj.Show();
}
}
OUTPUT:
Enter deposite amount
10000
deposit Amount 10000.0
Amount before deposit amount 100.0
Amount after deposit amount 10100.0
Enter withdrawal amount
6000
Withdrawal Amount 6000.0
Amount before deposit amount 10100.0
Amount after deposit amount 4100.0

QUESTION 10:WRITE A PROGRAM TO CALCULATE SALARY OF A


SALESMAN ALONG WITH HIS NAME AND ALLOWANCES.
import java.util.*;
class Info
{
String name;
double sal;
Info(String na,double salary)
{
name=na;
sal=salary;
}
public void show()
{
System.out.println("Name : "+ name);

System.out.println("Salary : "+ sal);


}
}

import java.util.*;
class Salary extends Info
{
double allowance,total;
Salary(String na, double salary)
{
super(na,salary); allowance=0.0; total=0.0;
}

public void compute()


{
if(sal>20000) allowance = 0.11*sal; else
allowance=0.0;
total = sal +allowance;
}
public void show()
{
super.show();
System.out.println("Allowance = "+ allowance); System.out.println("total Salary =
"+ total);
}

public static void main(String nn,double ss)


{
Salary ob = new Salary(nn,ss); ob.compute();
ob.show();
}
}
OUTPUT:
Name : YUGAL KISHORE MISHRA
Salary : 10000.0
Allowance =100.0
total Salary = 10100.0
4. RECURSIVE PROGRAMMING

Question 1: Write a recursive program to enter a number and check whether it is


palindrome or not.

Program:

import java.util.*;
class Palindrome
{
int num,revnum;
Palindrome()
{
num=0;revnum=0;
}
void accept()
{
Scanner sc =new Scanner(System.in);
System.out.println("enter the value of num ");
num=sc.nextInt();
}
int reverse(int y)
{
int k = (y+"").length();
if(k==1)
return y;
else
return (y%10)*(int)(Math.pow(10,k-1))+reverse(y/10);
}
void check()
{
revnum=reverse(num);
if(revnum==num)
System.out.println("Number is palindrome " +num);
else
System.out.println("Number is not palindrome " +num);
}
public static void main()
{
Palindrome ob = new Palindrome();
ob.accept();
ob.check();
}
}
Output:

enter the value of num


369
Number is not palindrome 369
enter the value of num
121
Number is palindrome 121

------------------*------------------*------------------*------------------
Question 2: Write a recursive program to accept a number and check
whether it is a happy number or not.

Program-
import java.util.*;
class Happy
{
int num;
Happy()
{
num=0;
}
void getnum(int nn)
{
num=nn;
}
int sum_sq_digits(int x)
{
int r;
if(x==0)
return 0;
else
{ r=x
%10;
return ((r*r)+sum_sq_digits(x/10));
}
}
void ishappy()
{
int p=num;
while(p>9)
{
p=sum_sq_digits(p);
}
if(p==1)
System.out.println(num+" is a happy number");
else
System.out.println(num+" is not a happy number");
}
public static void main(int number)
{
Happy ob = new Happy();
ob.getnum(number);
ob.ishappy();
}
}

OUTPUT:
68 is a happy number
76 is not a happy number
------------------*------------------*------------------*------------------

Question 4: Write a program to express digits of integer in words using


recursive technique.

Program:
import java.util.*;
class convert
{
int n;
convert()
{ n=
0;
}
void inpnum()
{
int t;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number ");
n=sc.nextInt();
t=n;
int r,s=0;
while(t>0)
{ r=t
%10;
t=t/10;
s=s*10+r;
}
extdigit(s);
}
void extdigit(intl i)
{
int r=0;
if(i==0)
return ;
else
{ r=i
%10;
num_to_words(r);
extdigit(i/10);
}
}
void num_to_words(int num)
{
String
ar[]={"Zero","One","Two","three","Four","Five",
"six","Seven","Eight","Nine","Ten"};
System.out.print(ar[num]+" ");
}
public static void main()
{
convert obj = new convert();
obj.inpnum();
}

OUTPUT:
Enter the number
245
Two Four Five
Enter the number
546
Five Four six
------------------*------------------*------------------*------------------
Question 6: Write a program to convert a decimal number into its equivalent octal
number.

Program:
class Decioct
{
int n, oct;
Decioct()
{

n=0;
oct=0;
}
void getnum(int nn)
{
n=nn;
}
void deci_oct()
{
int r;
if(n==0)
return;
else
{

r=n%8;
n=n/8;
deci_oct();
oct=(oct*10)+r;
}
}
void show()
{
System.out.println("Decimal No="+n);
deci_oct();
System.out.println("Octal No"+oct);
}
public static void main(int num)
{
Decioct obj=new Decioct();
obj.getnum(num);
obj.show();
}

Output:

Decimal No=12
Octal No14
Decimal No=10
Octal No12

------------------*------------------*------------------*------------------
Question 7:Design a class Disarium to check if a given number is a disarium
number or not. Some of the members of the class are given below:

Class name: Disarium


Data members/instance variables:
int num: stores the number.
int size: stores the size of the number.
Methods/Member functions:
Disarium(int nn): parameterized constructor to initialize the data members num =
n and size = 0.
void countDigit(): counts the total number of digits and assigns it to size.
int sumOfDigits(int n, int p): returns the sum of the digits of the number ‘n’ to
the power of their respective positions ‘p’ using recursive technique.
void check(): checks whether the number is a disarium number and displays the
result with an appropriate message.
Specify the class Disarium giving details of the constructor, void countDigit(), int
sumOfDigits(int, int) and void check(). Define the main() function to create an
object and call the functions accordingly to enable the task.

Program:

import java.util.*;
class Disarium
{

int num;
int size;
Disarium(int nn)
{
num=nn;
size=0;
}

void countdigit()
{
int p=num;
while(p>0)
{
p=p/10;
size++;
}

}
int sumofdigits(int n,int p)
{
int d,sum=0;
for(int i=p-1;i>=0;i--)
{
d=n/(int)(Math.pow(10,i));
sum=sum+(int)(Math.pow(d,p-i));
n=n%(int)(Math.pow(10,i));
}
return sum;
}
void check()
{
if(sumofdigits(num,size)==num)
System.out.println("Disarium Number");
else
System.out.println("Not a Disarium Number");

}
public static void main()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int no=in.nextInt();
Disarium ob = new Disarium(no);
ob.countdigit();
ob.check();

}
}

Output:
Enter a number
135
Disarium Number

Enter a number
121
Not a Disarium Number
------------------*------------------*------------------*------------------
Question8:
A library issues a book on rental basis at a 2% charge on the cost price of the
book per day. As per rules of the library, a book can be retained for 7 days
without any fine. If the book is returned after 7 days, a fine will also be charged
for the excess days as per the chart given below:
Number of excess days fine per day(Rs.)
1 to 5 2.00
6 to 10 3.00

Above 10 days 5.00


Design a class Library and another class Compute to perform the task. The
class details are as given below:
Class name: Library
Data members/instance variables:
Name, author: string variables to store the name of the book and author
name.
P: price of the book in decimals.
Member functions/methods:
Library(String n, String a, double np): parameterized constructor to assign the
parameters name = n, author = a and p = np.
Void show(): display the book details.
Class name: Compute
Data members/instance variables:
D: number of days taken in returning the book. R:
to store the fine.
Member functions/methods:
Compute(….): Parameterized constructor to assign values to data members of both
the classes.
Void fine(): calculates the fine for excess days.
Void display(): display the book details along with the number of days, fine and
total amount to be paid as fine. The amount is calculated as: (2% of price of
book*total number of days) + fine.
Specify the class Library giving details of the constructor and void show(). Using
the concept of Inheritance, specify the class Compute giving details of the
constructor and functions void fine() and void display(). Do not write the main()
function and algorithm.

Program:
class Library
{
String name, author;
double p;
Library(String n, String a, double np)
{
name=n;
author=a;
p=np;
}

void show()
{
System.out.println("Name of book="+name);
System.out.println("author Name:"+author);
System.out.println("Price"+p);
}
}

class Compute extends Library


{
int d;
double r;
Compute(String n, String a, double np, int day)

{
super(n,a,np);
d=day;
r=0;

}
void fine()
{
if(d>7)
{
int dd = d-7;
if(dd>=1&&dd<=5)
r=dd*2.0;
if(dd>5&&dd<=10)
r=dd*3.0;
if(dd>10)
r=dd*5.0;
}
else
r=0.0;
}
void display()
{
show();
System.out.println("Number of days="+d);
System.out.println("Fine="+r);
double amt=(p*0.02)*d+r;
System.out.println("Total amt to be paid as fine="+amt);
}
public static void main(String na, String au, double price, int days)
{
Compute obj = new Compute(na, au, price, days);
obj.fine();
obj.display();

}
}

Output:

Name of book=Discovery of India


author Name:Jawaharlal Nehru
Price300.0
Number of days=15
Fine=24.0
Total amt to be paid as fine=114.0

------------------*------------------*------------------*------------------
Question 9:
A super class Stock has been defined to store the details of the stock of a retail
store. Define a subclass Purchase to store the details of the items purchased with
the new rate and updates the stock. Some of the members of the classes are given
below:
Class name: Stock
Data members/instance variables:
item: to store the name of the item.
qty: to store the quantity of an item in stock.
rate: to store the unit price of an item.
amt: to store the net value of the item in stock.
Member functions:
Stock(…): parameterized constructor to assign values to the data members.
void display(): to display the stock details.

Class name: Purchase


Data members/instance variables:
pqty: to store the purchased quantity.
prate: to store the unit price of the purchased item.
Member functions/methods:
Purchase(…): parameterized constructor to assign values to the data members of
both classes.
void update(): to update stock by adding the previous quantity by the purchased
quantity and replace the rate of the item if there is a difference in the purchase rate.
Also update the current stock value as:
(quantity * unit price)
void display(): to display the stock details before and after updating.
Specify the class Stock, giving details of the constructor and void display().
Using concept of inheritance, specify the class Purchase, giving details of the
constructor, void update() and void display().

Program:
class Stock
{
String item;
int qty, rate, amt;
Stock(String it,int q, int r)
{
item=it;
qty=q;
rate=r;
amt=qty*rate;

}
void show()
{
System.out.println("Name of the item:"+item);
System.out.println("Quantity of item in stock->"+qty);
System.out.println("Net value of item in stock in rupees"+amt);
}

}
class Purchase extends Stock
{
int pqty,prate;
Purchase(String it, int q, int r, int pq, int pr)
{
super(it,q,r);
pqty=pq;
prate=pr;
}

void update()
{
qty=pqty;
if(prate!=rate)
rate=prate;
amt=qty*rate;
}
void display()
{
System.out.println("Stock details before updation");
super.show();
System.out.println("After Updation");
update();
super.show();

}
}

Output:
Stock details before updation
Name of the item:Dairy Milk
Quantity of item in stock->200
Net value of item in stock in rupees1000
After Updation
Name of the item:Dairy Milk
Quantity of item in stock->300
Net value of item in stock in rupees1200

------------------*------------------*------------------*------------------

Question 10:
Design a class Change to perform string related operations.
The details of the class are given below:
Class name: Change
Data Members/instance variables:
str: stores the word
newstr: stores the changed word
len: store the length of the word
Member functions:
Change(): default constructor

void inputword( ): to accept a 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, giving details of the Constructor ( ), 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.
Program:

import java.util.*;
class Change
{
String str,newstr;
int len;
Change()

{
str="";
newstr="";
len=0;
}

void inputword()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter word");
str=sc.nextLine();
len=str.length();

}
char caseconvert(char ch)
{
if(Character.isLowerCase(ch))
ch=Character.toUpperCase(ch);
else
ch=Character.toLowerCase(ch);
return ch;
}

void recchange(int l)
{
char ch;
if(l==len)
return;
else
{

ch=str.charAt(l);
ch=caseconvert(ch);
newstr=newstr+ch;
recchange(l+1);
}
}
void display()
{
System.out.println("Original Word:"+ str);
System.out.println("Modified Word="+newstr);
}
public static void main()
{
Change obj =new Change();
obj.inputword();
obj.recchange(0);
obj.display();
}

}
Output:

Hello
Original Word:Hello
Modified Word=hELLO
Enter word
magnificient

Original Word:magnificient
Modified Word=MAGNIFICIENT

------------------*------------------*------------------*------------------
5.DATA STRUCTURE

Question 1:
Dequeue is an entity which can hold 200 elements. This data structure allows the
insertion and deletion of elements from both the ends I.e. front and rear. The
details of the class DeQueue are as follows
Class name: DeQueue
Data members/instance variable:
Dque[]: integer array to hold maximum 200 elements
Cap: integer to store the maximum limit of dequeue
Front : integer to point to the index of the front end of the dequeue
Rear: integer to point to the index of the rear end of the dequeue
Member functions/methods:
Dequeue(int lim): constructor to initialize cap=lim, front=0 and rear =-1.

void push Atrear(int num): adds the integer num to the rear of dequeue if
possible, otherwise print a message “Overflow from rear”
void pushAtFront(int num): adds the integer num to the front of the dequeue if
possible, otherwise print a message “Overflow from front”.
Int PopFront(): removes an integer and return from the front of dequeue if
dequeue is not empty, otherwise print a message “Dequeue is empty” and returns
–9999.
Int PopRear(): removes an integer and return from the rear of dequeue if dequeue
is not empty, otherwise print a message “Dequeue is empty” and returns –9999.
void DequeueDisplay(): to display the elements of dequeue if dequeue is not
empty, otherwise display a message “Dequeue is empty”.
Specify the class Dequeue giving the details of the constructor and the functions
void pushAtRear(int), void pushAtFront(int), int PopFront(), intPopRear() and
void DequeueDisplay(). Define a main() function to create an object and call the
methods to enable all the dequeue operations mentioned above.
Program:

import java.util.*;
class Dequeue
{
int Dque[]= new int[200];
int front,rear,cap;
Dequeue()
{

for(int i=0;i<200;i++)
{
Dque[i]=0;
}
}
Dequeue(int lim)
{
cap = lim;
rear=-1;
front=0;
}

public void pushAtRear(int num)


{
if(rear<cap)
{
rear++;
Dque[rear]=num;
}
else
System.out.println( "Overflow from rear ");
}
void pushAtFront(int num)
{
if(front>0)
{
front--;
Dque[front]=num;
}
else
System.out.println( "Overflow from Front ");
}
public int PopFront()
{
int p;
if(front>=0&& front<=rear)
{
p=Dque[front];
front++;
return p;
}
else
{
p=-9999;
System.out.println("DEQUEUE IS EMPTY ");
return p;
}

}
public int PopRear()
{
int p;
if(rear>=front && rear>=0)
{
p= Dque[rear];
rear--;
return p;
}
else
{
p=-9999;
System.out.println("DEQUEUE IS EMPTY ");
return p;
}
}
public void DqueueDisplay()
{
int i;
if(front>=0&& front<=rear)
{
for( i= front ;i<=rear;i++)
{
System.out.print(Dque[i]+" -> ");
}
System.out.println("\n");
}
else
System.out.println("DEQUEUE IS UNDERFLOW");
}
public static void main(int C)
{
Dequeue obj = new Dequeue(C);
char ch ='y';
Scanner sc = new Scanner(System.in);
int v,choice;
do
{
System.out.println("\f");
System.out.println("1. FOR PUSH AT REAR IN DEQUEUE ->");
System.out.println("2. FOR PUSH AT FRONT IN DEQUEUE ->");
System.out.println("3. FOR POP FROM FRONT IN DEQUEUE ->");
System.out.println("4. FOR POP FROM REAR IN DEQUEUE ->");
System.out.println("5. FOR DISPLAY DATA OF DEQUEUE ->");
System.out.println("6. FOR EXIT ->");
System.out.println("ENTER YOUR CHOICE ->");
choice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("ENTER ELEMENT TO BE INSERTED DATA FORM
REAR SIDE IN Dequeue->");
v=sc.nextInt();
obj.pushAtRear(v);
break;
case 2:

System.out.println("ENTER ELEMENT TO BE INSERTED DATA FORM


FRONT SIDE IN Dequeue->");
v=sc.nextInt();
obj.pushAtFront(v);
break;
case 3:
v=obj.PopFront();
if(v!=-9999)
System.out.println("Delete element from DEQUEUE -> "+ v);
break;
case 4:

v=obj.PopRear();
if(v!=-9999)
System.out.println("Delete element from DEQUEUE -> "+ v);
break;
case 5:
obj.DqueueDisplay();
break;
case 6:

System.exit(0);
default:
System.out.println("WRONG CHOICE ");
}
System.out.println("EXECUTION OF DEQUEUE OPERATION AGAIN (Y/N ) -
>");
ch= sc.next().charAt(0);
}
while(ch=='Y' || ch =='y');
}
}

------------------*------------------*------------------*------------------
Question 2: Class name: circular_queue
Data members/instance variable:
int cque[]
int maxsize
int rear
int front

Member functions/methods:
circular_queue(int size)
void push (int item)
void pop()
void display()

public static void main(int C)

Program:
import java.util.*;
class circular_queue
{
int maxsize,rear,front;
int cque[];
circular_queue(int size)
{

maxsize= size;
cque = new int[maxsize];
rear =-1;
front =-1;
}
void push (int item)
{
if(((rear+1)%maxsize)==front)
System.out.println("circular queue is full ");
else
{

if(rear ==front && front ==-1)


{
front++;
}
rear =(rear+1)%maxsize;
cque[rear]=item;
}

}
void pop()
{
int p;
if(rear ==front && rear ==-1)
System.out.println("circular queue is empty ");
else
{

p=cque[front];
if(rear ==front)
{
rear=-1;
front=-1;
}
else
{
front=(front+1)%maxsize;
}
System.out.println(p+" is deleted element ");
}
}
void display()
{
int tempfront=front,i;
if(rear ==front && rear==-1)
System.out.println("circular queue is empty ");
else
{

for(i=0;i<maxsize;i++)
{
if(tempfront!=rear)
{
System.out.print(cque[tempfront]+"--->");
tempfront= (tempfront+1)%maxsize;
System.out.println();
}
else
{
System.out.print(cque[rear]+" ");
break;
}
}
}
}
public static void main(int C)
{
circular_queue obj = new circular_queue(C);
char ch ='y';
Scanner sc = new Scanner(System.in);
int v,choice;
do
{
System.out.println("\f");
System.out.println("1. FOR PUSH DATA IN CQUEUE ->");
System.out.println("2. FOR POP DATA FROM CQUEUE ->");
System.out.println("3. FOR DISPLAY DATA OF CQUEUE ->");
System.out.println("4. FOR EXIT ->");
System.out.println("ENTER YOUR CHOICE ->");
choice=sc.nextInt();
switch(choice)

{
case 1:
System.out.println("ENTER ELEMENT TO BE INSERTED IN QUEUE ->");
v=sc.nextInt();
obj.push(v);
break;
case 2:

obj.pop();
break;
case 3:
obj.display();
break;
case 4:

System.exit(0);
default:
System.out.println("WRONG CHOICE ");
}
System.out.println("EXECUTION OF CQUEUE OPERATIONAGAIN (Y/N ) -
>");
ch= sc.next().charAt(0);
}
while(ch=='Y' || ch =='y');
}
}

------------------*------------------*------------------*------------------
Question 4:
Stack is a kind of data structure which can hold elements. The stack restriction is
that an element can only be added or removed from the top only
I.e. applies LIFO format. To details of class stack are as follows:
Class name: stack
Data members/instance variables:
Int stk[]: the array to hold the integer elements of maximum 200.
Int capacity: the maximum capacity of the integer array.
Int top: to point to the index of the topmost element of the stack.
Member functions/ methods:
Stack(): constructor to initialize 0 to each location of the array stk[].
Stack(int cap): constructor to initialise the cap to capacity and –1 to top.
Void pushItem(int val): to push val into the stack stk[]on the top if possible,
otherwise outputs a message “Stack overflow”.
Int popItem(): removes the integer from the top of stack and returns it, if stack is
not empty, otherwise outputs a message “Stack underflow” and returns-9999.
Void print_stack(): to display the elements of stack if possible I.e. if the stack is
not empty, otherwise display a message “stack underflow”.
Specify the class stack giving the details of the constructors and functions void
pushItem(int val), int popItem() and void print_stack(). Define a main()function to
create an object and call the methods to enable the push, pop operations and
printing of the stack element.

Program:
import java.util.*;
class stack
{
int stk[]= new int[200];
int top,capacity;
stack()
{
for(int i=0;i<200;i++)
{
stk[i]=0;
}
}
stack(int cap)
{
capacity = cap;
top=-1;
}
public void pushitem(int val)
{
if(top<capacity)
{
top++;
stk[top]=val;
}

else
System.out.println(" STACK IS OVERFLOW ");
}
public int popItem()
{
int p;
if(top>=0)
{
p=stk[top];
top--;
return p;
}

else
{
p=-9999;
System.out.println("STACK IS UNDERFLOW");
return p;
}
}
public void print_stack()
{
int i;
if(top>=0)
{
for( i= top ;i>=0;i--)
{
System.out.print(" <- "+stk[i]);
}
System.out.println("\n");
}
else
System.out.println("STACK IS UNDERFLOW");
}
public static void main(int C)
{
stack obj = new stack(C);
char ch ='y';
Scanner sc = new Scanner(System.in);
int v,choice;
do

{
System.out.println("\f");
System.out.println("1. FOR PUSH DATA IN STACK ->");
System.out.println("2. FOR POP DATA FROM STACK ->");
System.out.println("3. FOR DISPLAY DATA OF STACK ->");
System.out.println("4. FOR EXIT ->");
System.out.println("ENTER YOUR CHOICE ->");
choice=sc.nextInt();
switch(choice)

{
case 1:
System.out.println("ENTER ELEMENT TO BE INSERTED IN STACK->");
v=sc.nextInt();
obj.pushitem(v);
break;
case 2:
v=obj.popItem();
if(v!=-9999)
System.out.println("Delete element from STACK -> "+ v);
break;
case 3:

obj.print_stack();
break;
case 4:
System.exit(0);
default:
System.out.println("WRONG CHOICE ");

}
System.out.println("EXECUTION OF STACK OPERATION AGAIN (Y/N)->");
ch= sc.next().charAt(0);
}
while(ch=='Y' || ch =='y');
}
}

-----------------*------------------*------------------*------------------
Question 6: Define a class 'queue' with the following details: Class
name : queue
Data members/instance variables :
que[] : integer array to hold 100 elements.
capacity : integer to store the maximum storage capacity of the array.
front : integer to point to the index of front of the queue.
rear : integer to point to the index of rear of the queue.
Member functions/methods:
queue(): constructor to initialize 0 in each memory cell of que[].
queue(int limit) : constructor to assign capacity=limit, front=0 and
rear=-1.
void dataPush(int num) : adds the integer num to the rear of the queue, if
possible, otherwise ouputs a message "Queue is full:".
int dataPOP() : removes the integer from the front of queue using FIFO and returns
it, if queue is not empty, otherwise
void QueueDisplay() : to display the elements of current queue, if queue is
not empty, otherwise display a message "Queue underflow".
Specify the class queue giving the details of the constructors and the functions
void dataPush(int), int dataPop() and void QueueDisplay().
Define a main() function to create an object and call the methods to enable the
push, pop operations and printing of the queue elements.

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

int que[]= new int[100];


int front, rear, capacity;
queue()
{

for(int i=0;i<100;i++)
{
que[i]=0;
}
}
queue(int limit)
{
capacity=limit;
rear=-1;
front=-1;

}
public void datapush(int num)
{
if(rear<capacity)
{
rear++;
que[rear]=num;
if(front<0)
front++;
}

else
System.out.println("Queue is full");
}
public int datapop()
{
int p;
if(front>=0&&front<=rear)
{
p=que[front];
front++;
return p;
}

else
{
p=-9999;
System.out.println("Queue is empty");
return p;
}
}
public void QueueDisplay()
{
int i;
if(front>=0&&front<=rear)
{
for(i=front;i<=rear;i++)
{
System.out.println(que[i]+"->");
}
System.out.println("\n");
}
else
System.out.println("Queue is Underflow");
}
public static void main(int C)
{
queue obj = new queue(C);
char ch = 'y';
Scanner sc = new Scanner(System.in);
int v, choice;
do

{
System.out.println("\f");
System.out.println("1.for Push Data in Queue->");
System.out.println("2.for Pop Data from Queue->");
System.out.println("3.for Display Data of Queue->");
System.out.println("4.for Exit->");
System.out.println("Enter Your Choice");
choice = sc.nextInt();
switch(choice)
{

case 1:
System.out.println("Enter element to be inserted in queue->");
v=sc.nextInt();
obj.datapush(v);
break;
case 2:
v=obj.datapop();
if(v!=-9999)
System.out.println("Delete element from Queue->"+v);
break;
case 3:
obj.QueueDisplay();
break;
case 4:
System.exit(0);
default:
System.out.println("Wrong Choice");

}
System.out.println("Execution of Queue Operation Again(Y/N)->");
ch=sc.next().charAt(0);
}

while(ch=='Y'||ch=='y');
}
}

-----------------*------------------*------------------*------------------
QUESTION 7:Write a program to execute queue of size 200 and to check whether
the stack is overflow or underflow and delete any data from queue and display the
deleted data.

import java.util.*;
class Queue
{
int que[] = new int[200];
int cap,rear,front;
Queue()
{
for(int i=0;i<=200;i++)
que[i]=0;
}
Queue(int c)
{
cap = c ;
front =-1;
rear =-1;
}
void pushItem(int val)
{
if(rear<cap)
{
rear++; que[rear] =val;
if(front<0)
front++;
}
else
{
System.out.println(" Queueu overflow ");
}
}

int popItem()
{
int p = -9999;
if(front>=0 && front<=rear)
{
p =que[front];
front++;
//p=stk[top--];
return p;
}
else
{
System.out.println(" queue is underflow");
return p;
}
}
void print_queue()
{
int i;
if(front>=0 && front<=rear)
{
for(i=front;i<=rear;i++)
{
System.out.print(que[i] + "-> ");
}
}
else
System.out.println("queue under flow ");
}

static void main(int capacity)


{
Queue qu = new Queue(capacity);
System.out.println();
qu.print_queue();
qu.pushItem(90);
qu.pushItem(85);
qu.pushItem(73);

qu.pushItem(45);
System.out.println();
qu.print_queue();
System.out.println();
int ele = qu.popItem();
if(ele!= -9999)
System.out.println("Deleted element from queue " + ele);
qu.print_queue();
System.out.println();
}
}
QUESTION 9:Write a stack program with size 50 and to check whether the stack is
overflow and underflow or not and form new stack by push and pop.
class Stack
{
int stk[] = new int[50];
int top,cap;
Stack(int nn)
{
cap = nn;
top = -1;
}
void push(int num)
{
if(top<cap)
{
top++; stk[top]=num;
}
else
System.out.println("Stack is Overflow ");
}
void pop()
{
int p ; if(top>=0)
{
p=stk[top]; top--;
System.out.println("Removed ele = "+ p);
}
else
System.out.println(" Stack is under flow ");
}
void display()
{
int i; if(top>=0)

{
for(i=top; i>=0 ;i--)
System.out.print(stk[i]+" - ");
}

else

System.out.println(" Stack is under flow ");

public static void main(int c)


{
Stack obj = new Stack(c);
obj.display();
System.out.println();
obj.push(78);
obj.display();
System.out.println();
obj.push(88);
obj.display();
System.out.println();
obj.push(89);
obj.display();
System.out.println();
obj.pop();
obj.display();
System.out.println();
}
}
QUESTION 10:Write a program to execute dequeue and dequeue elements from a
queue.

import java.util.*;
class Dequeue
{
int que[] = new int[200];
int cap,rear,front;
Dequeue()
{
for(int i=0;i<=200;i++)
que[i]=0;
}
Dequeue(int c)
{
cap = c ; front =-1;
rear =-1;
}
void pushAtrear(int val)
{
if(rear<cap)
{
++rear;
que[rear] =val;
if(front<0)
front++;
}
else
{
System.out.println(" Dequeueu overflow ");
}
}
void pushAtfront(int val)
{
if(front>0)
{ --front;
else
{
System.out.println(" Dequeueu overflow at front side ");
}
}
int popAtfront()
{
int p = -9999;
if(front>=0 && front<=rear)
{
p =que[front];
front++;
return p;
}
else
{
System.out.println(" Dequeue is underflow"); return p;
}
}
int popAtrear()
{
int p = -9999;
if(rear>=front)
{
p =que[rear--]; return p;
}
else
{
System.out.println(" Dequeue is underflow");

void print_Dequeue()
{
int i;
if(front>=0 && front<=rear)
{
for(i=front;i<=rear;i++)
{
System.out.print(que[i] + "-> ");
}
}
else
System.out.println("Dequeue under flow ");
}
static void main(int capacity)
{
Dequeue qu = new Dequeue(capacity);
System.out.println();
qu.print_Dequeue();
qu.pushAtrear(90);
qu.pushAtrear(85);
qu.pushAtrear(73);
qu.pushAtrear(45);
System.out.println();
qu.print_Dequeue();
System.out.println();
int ele = qu.popAtfront();
if(ele!= -9999)
System.out.println("Deleted element from queue " + ele);
qu.print_Dequeue();
System.out.println();
}
}

System.out.println("Deleted element from queue " + ele);


qu.print_Dequeue();
System.out.println();
qu.pushAtfront(111);
qu.print_Dequeue();
ele = qu.popAtrear();
System.out.println();
if(ele!= -9999)
System.out.println("Deleted element from rear end Dequeue " +
qu.print_Dequeue();
6.Practical Related Programming

Question 1: Write a program to input a natural number less than 1000 and
display it in words test your program on some random data.

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

public void main()


{
Scanner sc =new Scanner(System.in);
int num, h=0;
System.out.println("enter number ");
num=sc.nextInt();
String str1[]={" "," ONE "," TWO "," THREE "," FOUR "," FIVE "," SIX ","
SEVEN ", " EIGHTH ", " NINE ", "TEN " ," ELEVEN " ," TWELVE " ,"
THIRTEEN ", " FORTEEN " ,"FIFTEEN " , " SIXTEEN " , "SEVENTEEN" ,"
EIGHTEEN " , "NINETEEN " };
String str2[]={" " ," ", " TWENTY "," THIRTY "," FORTY ", " FIFTY ", " SIXTY
" ," SEVENTY ", " EIGHTY " , "NINTY " };
String wd="";
if(num<1000)
{

if(num>=100)
{
h=num/100;
System.out.print(str1[h]+" HUNDRED
"); num = num%100;
}

if(num>19)
{
System.out.print(str2[num/10]+" " +str1[num%10]);
}
if(num<20)
System.out.print(str1[num]);
}
else
System.out.print("OUT OF RANGE ");
}
}

Output:
enter number
999
NINE HUNDRED NINTY NINE

enter number
512
FIVE HUNDRED TWELVE

-----------------*------------------*------------------*------------------
Question 2: 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’(Goldbach Number).
Program:

import java.util.*;
class goldbach
{

public static void main()


{
int n,i,j;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to be checked");
n=sc.nextInt();
if(n%2!=0||n<0||(n<9&&n>50))
System.out.println("Invalid Input");
else
System.out.println(n+" is a goldbach number");
System.out.print("Odd Prime pairs are");
for(i=1;i<n;i+=2)
{

for(j=i;j<n;j++)
{
if((i%2!=0 && j%2!=0) && (i+j==n))
System.out.println(i+","+j);
}
}
}
}

Output:

Enter the number to be checked


14
14 is a goldbach number
Odd Prime pairs are1,13
3,11
5,9

7,7

Enter the number to be checked


49
Invalid Input

-----------------*------------------*------------------*------------------
Question 3:
Write a program to declare a matrix A[][] of order (M*N) where 'M' is the number
of rows and 'N' is the number of columns
such as the value of both 'M' and'N' must be greater than 2 and less than 10. Allow
the user to input integers into this matrix.
Perform the following tasks on the matrix.
(i) Display the original matrix.
(ii) Sort each row of the matrix in ascending order using any standard
sorting technique.
(iii) Display the changed matrix after sorting each row.
Test your program for the following data and some random data.

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

public static void main()


{
Scanner sc = new Scanner(System.in);
int AR[][], m, n, temp;
System.out.print("INPUT : M =");
m=sc.nextInt();
System.out.print("N =");
n=sc.nextInt(); if(m<=2||m>=10||
n<=2||n>=10)
System.out.println("MATRIX SIZE OUT OF RANGE");
else
{

AR=new int [m][n];


System.out.print("ENTER ELEMENTS OF MATRIX
OF ORDER"+m+"x"+n+":");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
AR[i][j]=sc.nextInt();
}
}
System.out.println("ORIGINAL MARTRIX");
for(int i=0; i<n; i++)
{

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


{
System.out.print(AR[i][j]+"\t");
}
System.out.println();
}

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


{
for(int j=0; j<n-1-i; j++)
{
{
if(AR[i][j]>AR[i][j+1])
{
temp=AR[i][j]; AR[i]
[j]=AR[i][j+1];
AR[i][j+1]=temp;
}
}
}
}
System.out.println("MATRIX AFTER SORTING ROWS");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
System.out.print(AR[i][j]+"\t");
}
System.out.println();
}
}
}
}
Output:
INPUT : M =3
N =3
ENTER ELEMENTS OF MATRIX OF ORDER3x3:22
5
19

7
36
12
9
13
6
ORIGINAL
MARTRIX 22 5
7 36

9 13
MATRIX AFTER SORTING
ROWS 5 19 22
7 36 12

9 13 6

INPUT : M =12
N =15
MATRIX SIZE OUT OF RANGE

-----------------*------------------*------------------*------------------

Question 4: Write a program to accept a range of numbers and print all the
kaprekar numbers within that range.Also print the frequency of their occurrence.

Program:
import java.util.*;
class kaprekar
{
public static void main()
{
Scanner sc=new Scanner(System.in);
int p,q,i,l,h,sq,freq=0,x,y;
String s,sl,sh;

System.out.println("Enter the lower range of the numbers to be checked");


p=sc.nextInt();
System.out.println("Enter the upper range of the numbers to be checked");
q=sc.nextInt();
System.out.println("List of kaprekar numbers");
for(i=p;i<=q;i++)
{ sq=i*i;
s=Integer.toString(sq);
if(sq<=9)
s="0"+s;

l=s.length();
h=l/2;
sl=s.substring(0,h);
sh=s.substring(h);
x=Integer.parseInt(sl);
y=Integer.parseInt(sh);
if((x+y)==i)
{

System.out.println(i);
freq++;
}
}
System.out.println("Frequency of kaprekar numbers="+freq);
}
}

Output :
Enter the lower range of the numbers to be checked
5
Enter the upper range of the numbers to be checked
60
List of kaprekar numbers
9
45
55
Frequency of kaprekar numbers=3

-----------------*------------------*------------------*------------------
Question 6:
The computer department of the International Cryptological Agency is trying to
decode intercepted messages. The agency's spies have determined that the enemy
decodes messages by first converting all characters to their ASCII values and then
reversing the string.
For example,

consider A-Z (the underscore is just to highlight the space).


The ASCII values of A,<space>,z are 65,32,122 respectively. Concatenate
them to get 6532122, then reverse them to get 2212356 as the coded message.
Write a program which reads a coded message and decodes it. The coded
message will not exceed 200 characters. It will contain only alphabets(A Z, and
a......z) and spaces. ASCII values of A ..... Z are 65 90 and those of
a ...... z are 97 122.

Program:
import java.util.Scanner;
class Decode2
{

public static void main()


{
int i,k,l;
String str1, str2="", str3="", str4="";
char chr, ch;
Scanner in=new Scanner(System.in);
System.out.println("Enter coded string");
str1=in.nextLine();
l=str1.length();
for(i=0;i<l;i++)
{
str2=str1.charAt(i)+str2;
}
i=0;
while(i<1)
{
ch=str2.charAt(i);
if(ch>'1')
{

str3=str2.substring(i,i+2);
k=Integer.parseInt(str3);
chr=(char)k;
i=i+2;

}
else
{
str3=str2.substring(i,i+3);
k=Integer.parseInt(str3);
chr=(char)k;
i=i+3;

}
str4=str4+chr;
}
System.out.println("The original encoded
message:"); System.out.println(str1);
System.out.println("The decoded message:");
System.out.println(str4);
}
}
Output:
Enter coded string
2312179862310199501872356231018117927
The original encoded message:
2312179862310199501872356231018117927
The decoded message:

Have A Nice Day

-----------------*------------------*------------------*------------------

Question 7: Write a program to accept a range of numbers and display all the
automorphic numbers between them. Also give the frequency of their
occurrence.
Program:

import java.util.*;
class automorphic
{

public static void main()


{
int i,l,u,p,c=0,rem,freq=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Lower Limit");
l=sc.nextInt();
System.out.println("Enter Upper Limit");
u=sc.nextInt();
if(l<=2000&&u<=2000&&l<u)
{
System.out.println("The automorphic integers are:");
for(i=(l+1);i<u;i++)
{

p=i;
int s=0;
while(p>0)
{

p=p/10;
c++;
}
p=i*i; rem=p%
((int)Math.pow(10,c)); c=0;
if(rem==i)

{
System.out.println(i);
freq++;
}
}
System.out.println("The frequency of automorphic integers is:"+freq);
}
else
System.out.println("Out of Range");
}
}

Output:
Enter Lower Limit
20
Enter Upper Limit
500
The automorphic integers are:

25
76
376

Enter Lower Limit


3000
Enter Upper Limit
4000
Out of Range
The frequency of automorphic integers is:3

Question 8: Write a program to accept a sentence, that must be terminated by (.)


or (?). The sentence
is valid otherwise invalid.
*To separate word from sentence.
*To find out number of vowels, number of consonants in each word.
make new sentence from each word started with capital letter.
Program:
class Sentence
{
public void main(String st)
{
int i, l, r=0, v=0, c=0;
char ch;
String nstr="",wd="";
l=st.length();
ch=st.charAt(l-1);
if(ch=='.'||ch=='?')
{
st=st.substring(0,l-1)+" ";
l=st.length();
System.out.println("Word\t\t vowel\t\t consonant");
for(i=0;i<l; i++)
{

ch=st.charAt(i);
if(ch!=' ')
{
if(r==0)
ch=Character.toUpperCase(ch);
r++;
if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'||ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch==
'u')
v++;
else
c++;
wd=wd+ch;
}
else
{
nstr=nstr+wd+" ";
System.out.println(wd+"\t\t"+v+"\t\t"+c);
wd="";
v=0;
c=0;
r=0;
}

}
System.out.println("Modified Sentence=");
System.out.println(nstr);
}
else
{
System.out.println("Sentence invalid");
}
}
}

Output
Word vowel consona
nt
Compute 3 5
r
Is 1 1
Fun 1 2

Modified Sentence = Computer Is Fun

-----------------*------------------*------------------*------------------
Question 9:
Write a program to accept a sentence which may be terminated by either '.','?' or
! only( any other character may be ignored). The words may be seperated by more
than
one blank space and are in upper case.
Prepare the following tasks:
(a) Accept the sentence and reduce all extra blank spaces between two words to
a single
blank space.
(b) Accept a word from the user which is apart of the sentence along with
its position
number and delete the word and display the sentence.

Program:
import java.util.*;
class WordRemove
{
public static void main()
{
Scanner in=new Scanner(System.in);
String word,st1,st2="",st3="";
int i,t,n;
char ch;
System.out.println("Enter a sentence ending with (.) or (?) or (!)");
st1=in.nextLine().toUpperCase();
System.out.println("Enter the word to be removed");
word=in.next();
System.out.println("Enter position number of the word to be removed");
n=in.nextInt();
ch=st1.charAt(st1.length()-1);
if(ch=='.'||ch=='?'||ch=='!')
{
StringTokenizer st=new StringTokenizer(st1);
t=st.countTokens();
for(i=1;i<=t;i++)

{
st2=st.nextToken().trim();
if(st2.equals(word)==false||i!=n)
st3=st3+' '+st2;
}

System.out.println("Sentence after removing word:");


System.out.println(st3);
}
else
System.out.println("Invalid Sentence");
}
}

OUTPUT:
Enter a sentence ending with (.) or (?) or (!)
AS YOU SOW,SO SO YOU REAP.
Enter the word to be removed
SO
Enter position number of the word to be removed
4
Sentence after removing word:
AS YOU SOW,SO YOU REAP.
Question 10:
A Prime-Adam integer is a positive integer (without leading zeros) which is a
prirne 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
output them along with the frequency, in the format given below:

Test your program with the and some random data.

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

boolean prime(int n)
{
int k,t=0;
for(k=1;k<=n;k++)
{
if(n%k==0)
t++;
}

if(t==2)
return true;
else
return false;

}
boolean adam(int l)
{
int k=l,r,c=-1,s=0,t,g=0,sq1,sq2;
while(k>0)
{
k=k/10;
c++;
}

k=l;
sq1=l*l;
while(k>0)
{

r=k%10;
k=k/10; s=s+
((int)Math.pow(10,c)*r); c--;
}

sq2=s*s;
t=sq2;
c=-1;
while(t>0)

{
t=t/10;
c++;
}
t=sq2;
while(t>0)
{
r=t%10;
t=t/10; g=g+
((int)Math.pow(10,c)*r); c--;
}

if(g==sq1)
return true;
else
return false;

}
public static void main()
{
Scanner sc=new Scanner(System.in);
primeadam ob=new primeadam(); int
m,n,i,freq=0,con=0;
System.out.println("Enter value of m");
m=sc.nextInt();
System.out.println("Enter value of n");
n=sc.nextInt();
System.out.println("Prime-Adam numbers in the given range are:");
if(m>n)
System.out.println("Faulty Input");
else
{
for(i=m; i<=n; i++)
{
if(ob.prime(i) && ob.adam(i)) //checking for prime-adam number
{
freq++;
System.out.print(i + "\t");
}
}
}
System.out.println("Frequency of prime-adam numbers="+freq);
}
}

Output:
Enter value of m
100
Enter value of n
200
Prime-Adam numbers in the given range are:

101 103 113 Frequency of prime-adam numbers=3


THANK YOU

You might also like