0% found this document useful (0 votes)
11 views102 pages

Project Comp

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

Project Comp

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

QUESTION NUMBER # 1

Suppose you take a positive integer ‘n’ and add its positive
divisors.
e.g if n=18, then sum=1+2+3+6+9+18=39
Ingeneral, when we do this with ‘n’, one of the following three
things will happen
1. If the sum is less than ‘2n’ then ‘n’ is said to be a
Deficient Number
examples 1,2,3,4,5,8,9.
2. If the sum is equal to ‘2n’ then ‘n’ is said to be a Perfect
Number
examples 6,28,496.
3. If the sum is greater than‘2n’ then ‘n’ is said to be a
Abundant Number
examples 12,18,20,24,30.

import java.util.*; /*importing the package for scannar class*/


class number_operation /*starting class*/

int i,no,sum=0; /*Initialization and declaration of variables*/


public static void main(String []args) /*Starting of main()*/

int no;
Scanner sc= new Scanner(System.in);
System.out.println("Enter your number"); /*Entering the
number by the user*/
no= sc.nextInt();
number_operation obj= new number_operation(); /*creation
of the object for the class*/

1
if(no>0) /*cheking for positive number*/

{
obj.num(no); /*calling the function*/

else
{

System.out.println("please enter a positive number");

} /*End of main()*/

void num(int no) /*Starting of num()*/


{
for(i=1;i<=no;i++) /*Starting of for loop*/

{
if(no%i==0)

{
sum=sum+i; /*finding the sum of the divisors*/
}
} /*Ending of for loop*/

if(sum<(2*no)) /*Starting of if-else for checking*/

{
System.out.println("The number is a deficient
number");
}

else if(sum==(2*no))
2
{
System.out.println("The number is a perfect number");
}

else if(sum>(2*no))

{
System.out.println("The number is an abundant
number");

} /* End of num()*/

} /*End of class*/

OUTPUT:

3
Enter your number
9
The number is a deficient number

Enter your number


496
The number is a perfect number

Enter your number


30
The number is an abundant number

ALGORITHM
Step 1: Start
Step 2: The class and the main() is created and the data members
are declared and initialized
Step 3: The number is taken form the user and stored in the
variable ‘n’.
Step 4: If the number is positive then the function is called
Else GOTO STEP8
Step 5: The sum of the divisor is found by:
for(i=1;i<=no;i++)
{
if(no%i==0)
{
sum=sum+i;
}
}

Step 7: If the sum is less then 2n (two times the number) then the
number is printed to be a
Deficient number
If the sum is equal to 2n (two times the number) then the
number is printed to be a
4
Perfect number
If the sum is greater than 2n (two times the number) then
the number is printed to be an
Abundant number

Step 8: End

VARIABLE DESCRIPTION CHART

VARIABLE NAME VARIABLE TYPE VARIABLE


DESCRIPTION
i Integer Loop variable
no Integer Stores the number
inputted by the user
sum Integer Add and stores the
sum of the divisors

QUESTION NUMBER #2:

5
Primorial(#P) is defined to be the product of prime numbers
less thean or equal to ‘p’
For example:
3#: 2*3=6
5#: 2*3*5=30
13#: 2*3*5*7*11*13=30030
This is also called p-prime factorial.
Write a program to find the p=prime factorial of a number
entered by the user.

import java.util.*; /*importing the package for scannar class*/


class primorial/*starting class*/
{
int n,p,i,j; /*Initialization and declaration of variables*/

public static void main(String []args) /*Starting of main()*/


{

Scanner sc = new Scanner(System.in);

System.out.println("Enter your number");/*Entering the


number by the user*/
n = sc.nextInt();
p= 1;
boolean isprime = false;

if(n>1) /*starting of if-else*/


{
System.out.print(n + "#:");
for( i = 2;i<=n;i++) /*Starting of for loop*/
{
isprime = true;

for( j = 2;j<i;j++)
{

6
if(i%j == 0)
isprime = false; /*cheking whether the number is
prime or not*/
}
if(isprime == true)
{
System.out.print(" "+i+" x ");
p *= i; /*finding out the primorial of the number*/
}

}/*Ending of for loop*/


System.out.print("="+p);
}/*end of if-else*/
else
System.out.println("Value of n should be greater than 1");

}/*End of main()*/
}/*End of class*/

OUTPUT:

7
Enter your number
3
3#: 2 x 3 x =6

ALGORITHM
Step 1: Start
Step 2: The class and the main() is created
Step 3: The number is taken from the user and is stored in a
variable.
Step 4: The number entered by the user is checked
if the number is a prime number then primordial is found
out by p*i
else GOTO STEP 5
Step 5: End.

VARIABLE DESTRIPTION CHART

VARIABLE NAME VARIABLE TYPE VARIABLE


DESCRIPTION
n Integer Variable to store the
number entered by the
user
p Integer A variable to store the
primorial of the
number
i Integer Loop control variable
j Integer Loop control variable

QUESTION NUMBER #3:

8
Create an array ‘a’ and perform the following tasks on the
array:
i) Copy the array ‘a’ to another array ‘b’
ii) Reverse the second array
iii) Display the second array
iv) Calculate the dot product of the two arrays as:
∑(a[i]*b[i])

import java.util.*; /*importing the package for scannar class*/


class array/*starting class*/

{
public static void main(String []args) ) /*Starting of main()*/

{
int lim,i,sum=0; /*Initialization and declaration of
variables*/
Scanner sc= new Scanner (System.in);
System.out.println("Enter your limit"); /*entering the limit of the
array*/

lim=sc.nextInt();

int a[]= new int[lim];

System.out.println("Enter your numbers");/*entering the


numbers in the array*/

for(i=0;i<lim;i++)/*start of for loop*/

{
a[i]=sc.nextInt();

}/*end of for loop*/


int b[]= new int[lim];/*new array created*/

9
for(i=0;i<lim;i++)
{
b[i]=a[i];/*array ‘a’ copied to array ‘b’*/
}
System.out.println(“The reversed array is:”);
for(i=lim-1;i>=0;i++)
{

System.out.println(b[i]);/*the reverse array is


printed*/
}

for(i=0;i<lim;i++)
{
sum=sum+(a[i]*b[i]);
}
System.out.println("the dot produt of the two arrays is"
+sum);
}/*end of main()*/
}/*end of class*

OUTPUT:

10
Enter your limit
10
Enter your numbers
1
2
3
4
5
6
7
8
9
10
The reversed array is :
10
9
8
7
6
5
4
3
2
1
the dot product of the two arrays is: 385

ALGORITHM
Step 1: Start
Step 2: The size of the array is taken from the user and an array is
created
Step 3: The numbers are taken from the user and stored in the array
‘a’
Step 4: A new array is created and the elements of the first array is
copied.
Step 5: The second array is reversed.
11
Step 6: The second array is displayed.
Step 7: The product of the two arrays is calculated by:
(a[i]*b[i])
VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
lim Integer Stores the limit of
the array
i Integer Loop control
variable
sum Integer Stores the sum of
the dot product of
the arrays
a[] Integer Array to store the
numbers
b[] Integer Array to store the
copy of the numbers

QUESTION NUMBER #4:


Write a program to transpose a matrix without using a second
array.

12
Transpose of a ‘m’ by ‘n’ matrix is defined to be ‘n’ by ‘m’
matrix that results from interchanging the rows and columns
of the matrix.

Example: A= a11 a12 a13 AT or A` = a11 a21


a21 a22 a23 a12 a22
a31 a32

import java.util.Scanner; /*importing the package for scanner


class*/

class Trans/*starting class*/


{
public static void main(String args[])/*Starting of main()*/
{
int m, n, r, c; /*Initialization and declaration of variables*/
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of
matrix:");
m = in.nextInt();/*enterting the number of rows and
columns*/
n = in.nextInt();
int matrix[][] = new int[m][n];
System.out.println("Enter the elements in the matrix:");
for(r=0;r<m;r++)/*entering the elements in the 2-D array*/
{
for ( c = 0 ; c < n ; c++ )
{
matrix[r][c] = in.nextInt();
}
}
int transpose[][] = new int[n][m];
for ( r = 0 ; r < m ; r++ )
{
for ( c = 0 ; c < n ; c++ )
13
{
transpose[c][r] = matrix[r][c]; /*transposing the matrix*/
}
}
System.out.println("The original matrix:-");
for(r=0;r<m;r++)
{
for(c=0;c<n;c++)
{
System.out.print(matrix[r][c]+"\t"); /*printing the
original matrix*/
}
System.out.println("\n");
}

System.out.println("Transpose of entered matrix:-"); /*printing the


transposed matrix*/
for ( r = 0 ;r < n ; r++ )
{
for ( c = 0 ; c < m ; c++ )
{
System.out.print(transpose[r][c]+"\t");
}
System.out.print("\n");
}
}/*end of main()*/
}/*end of class*/

OUTPUT:

14
Enter the number of rows and columns of matrix:
3
3
Enter the elements in the matrix:
1
2
4
5
7
8
9
6
3
The original matrix:-
1 2 4

5 7 8

9 6 3

Transpose of entered matrix:-


1 5 9
2 7 6
4 8 3

ALGORITHM:
Step 1: Start

15
Step 2: The number of rows and columns are entered by the user
and stored in different variables.
Step 3: A for loop is started which enters the elements in a 2-D
array
Step 4: The matrix is transposed i.e. the elements in the rows are
interchanged with that of the
Columns’.
Step 5: The transposed matrix is displayed.
Step 6: End.

VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
m Integer Stores the number of
rows entered by the
user
n Integer Stores the number of
columns entered by
the user
r Integer Loop control
variable for the rows
c Integer Loop control
variable for the
columns
matrix[] Integer A 2-D array to store
the original matrix.
transpose[] Integer A 2-D array to store
the transposed
matrix.

QUESTION NUMBER# 5:

16
ROT 13 is a very simple encryption scheme used in a software
news group to conceal potentially offensive postings. It works
by cyclically shifting each character(lowercase or uppercase)
by 13. So, the letter ‘a’ is replaced by ‘n’ and the letter ‘n’ is
replaced by ‘a’.
For example: ‘encryption’ is encoded as ‘rapeldgvba’.

import java.util.*; /*importing the package for scannar class*/

class Rot13 /*starting class*/


{
String word; /*initialization and declaration of variables*/
String nw;
int length;
Scanner sc = new Scanner(System.in);
Rot13() /*a default constructor*/
{
word = "";
nw = "";
length = 0;
}
void accept_word() /*accepting the word from the user*/
{
System.out.println("Enter your word");
word = sc.next();
length = word.length(); /*finding out the length of the
word*/
}
void encrypt() */to find out the encrypeted text*/
{
char ch;
char chr;
int c=0;
for(int i=0;i<length;i++)
{
17
ch = word.charAt(i);
if((ch>='a' && ch<='m')||(ch>='A' && ch<='M'))
{
c = (int)(ch+13);*/shifting the characters by 13
positions*/
}
if((ch>='n' && ch<='z')||(ch>='N' && ch<='Z'))
{
c = (int)(ch-13);
}
chr = (char)c;
nw = nw + chr;
}
}

void display() /*to print the encrypted text*/


{
System.out.println("The original word : "+word);
System.out.println("The encrypted word : "+nw);
}
public static void main(String args[])/*starting of main()*/
{
Rot13 ob = new Rot13();
ob.accept_word();
ob.encrypt();
ob.display();
}/*end of main()*/

}/*end of class*/

OUTPUT:

18
Enter your word
angelus
The original word : angelus
The encrypted word : natryhf

ALGORITHM:
Step 1: Start
Step 2: The class was created and the data members were
initialized.
Step 3: The word was accepted from the user and was stored in a
variable.
Step 4: The length of the word was found out.
Step 5: A for loop was started to extract each character.
Step 6: The character was converted into its ASCII code and the
was shifted by 13 positions.
Step 7: The original and the encrypted text was printed.
Step 8: End.
VARIABLE DESCRIPTION CHART
VARIABLE NAME VARIABLE TYPE VARIABLE
DESCRIPTION
word String To store the word
entered by the user
nw String To store the encrypted
text
length Integer To store the length of
the entered word
c Integer To store the new
character shifted by 13
places
ch Char To store the extracted
character form the
word
chr char To store the new
encrypted character.
i Integer Loop control variable.
QUESTION NUMBER #6:
19
Design a class Alpha which enables a word to be arranged in
ascending order according to its alphabets using any standard
sorting technique.
Example: “Trial” is sorted as “ailrT”

import java.util.*; /*importing the package for scannar class*/


class Alpha /* Starting of class*/
{
String word;/*initialization and declaration of variables*/
String nw;
int length;
Scanner sc = new Scanner(System.in);
Alpha() /*a default constructor*/
{
word = "";
nw = "";
length = 0;
}
void input()
{
System.out.println("Enter your word");
word = sc.next();/*accepting the word from the user*/
length = word.length();
}
void sort()
{
char arr[] = new char[length];
for(int i=0;i<length;i++)
{
arr[i] = word.charAt(i);/*extracting the characters and
storing it in another array*/
}
char temp;
int asci,ascii;
20
for(int k=0;k<(length-1);k++)
{
for(int l=(k+1);l<length;l++)/*sorting the array
alphabetically*/
{
asci = (int)arr[l];
ascii= (int)arr[l+1];
if(arr[l]>arr[l+1])
{
temp = arr[l];
arr[l] = arr[l+1];
arr[l+1] = temp;
}
asci=0;ascii=0;
}
}
for(int i=0;i<length;i++)
{
nw = nw + arr[i];/*forming the word to be printed*/
}
}
void display()
{
System.out.println("Original Word : "+word);
System.out.println("Sorted Word : "+nw);
}
public static void main(String args[])/*starting of main*/
{
Alpha ob = new Alpha();
ob.input();
ob.sort();
ob.display();
}/*end of main()*/
}/*end of class*/
OUTPUT:
21
Enter your word
Trial
Original Word : Trial
Sorted Word : ailrT

ALGORITHM:
Step 1: Start
Step 2: The class was created and the data members were
initialized.
Step 3: The word was accepted from the user.
Step 4: Each alphabet is extracted and stored in an array.
Step 5: The characters in the array are sorted alphabetically using
Selection sort
technique.
Step 6: The newly arranged word is printed.
Step 7: End.
VARIABLE DESCRIPTION CHART

VARIABLE NAME VARIABLE TYPE VARIABLE


DESCRIPTION
word String To store the word
entered by the user
nw String To store the new word
arr[] Char A character type array
to store the extracted
letters
temp Integer A temporary variable
for swapping
asci Integer To store the ACSII
value of the character
ascii Integer To store the ACSII
value to the following
character
i Integer Loop control variable
j Integer Loop control variable
l Integer Loop control variable
QUESTION NUMBER #7:
22
Implementation of stack (a data structure) which includes the
operations like push, pop and display.

import java.util.*; /*starting of class*/


class stack
{
Scanner sc=new Scanner(System.in);
int s[]=new int[20];
int sp,n;
stack(int nm) /*a parameterized constructor*/
{
int i;
for(i=0;i<20;i++)
s[i]=0;
sp=-1;
n=nm;
}
void pushdata(int item)
{
if(sp==(n-1))
System.out.println("stack overflows");/*checks if the stack
is overflowing or
not*/
else
{
sp++;
s[sp]=item; /*element is pushed in the stack*/
}
}
void popdata()
{
int v;
if(sp==-1)

23
System.out.println("stack underflows"); /*checking if the
underflows*/
else
{
v=s[sp];
System.out.println("popped out element is"+v); /*the element is
popped out*/
sp--;
}
}
void display()
{ if(sp==-1)
System.out.println("stack empty");
else
{
System.out.println("SP---->|"+s[sp]+"|"); /*printing the stack*/
System.out.println(" ----");
for(int i=sp-1;i>=0;i--)
{
System.out.println(" |"+s[i]+"|");
System.out.println(" -----------");
}
}
}
public static void main(String []args) /*starting of main()*/
{
stack ob= new stack(5);
ob.pushdata(9);
ob.pushdata(99);
ob.pushdata(88);
ob.display();
ob.popdata();
ob.display();
} /*end of main()*/
} /*end of class*/
24
OUTPUT:

SP---->|88|
----
|99|
-----------
|9|
-----------
popped out element is88
SP---->|99|
----
|9|
-----------

ALGORITHM:
Step 1: Start
Step 2: Class was created and data members were initialized
Step 3: Checks if the stack overflows
Step 4: Increases the stack pointer
Step 5: Pushes the element
Step 6: Check if stack underflows
Step 7: Pops out the element
Step 8: Decrements the stack pointer
Step 9: End

VARIABLE DESCRIPTION CHART

VARIABLR VARIABLE TYPE VARIABLE


NAME DESCRIPTION
s[] Integer An array to store the
elements
sp Integer The pointer to
increment and
decrement the
25
positions
n Integer The limit of the
array
nm Integer A copy of the limit
is stored in this
variable
item Integer The element to be
pushed in.
v Integer The popped out
element
i Integer Loop control
variable

26
QUESTION NUMBER #8: Implementation of Dequeue

public class dequeue


{
private int theSize; /*entering the size of the array*/
private int front; /*index of the first element*/
private int rear; /*index of the rear element*/.
private int [] items; /*array for the queue*/
public dequeue() /*default constructor*/
{
items = new int[5];
front = 0;
rear = -1;
theSize = 0;
}

public void insertRight(int x) /*Insert an item from the rear of


the queue*/
{
if(theSize == items.length)
{
grow();
}
rear = increment(rear);
items[ rear ] = x;
theSize++;
}
public void insertLeft(int x) /*Insert an item from the front
of the queue.*/

{
if(theSize == items.length)

27
{
grow();
}
rear = increment(rear);
theSize++;
int[] temp = new int[theSize];
for(int i = 0; i < theSize - 1; i++)
{
temp[i + 1] = items[i];
for(int j = i + 1; j < theSize; j++)
{
temp[j] = items[j - 1];
}
items = temp;
break;
}
items[0]=x;
}

public int removeLeft() /*Take item from front of queue*/


{
int temp = items[front++]; /* get value and increment
front*/
if(front == items.length)
front = 0;
theSize --; // one less item
return temp;
}
public int removeRight() /*Take item from rear of queue*/
{
int temp = items[rear--]; /*get value and decrement
rear*/
if(rear == -1)
rear = theSize -1;
theSize --;

28
return temp;
}
public void display() /*Display the elements in the
queue.*/
{
int j = front;
for (int count = 0; count < theSize; count++)
{
System.out.print(items[j] + " ");
j = increment(j);
}
System.out.println();
}
private int increment(int i) /*Internal method to increment.*/
{
if (i == items.length - 1)
return 0;
return ++i;
}
public int first() /*The first item in the front of the queue.*/
{
if(isEmpty())
{
System.err.println("Dequeue empty");
}
return items[front];
}

public int last() //The last item inserted from rear of queue.
{
if(isEmpty())
{
System.err.println("Dequeue empty");
}
return items[rear];

29
}
public int size() /*Number of items in queue*/.
{
return theSize;
}
public boolean isEmpty() /*True if queue is empty.*/
{
return (theSize ==0);
}
public static void main(String []args) /*starting of main()*/
{
dequeue ob= new dequeue();
ob.insertRight(6);
ob.insertRight(9);
ob.insertRight(7);
ob.insertRight(1);
ob.insertLeft(2);
ob.insertLeft(4);
ob.removeLeft();
ob.removeRight();
ob.display();
ob.increment(1);
ob.first();
ob.last();
ob.isEmpty();
}/*end of main()*/
} /*end of class*/

30
OUTPUT:
2 6 9 7

ALGORTHIM:
Step 1: Start
Step 2: Class name and data members are initialized
Step 3: Set the pointer if underflow
Step 4: Insert the element in the queue at front end
Step 5: Insert the element in the queue at rear end
Step 6: Check for underflow
Step 7: Delete element at the front end
Step 8: Delete element at the rear end
Step 9: End

VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
theSize Integer To store the size of
the array
front Integer To store the front
end pointer
rear Integer To store the rear end
pointer
items[] Integer To store the items
i Integer Loop control
variable
j Integer To store a copy of
the front end

31
QUESTION NUMBER #9: Implementation of singly linked list
function (add, delete, traverse and search)

import java.util.*; /*importing the package for scannar class*/


public class my_list /*starting class*/
{
class node
{
public int data;
public node next;
}
node head;

public my_list()
{
head = null;
}

void sort_list() /*sorting the linked list*/


{
node p,q;
node t;

for(p=head;p.next!=null;p=p.next)
{
for(q=p.next;q!=null;q=q.next)
{
if(p.data > q.data)
{
int temp;
temp = p.data;
p.data = q.data;
q.data = temp;

}
32
}
}
}

void copy()
{

void traverse() /*traversing the list*/


{
node p1;
p1=head;
System.out.println("The list is ::");
while (p1 != null)
{
System.out.println(p1.data);
p1 = p1.next;
}
}

void add()
{
node p = new node();
System.out.println("Enter the no to add::");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
p.data = n;
if(head == null)
p.next = null;
else
p.next = head;
head = p;
}

33
void add_end()
{
node p = new node();
node q;
System.out.println("Enter the no to add at the end::");
Scanner s3 = new Scanner(System.in);
int no1 = s3.nextInt();
p.data = no1;
p.next = null;
if (head == null)
head = p;
else
{
q = head;
while(q.next != null)
q = q.next;

q.next = p;
}
}

node search(node head,int x)


{
while((head != null) && (head.data != x))
head = head.next;
return head;
}

void after_element()
{
System.out.println("Enter the no after which you want to
insert::");

34
Scanner s = new Scanner(System.in);
int num = s.nextInt();
node loc = new node();
loc = search(head,num);
if(loc == null)
return;
node p = new node();
p.data = num;
p.next = loc.next;
loc.next = p;
}

void delete_beg()
{
node p,q;
p = head;

if(head == null)
{
System.out.println("The list is empty.");
return;
}

else
{
q = head;
head = head.next;
return;
}
}

void delete_end()
{
node p,q;

35
if(head == null)
{
//System.out.println("The list is empty.");
return;
}

else if (head.next == null)


{
p = head;
head = null;
return;
}

else
{
q = head;
p = q.next;
while(p.next != null)
{
q = p;
p = p.next;
}
q.next = null;
return;
}
}

void reverse_list()
{
node currentnode,previousnode,nextnode;

currentnode = head;
nextnode = currentnode.next;
previousnode = null;
36
currentnode.next = null;

while(nextnode != null)
{
previousnode = currentnode;
currentnode = nextnode;
nextnode = currentnode.next;
currentnode.next = previousnode;

head = currentnode;

void insert_pos()
{
int i;
System.out.println("Enter the position where you want to
insert a new node::");
Scanner pos = new Scanner(System.in);
int pos1 = pos.nextInt();

node p = new node();


node t,q;
System.out.println("Enter the no::");
Scanner no = new Scanner(System.in);
int num1 = no.nextInt();
p.data = num1;

if (pos1 == 1)
{
p = head;

37
head = head.next;
}

else
{
for(q = head,i=1;i< pos1;i++)
{
q = q.next;
p.next = q.next;
q.next = p;
}
}

void delete_pos()
{
System.out.println("Enter the position no which you want to
delete::");
Scanner scan1 = new Scanner(System.in);
int po = scan1.nextInt();
int i;

node p;

if(po ==1)
{
p = head;
head = head.next;
return;
}

else
{
node q;
38
for(q = head,i=1;i<po;i++)
{
q=q.next;
p = q.next;
head.next = p.next;
}
return;
}
}

void max_no()
{
node p;
int temp = 0;

for(p=head;p!=null;p=p.next)
{
if(p.data >temp)
temp = p.data;
}

System.out.println("Maximum no is::" + temp);

public static void main(String []args)


{

my_list l = new my_list();


int ch;

do
{
System.out.println("MENU");
System.out.println("-----");

39
System.out.println("1.Add.");
System.out.println("2.Display the list.");
System.out.println("3.Add at the end.");
System.out.println("4.Add after an element.");
System.out.println("5.Delete from beginning.");
System.out.println("6.Delete from end.");
System.out.println("7.Reverse List.");
System.out.println("8.Insert at a position.");
System.out.println("9.Sort list.");
System.out.println("10.Delete at a position.");
System.out.println("11.Maximum element in the list.");
System.out.println("12.Exit.");

Scanner s1 = new Scanner(System.in);


ch = s1.nextInt();

switch(ch)
{
case 1:l.add();
break;

case 2:l.traverse();
break;

case 3:l.add_end();
break;

case 4:l.after_element();
break;

case 5:l.delete_beg();
break;

case 6:l.delete_end();
break;
40
case 7:l.reverse_list();
break;

case 8:l.insert_pos();
break;

case 9: l.sort_list();
break;

case 10:l.delete_pos();
break;

case 11:l.max_no();
break;

}
}while(ch!=12);

}/*end of main()*/
} /*end of class*/

41
OUTPUT:
1.Add
2.Display the list.
3.Add at the end.
4.Add after an element.
5.Delete from beginning.
6.Delete from end.
7.Reverse List.
8.Insert at a position.
9.Sort list.
10.Delete at a position.
11.Maximum element in the list.
12.Exit.
1
Enter the no to add::
8
MENU
-----
1.Add.
2.Display the list.
3.Add at the end.
4.Add after an element.
5.Delete from beginning.
6.Delete from end.
7.Reverse List.
8.Insert at a position.
9.Sort list.
10.Delete at a position.
11.Maximum element in the list.
12.Exit.
2
The list is ::
8
44
4
42
MENU
-----
1.Add.
2.Display the list.
3.Add at the end.
4.Add after an element.
5.Delete from beginning.
6.Delete from end.
7.Reverse List.
8.Insert at a position.
9.Sort list.
10.Delete at a position.
11.Maximum element in the list.
12.Exit.
11
Maximum no is::44

ALGORITHM:
Step 1: Start
Step 2: Create the first list of the structure
Step 3: Initialize the temporary objects
Step 4: Input number of nodes to be created
Step 5: Create the other nodes of the linked list structure and
connect them
Step 6: Connect the temporary list in existing linked list
Step 7: Withdraw temporary pointer Ptr
Step 8: Return
Step 9: Add the list in the beginning
Step 10: Locate the last list of the linked list structure
Step 11: Insert the list
Step 12: Locate Nth node to be deleted
Step 13: Delete the list
Step 14: End

43
VARIABLE DESCRIPTION CHART

VARIABLE NAME VARIABLE TYPE


data Integer
next node
head node

44
QUESTION NUMBER #10: Implementation of a Doubly
Linked List

import java.util.*; /*importing the package for scannar class*/


class doubly /*starting class*/
{

class node
{
node prev;
int data;
node next;
}

node head;
node tail;

doubly() /*default constructor*/


{
head=null;
//tail=null;
}

void insert()
{
node p = new node();
System.out.println("enter the data::");
Scanner s = new Scanner(System.in);
int no = s.nextInt();
p.data=no;
p.next=null;
p.prev=null;

if(head == null)
head = p;
45
else
{
node q;
q=head;
while(q.next!=null)
q=q.next;
q.next=p;
p.prev=q;

}
}
void display()
{
node p;
p=head;
while(p!=null)
{
System.out.println(p.data);
p=p.next;
}
}

void reverse()
{
node currentnode,previousnode,nextnode;

currentnode = head;
nextnode = currentnode.next;
previousnode = null;

currentnode.next = null;

while(nextnode != null)
{
46
previousnode = currentnode;
currentnode = nextnode;
nextnode = currentnode.next;
currentnode.next = previousnode;

head = currentnode;

void delete()
{
node p;
if(head == null)
return;
p=head;
if(head == tail)
head=tail=null;
else
{
p.next.prev=null;
head=p.next;
}
}

void max() /*finding out the maximum element*/


{
node p;
int temp = 0;

for(p=head;p!=null;p=p.next)
{
if(p.data >temp)
temp = p.data;
47
}

System.out.println("Maximum no is::" + temp);


}

public static void main(String []args) /*starting of main()*/


{
doubly d = new doubly();
d.insert();
d.insert();
d.insert();
d.insert();
d.display();
d.reverse();
d.display();
d.max();

} /*end of main()*/

} /*end of class*/

48
OUTPUT:
enter the data::
5
enter the data::
2
enter the data::
1
enter the data::
0
5
2
1
0
0
1
2
5
Maximum no is::5

ALGORITHM:
Step 1: Start
Step 2: Create the first list of the structure
Step 3: Initialize the temporary object
Step 4: Input the number of nodes to be created
Step 6: Connect the temporary list with the original list
Step 7: Withdraw temporary pointer Ptr
Step 8: Locate Nth node to be deleted
Step 9: Delete the list
Step 10: Withdraw the temporary pointers
Step 11: Traverse the Linked list
Step 12: End

49
VARIABLE DESCRIPTION CHART:

VARIABLE NAME VARIABLE TYPE


prev Node
data Integer
next Node
head Node
tail Node

50
QUESTION NUMBER #11: Tower of Hanoi using three disks

import java.util.Scanner;
public class TowersOfHanoi /*starting of class*/
{
public static void solveTowers(int d, int start, int end, int temp)
{
if (d == 1)
{
System.out.println(start + "--> " + end);
return;
}
solveTowers(d - 1, start, temp, end); /*function calling itself
Recursive Technique*/
System.out.println(start + "--> " + end);
solveTowers(d - 1, temp, end, start);
}
public static void main(String[] args) /*Starting of main()*/
{
Scanner s = new Scanner(System.in);
System.out.println("Enter number of disks");
solveTowers(s.nextInt(), 1, 3, 2);
}/*end of main()*/
} /*end of class*/

51
OUTPUT
Enter number of disks
3
1--> 3
1--> 2
3--> 2
1--> 3
2--> 1
2--> 3
1--> 3

ALGORITHM:
Step 1: Start
Step 2: The class was created and the variables were initialized and
declared
Step 3: The tower of Hanoi was formed by recursive technique (a
function which calls
itself).
Step 4: The tower of Hanoi was printed.
Step 4: End.

VARIABLE DESCRIPTION CHART:

VARIABLE TYPE VARIABLE TYPE VARIABLE


DESCRIPTION
d Integer Counter variable
start Integer To store the
starting level
end Integer To store the
ending level
temp Integer A temporary
variable

52
QUESTION NUMBER #12:

Write a program to enter two arrays are perform merge sort


and display the final array. The elements of the array will be
entered by the user.

import java.util.*; /*importing the package for scannar class*/


class MergeSort /*starting class*/
{
public static void main(String []args) /*starting main()*/
{
int i,j; /initialization and declaration of variables*/
Scanner s = new Scanner(System.in);
System.out.println("Enter the no of elements for the first array ::");
int n = s.nextInt();
System.out.println("Enter the no of elements for the second
array ::");
int m = s.nextInt();

System.out.println("Enter the elements in the first array ::");

int a[]=new int[n];

for(i=0;i<n;i++) /*entering the elements of the first array*/


{
int x =s.nextInt();
a[i]=x;
}
System.out.println("Enter the elements in the second array ::");
int b[]=new int[m];

for(i=0;i<m;i++)
{
int y=s.nextInt();/*entering the elements of the second
array*/
53
b[i]=y;
}

for(i=0;i<n;i++) /*sorting the first array*/


{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

System.out.println("The first sorted array is ::");

for(i=0;i<n;i++)
{
System.out.println(" "+a[i]);
}

for(i=0;i<m;i++)
{
for(j=0;j<m;j++) /*starting the second array*/
{
if(b[i]<b[j])
{
int temp;
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
54
}
}

System.out.println("The second sorted array is ::");

for(i=0;i<m;i++)
{
System.out.println(" "+b[i]);
}

int p,q,r;
p=q=r=0;

int c[]=new int[100];

while(p<n && q<m) /*using the Merge Sort technique to


display the final array*/
c[r++]=a[p]<b[q]?a[p++]:b[q++];
while(p<n)
c[r++]=a[p++];
while(q<m)
c[r++]=b[q++];

int z = a.length+b.length;

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

for(i=0;i<z;i++)
{
System.out.println(" "+c[i]);

}
}

}
55
OUTPUT:

Enter the no of elements for the first array ::


4
Enter the no of elements for the second array ::
3
Enter the elements in the first array ::
1
2
3
4
Enter the elements in the second array ::
5
6
7
The first sorted array is ::
1
2
3
4
The second sorted array is ::
5
6
7
The final sorted arrays are ::
1
2
3
4
5
6
7

56
ALGORITHM:
Step 1: Start
Step 2: Class name and data members are initialized
Step 3: Compare the elements of the array
Step 4: Store the remaining elements in C
Step 5: Return
Step 6: End

VARIABLE DISCRIPTION CHART:

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
n Integer To store the number
of elements of 1st
array
m Integer To store the number
of elements of 2nd
array
a[ ] Integer To store the
elements of the first
array
b[ ] Integer To store the
elements of the
second array
c[ ] Integer To store the final
sorted array

57
QUESTION NUMBER #13:
Write a program to enter 10 numbers and search a number
entered by the user by Binary Search technique. Display
suitable messages.

import java.util.*; /*importing the package for scannar class*/


public class binarysearch /*starting class*/
{
Scanner sc = new Scanner(System.in);
int num[] = new int[10];
int t;
int n;
binarysearch() /*default constructor*/
{
for(int i = 0;i<10;i++)
num[i]=0;
t=0;
n=0;
}
void input()
{
System.out.println("Enter 10 numbers");/*entering the numbers */
for(int i=0;i<10;i++)
{
num[i] = sc.nextInt();
}
System.out.println("Enter the number to be searched");
n=sc.nextInt();
}
void sort() /*sortint the array using bubble sort technique*/
{
for(int i=0;i<9;i++){
for(int j=0;j<(9-i);j++){
if(num[j]<num[j+1]){
t=num[j];
58
num[j]=num[j+1];
num[j+1]=t;
}
}
}
}
void search() /*searching for the number entered by the user*/
{
int k=0;lb=0;ub=9;p=0;
while(lb<=ub)
{
p=(lb+ub)/2;
if(num[p]<n)
lb=p+1;
if(num[p]>n)
ub=p-1;
if(num[p]==n)
{
k=1;
break;
}
}
if(k==1)
System.out.println("Search succesful");
else
System.out.println("Number is not present");
}
public static void main(String args[])
{
binarysearch ob = new binarysearch();
ob.input();
ob.sort();
ob.search();
}
}
59
OUTPUT:
Enter 10 numbers
0
1
2
3
4
5
6
7
8
9
Enter the number to be searched
0
Search successful

Enter 10 numbers
0
1
2
3
4
5
6
7
8
9
Enter the number to be searched
12
Number is not present

ALGORITHM:
Step 1: Start

60
Step 2: Class was created and the data members were declared and
initialized
Step 3: 10 numbers are taken as an input from the user
Step 4: The numbers are sorted using Bubble sort technique
Step 5: The lower boundary is set at the 0th position and the upper
boundary is set at 9th position
Step 6: If the number is present in the first half, (lb) increases by
one
Step 7: If the number is present in the lower half, (ub) decreases by
one
Step 8: The number is found when the number to be searched is
equal to the number at ((UB+LB)/2)th positon
Step 9: End

VARIABLE DESCRIPTION CHART:

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
num[ ] Integer To store 10 numbers
inputed by the user
n Integer To store the number
to be searched
t Integer Swapping variable
ub Integer To store the Upper
boundary, i.e. 9
lb Integer To store the Lower
boundary, i.e. 0
p Integer To store the mid
value (ub+lb)/2
k Integer Flag variable

61
QUESTION NUMBER #14:

Design a class change to convert a decimal number to its


hexadecimal equivalent in base 16 and to convert
it back to its original form.Some of the members
of the class change are as follows:
Class name: change
Data members/Instance variables:
a[ ] - an integer array
n - Integer to be converted to base 16
Member functions/method:
change( ) – constructor to initialize 0 to the data members
void input( ) – to accept an integer to be converted to base 16
void hexadeci(String atr) – to convert hexadecimal back to
decimal
void decihexa( ) – to convert decimal integer to hexadecimal
form

import java.util.*; /*importing the package for scannar class*/


class change /*starting of class*/
{
Scanner sc=new Scanner(System.in);
int a[]=new int[50];
int n,i;
void change(){
for(i=0;i<50;i++){
a[i]=0;
}
n=0;
}
void input() /*entering the number*/
{
System.out.println("Enter the decimal number");
n=sc.nextInt();
}
62
void decihexa(String str) /*conversion of the hexadecimal
number into decimal form*/
{
int a=0,len,p=0,k=0;
double d=0,s=0;
String str1="";
char ch;
len=str.length();
p=len;
for(i=0;i<len;i++)
{
ch=str.charAt(i);
if(ch>='A')
{
k=(int)ch-55;
}

else
{
str1=str1+ch;
k=sc.nextInt();
str1="";
}
d=Math.pow(16,(p-1))*k;
s=s+d;
p--;
}
System.out.println("The decimal equialent of HexaDecimal
Number "+str);
System.out.println((int)s);
}
void hexadeci() /*converting the decimal number to its
hexadecimal form*/
{

63
int i=0,c=0,r,t;
String str2="";
System.out.println("The HexaDecimal equivalent of Decimal
Number:"+n);
while(n>0)
{
r=n%16;
a[i]=r;
n=n/16;
i++;
c++;
}
for(i=c-1;i>=0;i--)
{
if(a[i]>=10)
{
t=a[i]-10;
t=65+t;
str2=str2+(char)t;
}
else
str2 = str2+(char)(48+a[i]);
}
System.out.println(str2);
decihexa(str2);
}
public static void main(String args[]) /*starting main()*/
{
change ob = new change();
ob.input();
ob.hexadeci();
}/*ending main()*/
}/*ending class*/

64
OUTPUT:
Enter the decimal number
15
The HexaDecimal equivalent of Decimal Number:15
F
The decimal equialent of HexaDecimal Number F
15
ALGORITHM:
Step 1: Start
Step 2: The class was created and the data members were
initialized
Step 3: The number is taken from the user
Step 4: Each digit of the number is stored in an array
Step 5: The digits of the number are converted to its hexadecimal
form and printed
Step 6: The hexadecimal number is again converted back to
decimal form and displayed
Step 7: End
VARIABLE DESCRIPTION CHART:

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
a[ ] Integer Array to store each
digits of the number
n Integer To store the number
entered by the user
i Integer Loop control
variable
str String To store the decimal
number converted
from its hexadecimal
equivalent
str2 String To store the
hexadecimal number
converted from its
65
decimal equivalent

66
QUESTION NUMBER #15:
write a program using String tokenizer to find the total
number of tokens and the sum of the tokens.
import java.util.StringTokenizer;
import java.util.Scanner;
class tokens /*starting class*/
{
public static void main(String[] args) /*starting main()*/
{
Scanner input=new Scanner(System.in);
String sentence=input.nextLine();
String temp;
int k,total=0;
StringTokenizer s1=new StringTokenizer(sentence);
System.out.println("Total Number of
tokens:"+s1.countTokens()); /*to count and print the total
number of tokens*/

while(s1.hasMoreTokens())
{
temp=s1.nextToken();
k=Integer.parseInt(temp);
total+=k; /*to find the sum the
tokens*/
System.out.print(k+"\t");
}
System.out.println("Sum of tokens :"+total);
}/*end of main()*/
}/*end of class*/

67
OUTPUT:

578
Total Number of tokens:3
5 7 8
Sum of tokens :20

ALGORITHM:
Step 1: Start
Step 2: Class name and data members are initialized
Step 3: Input is taken from the user
Step 4: The number of tokens is calculated by using the string
tokenizer function
Step 5: The sum of tokens is calculated
Step 6: All the values are displayed
Step 7: End

VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE VARIABLE


NAME TYPE DESCRIPTION
sentence String To store the input
from the user
temp Integer For calculating the
number of tokens
k Integer To store the tokens
total Integer For calculating the
sum of all the
tokens

68
QUESTION NUMBER #16:

To print the name, roll number, and total marks of a student


using INHERITANCE.

import java.util.*; /*importing the package for scannar class*/


class std /*starting of class*/
{
String std; int roll;
void accept() /*accepting the name and roll number of the
student*/
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the name and roll number of the
students::");
std = sc.next();
roll = sc.nextInt();
}
void show()
{
System.out.println("The name of the student is::"+std);
System.out.println("The roll no is::"+roll);
}
}
class marks extends std /*the inherited class*/
{
protected float sub1,sub2;
void get(float x, float y)
{
sub1 = x;
sub2 = y;
}
void display()
{

69
System.out.println("The marks of subject 1 and subject 2
are::"+sub1+"and"+sub2);
}
}
class result extends marks /*inherited class*/
{
float tot;
void disp()
{
tot = sub1 + sub2;
show();
display();
System.out.println("The total of the marks is::"+tot);
}
public static void main(String []args) /*starting of main()*/
{
result obj = new result();
obj.accept();
obj.get(90, 78);
obj.disp();
} /*end of main()*/
}/*end of class*/
OUTPUT:
Enter the name and roll number of the students::
angelus 12
The name of the student is::angelus
The roll no is::12
The marks of subject 1 and subject 2 are::90.0and78.0
The total of the marks is::168.0

ALGORITHM:
Step 1: Start
Step 2: Class was created and data members were initialized
Step 3: The Name and the roll number were accepted from the
user
70
Step 4: The marks and the total marks is displayed
Step 5: End

VARIABLE DISTRIBUTION CHART:

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
std String To store the name of
the user
roll Integer To store the roll
number of the user
sub1 Protected Integer To store the marks of
the first subject
sub2 Protected Integer To store the marks of
the second subject
tot Integer To display the total
of the two subjects

71
QUESTION NUMBER #17:
Write a program to find the volume of a cube, sphere, cuboid
using function overloading technique.

import java.util.*; importing the package for scannar class*/


class overload /*starting class*/
{
double vc=0,vs=0,vcd=0; /*initialization and declaration of
variables*/
public void volume(int s) /*finding the volume of a cube*/
{
vc=s*s*s;
System.out.println("The volume of cube : "+vc);
}
public void volume(float r) /*finding the volume of a sphere*/
{
vs=4/3*22/7*r*r*r;
System.out.println("The volume of sphere : "+vs);
}
public void volume(int l,int b,int h) /*finding the volume of a
cuboid*/
{
vcd=l*b*h;
System.out.println("The volume of cuboid : "+vcd);
}
public static void main(String args[]) /*starting of main()*/
{
Scanner sc = new Scanner(System.in);
int s,l,b,h;
float r;
System.out.println("Enter the side of a cube");
s = sc.nextInt();
System.out.println("Enter the radius of the circle");
r = sc.nextFloat();

72
System.out.println("Enter the length, breadth and height of
the cuboid");
l = sc.nextInt();
b = sc.nextInt();
h = sc.nextInt();
overload ob = new overload();
ob.volume(s);
ob.volume(r);
ob.volume(l,b,h);
}/*end of main()*/
}/*end of class*/

73
OUTPUT:
Enter the side of a cube
3
Enter the radius of the circle
4
Enter the length, breadth and height of the cuboid
257
The volume of cube : 27.0
The volume of sphere : 192.0
The volume of cuboid : 70.0

ALGORITHM:

Step 1: Start
Step 2: Class was created and the data members were
initialized
Step 3: The side of the cube is accepted and the volume is
calculated and displayed
Step 4: The radius of the sphere is accepted and the volume is
calculated and displayed
Step 5: The length, breadth and the height of the cuboid is
accepted and the volume is calculated and displayed
Step 6: End

VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
vc Double To store the volume
of cube
vs Double To store the volume
of sphere
vcd Double To store the volume
of cuboid
s Integer To store the side of
74
cube
r Float To store the radius
of sphere
l Integer To store the length
of cuboid
b Integer To store the breadth
of cuboid
h Integer To store the height
of cuboid

75
QUSTION NUMBER #18:
Write a program to help a user create his/her account and find
his/her balance or to deposit a certain amount and display it.

import java.io.*; /*importing the i/o package*/


import java.lang.*;
class BankAccount5 /* starting of class
{
public static void main(String[]args)throws IOException /*starting
of main()*/
{
char [] newType = new char [20]; /*initialization and declaration
of the variables*/
double [] newTransaction = new double [20];
double [] newBalance = new double [20];
int o = 0;
int s = 0;
int t = 0;

BufferedReader console = new BufferedReader (new


InputStreamReader(System.in));
System.out.println(" Enter Your Name");
String name = console.readLine();

System.out.println("Hello " + name);


System.out.println(name +" " + "enter your account number");
String account = console.readLine();

System.out.println(" enter your original balance");


String Bal = console.readLine();
double initialBalance = Double.parseDouble(Bal);
double balance = initialBalance;

76
System.out.println("Enter c for Check; d for Deposit; or p to Print
Summary");
char continueAnswer = console.readLine().charAt(0);
boolean answer = true;
newType [o] = continueAnswer;

if (continueAnswer == 'p')answer = false;

double Fee;
double OverdraftTotal = 0;
double checks = 0;
double deposit = 0;
double TotalBalance = initialBalance;

while (answer == true)


{
System.out.println("Enter amount");
String input = console.readLine();
double transaction = Double.parseDouble(input);
newTransaction [o] = transaction;

if (continueAnswer == 'c')
checks = checks + transaction;

{
checks = checks + 0;
if (transaction > balance)
{
if (transaction > 250)
Fee = transaction * .10;
else
Fee = 25.00;
balance = (balance) - Fee;
newBalance [t] = TotalBalance;
77
OverdraftTotal = OverdraftTotal + Fee;
o = o + 0;
t = t + 0;
newType [o] = 'f';
newTransaction [o] = Fee;

}
else
balance = balance - transaction;
newBalance [t] = balance;

if (continueAnswer == 'd')
deposit = deposit + transaction;
balance = deposit + transaction;
newBalance [t] = balance;
o = o + 1;
t = t + 1;

System.out.println("Enter c for Check; d for Deposit; or p to Print


Summary");
continueAnswer = console.readLine().charAt(0);
newType [o] = continueAnswer;
if (continueAnswer == 'p')answer = false;

}
if (balance <= 0)
System.out.println("Your account insufficient, You should enter $"
+ balance + " to bring account current");

78
System.out.println("Name " + name + ", Account Number " +
account);
System.out.println(" Account Statement");
System.out.println("Your balance " + balance);
System.out.println("Amount of checks: " + checks);
System.out.println("Overdraft total fees: $" + OverdraftTotal);
System.out.println("Total Checks: $" + checks);
System.out.println("Total Deposits: $" + deposit);
while (s < o)
{
System.out.println(newType[s] + " " + newTransaction [s] + " " +
newBalance[s]);
s = s + 1;
System.out.println("");
}
}/*end of main()*/
}/*end of class*/

79
OUTPUT:

Enter Your Name


angelus
Hello angelus
angelus enter your account number
1452682
enter your original balance
200000
Enter c for Check; d for Deposit; or p to Print Summary
c
Enter amount
1500
Enter c for Check; d for Deposit; or p to Print Summary
d
Enter amount
200
Enter c for Check; d for Deposit; or p to Print Summary
p
Name angelus, Account Number 1452682
Account Statement
Your balance 400.0
Amount of checks: 1500.0
Overdraft total fees: $0.0
Total Checks: $1500.0
Total Deposits: $200.0
c 1500.0 1500.0

d 200.0 400.0

ALGORITHM:
Step 1: Start
Step 2: The class was created and the data members were
initialized.
Step 3: The name and account number was accepted from the user.

80
Step 4: The balance is transacted as per the users entry.
Step 5: the balance is displayed.
Step 6: End.

VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
newType Char To store the account
number
newTransaction Double To store the
transacted balance
newBalance double To store the balance
o integer To store the balance
s integer To store the balance
t integer To store the total
balance

81
QUESTION NUMBER #19:

write a program to calculate the loan of a person

import java.util.*;
import java.lang.Math;
class loan_calculator/*starting class*/
{
String name,address;
int amount,loan,ch;
double a,emi,rate;
Scanner sc=new Scanner(System.in);
loan_calculator() /*to initialize the data members*/
{
name="";address = "";
amount=0;loan=0;ch=0;
a=0.00;emi=0.00;rate=15.5;
}
void savings() /*for savings account*/
{
System.out.println("Enter your name");
name=sc.next();
System.out.println("Enter your address");
address=sc.next();
System.out.println("Enter the amount of money you want to
open your account with(minimum rs.1000)");
amount = sc.nextInt();
if(amount<1000) /*checks whether the amount entered is
greater than 1000*/
System.out.println("Enter a higher amount");
else
{
System.out.println("Congratulations! Your account has
been created");
System.out.println("Name : "+name);

82
System.out.println("Address :"+address);
System.out.println("Amount : Rs."+amount);
System.out.println("Enter 1 if you want to apply for a
loan ;2 to abort/exit");
ch=sc.nextInt();
if(ch==1)
{
System.out.println("Enter the amount of money for
which you want to apply for loan");
loan=sc.nextInt();
if(loan>(0.8*amount))
System.out.println("You cannot take such a high
amount of loan enter a lower amount");
else{
rate=15.5;
System.out.println("The rate is 15.5% per annum");
System.out.println("The time in which you have to clear
the loan is 1 year");
a=loan*(Math.pow((1+rate/1200),12)); /*calculates
loan*/
emi=a/12; /*calculates emi*/
System.out.println("The amount of money that you have
to pay at the end of one year is : Rs."+a);
System.out.println("The amount of money that you have
to pay at the end of each month is : Rs."+emi);
}
}
else
System.out.println("Thank You for Visiting our Bank");
}
}
void current() /*for current accounts*/
{
System.out.println("Enter your name");
name=sc.next();
83
System.out.println("Enter your address");
address=sc.next();
System.out.println("Enter the amount of money you want to
open your with(minimum rs.500)");
amount = sc.nextInt();
if(amount<500) /*checks whether amount entered is greater
than 500*/
System.out.println("Enter a higher amount");
else
{
System.out.println("Congratulations! Your account has
been created");
System.out.println("Name : "+name);
System.out.println("Address : "+address);
System.out.println("Amount : Rs."+amount);
System.out.println("Enter 1 if you want to apply for a
loan ;2 to abort/exit");
ch=sc.nextInt();
if(ch==1)
{
System.out.println("Enter the amount of money for
which you want to apply for loan");
loan=sc.nextInt();
if(loan>(5*amount))
System.out.println("Enter a lower amount");
else{
rate=15.5;
System.out.println("The rate is 15.5% per annum");
System.out.println("The time in which you have to clear
the loan is 1 year");
a=0.00;
a=loan*(Math.pow((1+rate/1200),12)); /*calculates the
amount*/
emi=a/12; /*calculates the emi*/

84
System.out.println("The amount of money that you have
to pay at the end of one year is : Rs."+a);
System.out.println("The amount of money that you have
to pay at the end of each month is : Rs."+emi);
}
}
else
System.out.println("Thank You for Visiting our Bank");
}
}
public static void main(String args[])/*starting main()*/
{ Scanner sc=new Scanner(System.in);
int c;
loan_calculator ob =new loan_calculator();

do{
System.out.println("MENU");
System.out.println("1.Savings");
System.out.println("2.Current");
System.out.println("3.Exit");
c = sc.nextInt();
switch(c)
{
case 1:ob.savings();
break;
case 2:ob.current();
break;
}

}while(c!=3); /*loop for restarting the program*/


} /*ending main()*/
} /*ending class*/

85
OUTPUT:

MENU
1.Savings
2.Current
3.Exit
1
Enter your name
angelus
Enter your address
118/f anandapalit road
Enter the amount of money you want to open your account
with(minimum rs.1000)
900
Enter a higher amount
MENU
1.Savings
2.Current
3.Exit
1
Enter your name
angelus
Enter your address
118/f anandapalit road
Enter the amount of money you want to open your account
with(minimum rs.1000)

Congratulations! Your account has been created


Name : Angelus
Address :118/f ananda palit road
Amount : Rs.10000
Enter 1 if you want to apply for a loan ;2 to abort/exit
1
Enter the amount of money for which you want to apply for loan
7000
86
The rate is 15.5% per annum
The time in which you have to clear the loan is 1 year
The amount of money that you have to pay at the end of one year
is : Rs.8165.497413837042
The amount of money that you have to pay at the end of each
month is : Rs.680.4581178197535
MENU
1.Savings
2.Current
3.Exit
2
Enter your name
angelus
Enter your address
118/f anada palit road
Enter the amount of money you want to open your with(minimum
rs.500)
500
Congratulations! Your account has been created
Name : angelus
Address : 118/f anada palit road
Amount : Rs.500
Enter 1 if you want to apply for a loan ;2 to abort/exit
1
Enter the amount of money for which you want to apply for loan
2000
The rate is 15.5% per annum
The time in which you have to clear the loan is 1 year
The amount of money that you have to pay at the end of one year
is : Rs.2332.9992610962977
The amount of money that you have to pay at the end of each
month is : Rs.194.41660509135815
MENU
1.Savings
2.Current
87
3.Exit
3
ALGORITHM:

Step 1: Start
Step 2: Class loan_calculator is made and data members are
declared
Step 3: The user is asked whether he/she wants to open a
savings account, a current account or to exit. Each time a
wrong or invalid input is entered the program restarts.
Step 4: If user enters for a savings account his/her name,
address and the amount with which he/she wants to open the
account is asked which should not be less than Rs.1000.
Step 5: The user is asked whether he/she wants to apply for a
loan or not. If yes he/she should not enter an amount more
than 80% of the amount he has opened the account with
otherwise the program terminates.
Step 6: The due amount is calculated by the formulae
Amount = principal*(1+r/1200)12
The emi is calculate by the formulae
Emi = Amount/12
The amount due and emi is displayed and the program
restarts
Step 7: If the user applies for a current account his/her name,
address and the amount with which he/she wants to open the
account with is entered which should not decrease Rs.500
Step 8: The user is asked for a loan if yes the amount of loan is
accepted which can maximum be 5 times the amount entered
Step 9: The amount and the emi are calculated by the above
respective formulae and displayed
Step 10: End

VARIABLE DISTRIBUTION CHART

88
VARIABLE VARIABLE VARIABLE
NAME TYPE DESCRIPTION
name String To store the name
of the user
address String To store the
address of the user
amount Integer To accept the
amount user is
starting his/her
account with
loan Integer To accept the
amount of loan
which the user
wants
ch Integer Used as a flag
variable for
checking
conditions
a Double To store the
calculated due
amount at the end
of 1 year
emi Double To store the
calculated emi
rate Double To store the rate
which is15.5%
c Integer To accept the
choice of the user
whether he/she
wants to start a
savings account, a
current account or
to exit

89
QUESTION NUMBER #20:

A scientific calculator for easier calculations.

import java.util.*; /importing the scanner class*/


class OBQ
public static void main(String args[])/*starting main()*/
{
Scanner sc= new Scanner (Stystem.in);
System.out.println(“Enter for calculation);
String ent=sc.nextLine();
int l= ent.length();
String store[]=new String[l]; /*initializing and declaring the
variables*/
String sign=new String[l];
store[0]=””; sign[0]=””;
int j=0,k=0;
for(i-0;i<l;i++)
{
if(((int)(ent.chartAt(i))>=48)&&(((int)(ent.chartAt(i))<=57))||
(((int)(ent.charAt(i))==46)))
{
store[j]=store[j]+ent.charAt(i);
}
if(((int)(ent.chartAt(i))==43)||(((int)(ent.chartAt(i))==45))||(((int)
(ent.charAt(i))==42))||(((int)(ent.chartAt(i))==47)||(((int)
(ent.chartAt(i))==37))||(((int)(ent.charAt(i))=94)))
{
sign[k]=sign[k]+ent.charAt(i);
store[++j]=””;
k++;
}
}

90
if (sign[0].equalsIgnoreCase(“+”)||sign[0].equalsIgnoreCase(“-”)||
sign[0].equalsIgnoreCase(“*”)||sign[0].equalsIgnoreCase(“/”)||
sign[0].equalsIgnoreCase(“^”)||sign[0].equalsIgnoreCase(“%”))
{
System.out.println();
double num1=Dounle.parseDouble(store[0]);
double num2=Dounle.parseDouble(store[1]);
double total=0;
String re=””:
if(sign[0].equalsIgnoreCase(“+”)) /checking signs*/
{
total=num1+num2;
System.out.println(“The answers is”+total);
}
if (sign[0].equalsIgnoreCase(“-”))
{
total=num1-num2;
System.out.println(“The answers is”+total);
}
if(sign[0].equalsIgnoreCase(“*”))
{
total=num1*num2;
System.out.println(“The answers is”+total);
}
if(sign[0].equalsIgnoreCase(“/”))
{
total=num1/num2;
System.out.println(“The answers is”+total);
}
if(sign[0].equalsIgnoreCase(“%”))
{
total=num1%num2;
System.out.println(“The answers is”+total);
}
if(sign[0].equalsIgnoreCase(“^”))
91
{
total=Math.pow(num1,num2);
System.out.println(“The answers is”+total);
}
String ent2=sc.nextLine();
if(ent2.equalsIgnoreCase(“”))
{
System.exit(0);
}
else
{
do
{
int l2= ent2.length();
String store2[]=new String[12];
store2[0]=””:
char sign2=ent2.charAt(0);
for(int i= 1;i<12;i++)
{
if(((int)(ent.chartAt(i))>=48)&&(((int)(ent.chartAt(i))<=57))||
(((int)(ent.charAt(i))==46)))
{
store2[0]=store2[0]+ent2.charAt9i0;
}
}
double num3= Double.parseDouble(store2[0]);

if (sign2==’+’)
{
total=total+num3;
System.out.println(“The answers is”+total);
}
if (sign2==’-’)
{
total=total-num3;
92
System.out.println(“The answers is”+total);
}

if (sign2==’*’)
{
total=total*num3;
System.out.println(“The answers is”+total);
}

if (sign2==’/’)
{
total=total/num3;
System.out.println(“The answers is”+total);
}

if (sign2==’^’)
{
total=Math.pow(total.num3);
System.out.println(“The answers is”+total);
}

String entey= sc.nextLine();


if(entry.equalsIgnoreCase(“”))
{
break;
}
else
{
ent2=entry;
}
}
while(ent2!=””);
}
}
else
93
{
System.out.println(“Syntax error”);
System.exit(0);
}
}/*end of main()*/
} /*end of class*/

94
OUTPUT:
Enter for calculation
85+96
The answer is 181.0
-81
The answer is 100.0
*5
The answer is 500
/100
The answer is 5.0
^25
The answer is 2.9802322387695315E17
%5
The answer is 2.0

ALGORITHM:
Step 1: Start
Step 2: The class was created and the data members were
initialized.
Step 3: The number was entered by the user
Step 4: The calculations were executed according to the user’s
entry.
Step 5: The answers were displayed.
Step 6: End

VARIABLE DESCRIPTION CHART

VARIABLE VARIABLE TYPE VARIABLE


NAME DESCRIPTION
ent String To store the number
entered by the user
sign String To store the sign
i Integer Loop control
variable
k Integer Counter variable
95
num1 Integer To store the first
number
num2 Integer To store the second
number
num3 Integer To store the thied
number
total Integer To store the total

96
QUESTION NUMBER #21:
A program to convert roman number to decimal number
import java.util.*;
class RomanToNumber {
// This function returns
// value of a Roman symbol
int value(char r)
{
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
// Finds decimal value of a
// given romal numeral
int romanToDecimal(String str)
{
// Initialize result
int res = 0;
for (int i = 0; i < str.length(); i++) {
// Getting value of symbol s[i]
int s1 = value(str.charAt(i));
// Getting value of symbol s[i+1]
if (i + 1 < str.length()) {
97
int s2 = value(str.charAt(i + 1));
// Comparing both values
if (s1 >= s2) {
// Value of current symbol
// is greater or equalto
// the next symbol
res = res + s1;
}
else {
// Value of current symbol is
// less than the next symbol
res = res + s2 - s1;
i++;
}
}
else {
res = res + s1;
i++;
}
}
return res;
}
// Driver method
public static void main(String args[])
{
RomanToNumber ob = new RomanToNumber();
Scanner sc=new Scanner(System.in);
// Considering inputs given are valid
String str = sc.nextLine();
System.out.println(
"Integer form of Roman Numeral"
+ " is " + ob.romanToDecimal(str));
}
}

98
OUTPUT:
XII
Integer form of Roman Numeral is 12
LV
Integer form of Roman Numeral is 55

ALGORITHM:

Step 1: Start
Step 2: Class RomanToNumber is made and data members are
declared
Step 3: The function value is created to check the equivalent
Roman Letters
Step 4: In the main function the input is taken as string and
passed to the romantodecimal function
Step 5: The length of the string is obtained and each character
extracted is sent to the value function to find the equivalent
value.
Step 6: The returned value is stored
Step 7: The result is displayed
Step 10:End
VARIABLE DISTRIBUTION CHART

VARIABLE VARIABLE VARIABLE


NAME TYPE DESCRIPTION
str String To store the roman
value
res integer To store the final
result
i Integer Used in the loop
S1 Integer Stores the returned
value
S2 Integer Stores the returned
value

99
QUESTION NUMBER #22:

A program to generate a magic square matrix


import java.util.*;

class magicsquare
{

static void generateSquare(int n)


{
int[][] magicSquare = new int[n][n];

// Initialize position for 1


int i = n/2;
int j = n-1;

// One by one put all values in magic square


for (int num=1; num <= n*n; )
{
if (i==-1 && j==n) //3rd condition
{
j = n-2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;

//1st condition helper if next number is


// goes to out of square's upper side
if (i < 0)
i=n-1;
}

100
//2nd condition
if (magicSquare[i][j] != 0)
{
j -= 2;
i++;
continue;
}
else
//set number
magicSquare[i][j] = num++;

//1st condition
j++; i--;
}
// print magic square
System.out.println("The Magic Square for "+n+":");
System.out.println("Sum of each row or column
"+n*(n*n+1)/2+":");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
System.out.print(magicSquare[i][j]+" ");
System.out.println();
}
}
// driver program
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();
generateSquare(n);
}
}
OUTPUT:

101
5
The Magic Square for 5:
Sum of each row or column 65:
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24
11 10 4 23 17
ALGORITHM:

Step 1: Start
Step 2: Class magicsquare is made and data members are
declared
Step 3: Accept the size of the matrix
Step 4: declare a 2D square matrix of size given by the user.
Step 5: One by one put all values in magic square
Step 6: 1st condition , if next number goes to out of square's
right side
Step 7: 1st condition , if next number is goes to out of square's
upper side
Step 8: print magic square
Step 10:End
VARIABLE DISTRIBUTION CHART
VARIABLE VARIABLE VARIABLE
NAME TYPE DESCRIPTION
magicSquare[][] Integer To declare the
matrix
i Integer To store the initial
position of row
j Integer To store the initial
position of column
num Integer Values Stored in
the matrix
n Integer Size of the matrix

102

You might also like