Final Project
Final Project
Class: XII - A
Index No:_____________
UID No:_____________
Subject: Computer Science
Teacher’s Name: Tapasya Falor
1
INDEX
SL DATE CONTENTS PAGE REMARK
NO.
NUMBER
1. Acknowledgement 5
2. Introduction 6
2
SL DATE PROGRAM PAGE REMARK
NO.
NUMBER
3
SL DATE PROGRAM PAGE REMARK
NO.
NUMBER
4
ACKNOWLEDGEMENT
I, S o u m y a d e e p R o y , a class XII – A student
, would like to express my gratitude to my Computer
teacher, Mrs. Tapasya Falor, for her guidance and
support in completing my project.
5
INTRODUCTION
Blue J is an integrated development environment (IDE)
for the Java programming language, developed mainly
for educational purposes, but also suitable for small–
scale software development. It runs with the help of
JDK (Java Development Kit). BlueJ was developed to
support the learning and teaching of object-oriented
programming, and its design differs from that of other
development environments. The latest version of BlueJ
is version 5.4.0. The hardware and software
requirements for BlueJ are as follows:
Hardware Requirements :
Software Requirements :
Features:
6
Simple BlueJ has a deliberately smaller and simpler
interface than professional environments like NetBeans
or Eclipse. This allows beginners to get started more
quickly, and without being overwhelmed.
7
PROGRAM 1:
Write a program to display all the magic composite
numbers from 1 to 100. A magic composite number is a
composite number which gives 1 after repeated addition
of the digits of the sum of digits.
Eg: 64 is a magic composite number. Since 6+4=10 and
1+0=1
ALGORITHM
Step 1: Start
Step 2: declaration of class
Step 3: declaration of main()
Step 4: print “the composite magic numbers are:”
Step 5: For i←1 to 100 step value 1
a←i
s←i
c←0
For j←1 to a step value 1
If a%j is equal to 0 then c++
End of j loop
while s>9
n←s
s←0
while n>0
d←n%10
s←s+d
n←n/10
End of inner while loop
End of outer while loop
If s is equal to 1 and c is not equal to 2 then print a
End of i loop
8
Step 6: Stop
CODING
import java. util.*;
class MagiCompNumber
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int a, n, s, d, i, j, c;
System.out.println("The composite magic numbers from 1 to 100 are :");
for(i = 1; i <= 100; i++)
{
a = i;
s = i;
c = 0;
for(j = 1; j <= a; j ++)
{
if(a % j == 0)
c ++;
}//ending of inner loop
while (s > 9)
{
n = s;
s = 0;
while(n > 0)
{
d = n % 10;//extracting the digits.
s = s + d;
n = n / 10;
}//ending of while loop
}
if (s == 1 && c != 2)
9
System.out.println(a);//printing the magic composite number.
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
OUTPUT
10
PROGRAM 2:
Write a program to accept two numbers. Convert the
numbers into their binary forms and display the binary
forms. Perform binary addition on the two numbers and
display the sum.
ALGORITHM
Step 1 : Start
Step 2 : Declaration of class addition
Step 3 : Declaration of main function
Step 4 : Declaration and initialization of variables
Step 5 : Print “enter the first number” and accept it in m
M←sc.nextLong()
Step 6 : Print “enter the second number” and accept it in n
n←sc.nextLong()
Step 7 : Store a copy of both the accepted numbers.
m1← m
n1← n
Step 8 : if(m>0 and n>0) proceed to next step else go to step 17
Step 9 : while(m>0) //loop for converting the first number to binary
d←m%2
binary1←Long.toString(d)+binary 1
m←m/2
end of while loop
Step 10 : while(n>0) //loop for converting the first number to binary
d1← n%2
binary2←Long.toString(d1)+binary2
n←n/2
end of while loop
Step 11 :p← Long.parseLong(binary1) //converting the 1st binary number from string form to long
11
Step 12 : display the 1 st number in binary form
Step 13 : q←Long.parseLong(binary2) //converting the 2nd binary number from string form to long
Step 14 : display the 2nd number in binary form
Step 15 : while(p>0 or q>0)//loop to perform binary addition
x←p%10//extracting the last digit of the 1st binary form
y←q%10//extracting the last digit of the 2nd binary form
if both the digits are zero and carry is zero then sum will be zero
if(x==0 and y==0 and carry==0)
sum← 0
add←Long.toString(sum)+add
if both the first digit is zero and second digit is 1 and carry is zero then sum will be 1
if(x==0 and y==1 and carry==0)
sum← 1
add←Long.toString(sum)+add
if both the first digit is one and the second digit is zero and carry is zero then sum will be 1
if(x==1 and y==0 and carry==0)
sum← 1
add←Long.toString(sum)+add
if both the digits are one and carry is zero then sum will be 0 and carry will be 1
if(x==0 and y==0 and carry==0)
sum← 0
add←Long.toString(sum)+add
carry← 1
if both the digits are zero and carry is 1 then sum will be 1 and carry will be 0
if(x==0 and y==0 and carry==1)
sum← 1
add←Long.toString(sum)+add
carry←0
if the first digit is 1 and the second digit is 0 and carry is 1 then sum will be zero and carry will
be 1
if(x==1 and y==0 and carry==1)
sum← 0
add←Long.toString(sum)+add
12
carry← 1
if both the digits are 1 and carry is 1 then sum will be 1 and carry will be 1
if(x==1 and y==1 and carry==1)
sum← 1
add←Long.toString(sum)+add
carry← 1
p←p/10
q←q/10
end of while loop
Step 16 : if (p==0 and q==0 and carry==1) then
Add ← “1”+add //if a carry is left at the end it will be added Print the added number in binary form
Step 17 : print wrong output
Step 18 : Stop
CODING
import java.util.*;
class Addition
{
public static void main ()
{
Scanner sc =new Scanner (System.in);
long m, n, m1, n1, sum, carry = 0, d = 0, x = 0, d1 = 0, q, p, y = 0;
String binary1="", binary2="", add="";
System.out.println("Enter the first number");
m=sc.nextLong();
System.out.println("Enter the second number");
n=sc.nextLong();
m1 = m;
n1 = n;
if (m > 0 && n > 0)//checking if the entered numbers are valid numbers.
{
while (m > 0)
{
13
d = m % 2;
binary1 = Long.toString(d) + binary1;//converting from long to string
m = m / 2;
}
while(n > 0)
{
d1 = n % 2;
binary2 = Long.toString(d1) + binary2;
n = n / 2;
}
p = Long.parseLong(binary1);//converting from string to long
System.out.println("Binary of " + m1 +" = "+ p);//displaying the binary form
q = Long.parseLong(binary2);
System.out.println("Binary of " + n1 +" = "+ q);
while (p > 0 || q > 0)
{
x = p % 10;
y = q % 10;
if(x == 0 && y == 0 && carry == 0)
{
sum = 0;
add = Long.toString(sum) + add;
}
else if(x == 0 && y == 1 && carry==0)
{
sum = 1;
add = Long.toString(sum) + add;
}
else if(x == 1 && y == 0 && carry == 0)
{
sum = 1;
add = Long.toString(sum) + add;
14
}
else if(x == 1 && y == 1 && carry == 0)
{
sum = 0;
add = Long.toString(sum) + add;
carry = 1;
}
else if(x == 0 && y == 0 && carry == 1)
{
sum = 1;
add = Long.toString(sum) + add;
carry = 0;
}
else if(x == 0 && y == 1 && carry == 1)
{
sum = 0;
add = Long.toString(sum) + add;
carry = 1;
}
else if(x == 1 && y == 0 && carry == 1)
{
sum = 0;
add = Long.toString(sum) + add;
carry = 1;
}
else if(x == 1 && y == 1 && carry == 1)
{
sum = 1;
add = Long.toString(sum) + add;
carry = 1;
}
p = p / 10;
15
q = q / 10;
}
if(p == 0 && q == 0 && carry == 1)
{
add = "1" + add;
System.out.println("The binary addition = " + add);
}
else
{
System.out.println("Wrong input");
}//end of else block
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
16
OUTPUT
17
PROGRAM 3:
Write a program to display the number of days between
2 given dates according to the given functions.
ALGORITHM
Step 1 : Start
Step 2 : Declaration of class
Step 3 : Declaration of array storing the number of days in each month.
Algorithm for isLeap() function
Step 4 : if y is divisible by 400 or divisible by 4 and not 100 then return 29 else return 28
if((y%400==0)
|| ((y%100!=0)&&(y%4==0))) //checking if it is a leap year.
Algorithm for dateValidate() function
Step 5 : if(m12 || dmonth[m] || y9999) //checking if the entered date is valid or not. If these conditions
satisfied then date is not valid and false is returned else true is returned.
Algorihm for dayno() function
Step 6 : month[2]=isLeap(y)//calling the isLeap function and assigning the number of days in
February.
Step 7:for i←1 to m step 1
dn←dn+month[i]//calculating the number of days.
end of for loop
Step 8 : dn←dn+d //adding the number of days left in the month emtered by the user.
Step 9 : For i←1000 to y step 1
if(isLeap(i)==29)//checking if it is a leap year
if leap year then dn←dn+366 else add 365 days dn←dn+365
end of for loop
Step 10 : return dn
Algorithm for main function
Step 11 : Declaration of scanner class
Scanner sc←new Scanner(System.in)
Step 12 : accept the first date.
String date1←sc.nextLine().trim();
18
Step 13 : extracting the days months and year from the first date. //Extracting the day
P←date1.indexOf("/");
CODING
import java.util.*;
class date
{
int month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
//function for checking for Leap Year
int isLeap(int y)
{
if((y % 400 == 0) || (( y % 100 !=0 ) && ( y % 4 == 0)))
return 29;
else
19
return 28;
}
//function for checking date validation
Boolean dateValidate(int d, int m, int y)
{
month[2] = isLeap(y);
if(m < 1 || m > 12 || d < 1 || d > month[m] || y < 1000 || y > 9999)
return false;
else
return true;
}
//function for finding day number from year = 1 till the inputted year
int dayno(int d, int m, int y)
{
int dn =0;
month[2] = isLeap(y);
for(int i = 1; i < m ; i ++)
{
dn = dn + month[i];
}
dn =dn + d;
for(int i = 1000; i < y; i ++)
{
if(isLeap(i) == 29)
dn = dn + 366;
else
dn = dn + 365;
}
return dn;
}
public static void main(String args[])
{
20
Scanner sc = new Scanner(System.in);
date ob = new date();
System.out.print("Enter the 1st date in (dd/mm/yyyy) format: ");
String date1 = sc.nextLine().trim();
int p, q;
//Extracting the day
p = date1.indexOf("/");
int d1 = Integer.parseInt(date1.substring(0, p));
//Extracting the month
q =date1.lastIndexOf("/");
int m1 = Integer.parseInt(date1.substring(p + 1, q));
//Extracting the year
int y1 = Integer.parseInt(date1.substring(q + 1));
System.out.print("Enter the 2nd date in (dd/mm/yyyy) format: ");
String date2 = sc.nextLine().trim();
p = date2.indexOf("/");
int d2 = Integer.parseInt(date2.substring(0, p));
q = date2.lastIndexOf("/");
int m2 = Integer.parseInt(date2.substring(p + 1, q));
int y2 = Integer.parseInt(date2.substring(q + 1));
//Validating both the dates
if(ob.dateValidate(d1, m1, y1) == true && ob.dateValidate(d2, m2, y2) == true)
{
int a = ob.dayno(d1, m1, y1);
int b = ob.dayno(d2, m2, y2);
System.out.print("Output: Difference = "+ Math.abs(a - b) + " days.");
}
else
System.out.println("Invalid Date");
}
}
21
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. month[] int 52 bytes global Used to store the number of days in each
month.
OUTPUT
22
PROGRAM 4:
Write a program to accept two positive integers m and
n, where m must be less than n and the values of both
'm' and 'n' must be greater than 99 and less than 10000
as user input. Display all fascinating numbers that are in
the range between m and n (both inclusive) and output
them along with the frequency, in the format given
below:
INPUT: m = 100
INPUT: n = 500
OUTPUT: THE FASCINATING NUMBERS ARE:
OUTPUT: 192 219 273 327
OUTPUT: FREQUENCY OF FASCINATING
NUMBERS: 4
ALGORITHM
Step 1: Start
Step 2: Declare the Fascinating class.
Step 3: Declare the main() method.
Step 4: Create a Scanner object to take input from the user.
Step 5: Print "Enter lower boundary:" and store the input in the variable m.
Step 6: Print "Enter upper boundary:" and store the input in the variable n.
Step 7: Check if m > 99, n < 10000, and m < n.
If true, proceed to the next steps.
If false, print "Invalid input" and skip to Step 12.
Step 8: Initialize a variable count to 0.
Step 9: Print "THE FASCINATING NUMBERS ARE:".
Step 10: Loop through each number i from m to n:
Step 10.1: Check if i is a fascinating number by calling the isFascinating(i) method.
23
Step 10.2: If isFascinating(i) returns true, print i and increment count by 1.
Step 11: After the loop, print "FREQUENCY OF FASCINATING NUMBERS:" followed by the
value of count.
Step 12: Stop.
CODING
import java.util.*;
class Fascinating
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int m, n;
//taking input from user
System.out.println("Enter lower boundary:");
m = sc.nextInt();
System.out.println("Enter upper boundary:");
n = sc.nextInt();
if(m > 99 && n < 10000 && m < n)//checking if numbers match parameters
{
int count = 0;
System.out.println("THE FASCINATING NUMBERS ARE:");
for (int i = m; i <= n; i++)
{
if (isFascinating(i))//calling method
{
System.out.print(i + " ");
count++;
}
}
System.out.println();
System.out.println("FREQUENCY OF FASCINATING NUMBERS: " + count);
}
24
else
{
System.out.println("Invalid inpupt");
}
}
//method to check if a number is fascinating
static boolean isFascinating(int num)
{
String con = num + "" + (num * 2) + "" + (num * 3);//creating concatenated number
if (con.length() != 9)
{
return false;
}
boolean[] digits = new boolean[9];
for (char c : con.toCharArray())
{
if (c == '0' || digits[c - '1'])
{
return false;
}
digits[c - '1'] = true;
}
for (boolean digit : digits)
{
if (!digit)
{
return false;
}
}
return true;
}
}
25
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
26
OUTPUT
27
PROGRAM 5:
Write a program to accept a number and display it in
roman numerals.
For example: INPUT – 15 should give the OUTPUT –
XV.
ALGORITHM
Step 1 : Start
Step 2 : Declaration of class – Roman
Step 3 : Declaration of main function
Step 4 : Declaration and initialization of variables
Step 5 : Initialization of the two arrays . One with roman symbols and other with its corresponding
values.
a[] ←{'I','V','X','L','C','D','M'}
b[]← { 1,5,10,50,100,500,1000}
Step 6 : Accept the number entered by the user in n.
n← sc.nextInt()
Step 7 : For i← 6 to 0 Step -1
m ← n/b[i]
if m>0
For j ←1 to m Step 1
Print a[i] //printing the corresponding roman numeral
End of j loop
n=n%b[i]
End of i loop
Step 8 : Stop
CODING
import java.util.*;
class Roman
{
28
public static void main()
{
Scanner sc = new Scanner(System.in);
char a[] = {'I','V','X','L','C','D','M'};//storing the roman symbols
int b[] = {1,5,10,50,100,500,1000};//storing the equivalent values of the symbols
int n, i, m, j;
System.out.println("Enter the number:");
n = sc.nextInt();//accepting number from the user.
for(i = 6; i >= 0; i --)
{
m = n / b[i];
if(m > 0)
{
for(j = 1; j <= m; j ++)
{
System.out.print(a[i]);
}//end of j loop
}
n = n % b[i];
}//end of i loop
}//end of main() function
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
29
4. m int 4 bytes local Used to store the number of times a
particular roman numeral is to be
printed.
OUTPUT
30
PROGRAM 6:
Write a menu driven program to sort a given array by
the help of different sorting methods, that is, bubble
sort, selection sort and insertion sort.
ALGORITHM
Step 1 : Start
Step 2 : Declaration of class – Sorting
Algorithm for input()
Step 3 : Declaration of Scanner class
Step 4 : Accept the elements of the array using for loop
Algorithm for display()
Step 5 : display the elements of the array using for loop
Algorithm for selection()
Step 6 :for i←0 to 9 step 1
min←i
for j←i+1 to 10 step 1
if(a[j]<a[min])//comparing two consecutive elements
min←j
end of j loop
//swapping the elements.
t←a[i]
a[i] ←a[min]
a[min] ←t
end of i loop
Algorithm for bubble()
Step 7: for i←0 to 9 step 1
For j←0 to (9-i) step 1
if(a[j]<a[j+1])//comparing two elements
//swapping the elements.
t←a[j]
31
a[j] ←a[j+1]
a[j+1] ←t
end of j loop
end of i loop
Algorithm for insertion()
Step 8: for i←01 to 10 step 1
Temp←a[i]
Ptr←i-1
while(a[ptr]>temp)
a[ptr+1] ←a[ptr]
ptr—
end of while loop
a[ptr+1] ←temp
end of i loop
Algorithm for main() function
Step 9 : Declaration of Scanner class
Scanner sc←new Scanner(System.in)
Step 10 : display the menu and accept the user‟s choice in ch
Step 11 : switch(ch)//starting of switch block //go to the respective case based on the choice
case 1://to sort the array by using selection sort
ob.display()//display the original array
ob.selection()//calling the function to perform selection sort.
ob.display()//display the sorted array and go to step 12
case 2://to sort the array by using bubble sort
ob.display()//display the original array
ob.bubble()//calling the function to perform bubble sort.
ob.display()//display the sorted array and go to step 12
case 3://to sort the array by using insertion sort
ob.display()//display the original array
ob.insertion()//calling the function to perform insertion sort.
ob.display()//display the sorted array andgo to step 12
default: in case the choice is not in between 1-3
32
display “invalid choice!”
Step 12 : stop.
CODING
import java.util.*;
class Sorting
{
int a[] = new int[9];
int i, j;
void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the elements of the array");
for(i = 0; i < 9; i ++)
{
a[i] = sc.nextInt();
}
}
void display()
{
for(i =0; i < 9; i ++)
{
System.out.print(a[i] + “ “);
}
System.out.println();
}
void selection()
{
int t ,min;
for(i = 0; i < 8; i ++)
{
min = i;
for(j = i + 1; j < 9; j ++)
33
{
if(a[j] < a[min])//comparing the two elements
min = j;
}
//swapping the elements
t = a[i];
a[i] = a[min];
a[min] = t;
}
}
void bubble()
{
int t;
for(i = 0; i < 8; i ++)
{
for(j = 0; j < (8 - i); j++)
{
if(a[j] < a[j + 1])//comparing the two elements
{
//swapping the elements.
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}
void insertion()
{
int ptr, temp;
for(i = 1; i < 9; i ++)
{
34
temp = a[i];
ptr = i - 1;
while(a[ptr ] >temp)//comparing
{
a[ptr + 1] = a[ptr];
ptr--;
}
a[ptr + 1] = temp;
}
}
public static void main()
{
Scanner sc = new Scanner(System.in);
Sorting ob = new Sorting();
ob.input();
System.out.println("1.Press 1 for performing selection sort");
System.out.println("2.Press 2 for performing bubble sort");
System.out.println("3.Press 3 for performing insertion sort");
System.out.println("Enter your choice");
int ch = sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Original array");
ob.display();
ob.selection();
System.out.println("Sorted array");
ob.display();
break;
case 2:
System.out.println("Original array");
ob.display();
35
ob.bubble();
System.out.println("Sorted array");
ob.display();
break;
case 3:
System.out.println("Original array");
ob.display();
ob.insertion();
System.out.println("Sorted array");
ob.display();
break;
default:
System.out.println("Invalid choice");
break;
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
36
OUTPUT
37
PROGRAM 7:
Write a program to accept a sentence which may be
terminated by either ‘.’ , ‘?’ or ‘!’. The words are to be
separated by a single blank space and are in UPPER
CASE.
Perform the following tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence
into palindrome words by concatenating the word by its
reverse(excluding the last character).
(c) Display the original sentence along with the
converted sentence.
For Example: INPUT: THE BIRD IS FLYING.
For Example: OUTPUT: THEHT BIRDRIB ISI
FLYINGNILYF.
ALGORITHM
Step 1 : Start
Step 2 : Declaration of class
Step 3: Declaration of the Scanner class
Scanner sc←new Scanner(System.in)
Step 4 : Accept the sentence from the user.
s←sc.nextLine()
Step 5 : Find the length of the sentence.
l←s.length()
Step 6 :if(s.charAt(l-1)=='.'||s.charAt(l-1)=='?'||s.charAt(l-1)=='!')//checking if the sentence ends with
a
fullstop or a question mark or exclamation mark. If true then go to step 7 else go to step 10
38
Step 7 : for i←0 to l step 1
Ch←s.charAt(i) //extracting each letter from the sentence
if(ch!=' ')//checking if a word has ended if not so then
w←w+ch//store the letters together as a word
rw←ch+rw//store the letters as the reverse of the word
else if a word is complete then
ns←ns+" "+w+rw.substring(1)//form the new sentence by making the words palindrome.
w←""//empty the variable for a new word
rw←""//empty the variable for a new reverse word
End of for loop
Step 8 : display the original sentence
Step 9 : display the changed sentence then go to step 11
Step 10 : display invalid input
Step 11 : Stop
CODING
import java.util.*;
class Palindrome
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String s = sc.nextLine();
int l = s.length();
int i;
String w = "", rw="", ns="";
char ch;
if(s.charAt(l - 1) == '.' || s.charAt(l - 1) == '?'|| s.charAt(l - 1) == '!')//checking if the sentence ends
with a full stop, question mark or exclamation mark
{
for(i = 0; i < l; i ++)
{
39
ch = s.charAt(i);//extracting the characters.
if(ch != ' ')
{
w = w + ch;//forming the word.
rw = ch + rw;//forming the reverse word.
}
else
{
ns = ns + " " + w + rw.substring(1);//forming the new string.
w = "";//emptying the variable for the new word.
rw = "";//emptying the varaiable for new word.
}
}
System.out.println("Original Sentence:");
System.out.println(s);
System.out.println("New Sentence:");
System.out.println(ns);
}
else
{
System.out.println("Invalid Input");
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
40
3. l int 4 bytes local To store the length of the sentence.
6. rw String More than local Used to store the reverse of the words
2 bytes temporarily.
OUTPUT
41
PROGRAM 8:
Write a program to exchange the two consecutive words
in the sentence entered by the user.
For example: INPUT – This is a ball which is red.
For example: OUTPUT – is This ball a is which red.
ALGORITHM
Step 1 : Start
Step 2 : class – interchange_word
Step 3 : Declaration and Initialization of variables
Step 4 : Starting of the input() function
Step 5 : Print “enter the sentence”
str ← sc.nextLine()
Step 6 : str←str+ “ “
Step 7: Closing of the input()
Step 8 : Starting of the compute()
Step 9 : Finding the length of the string
l ← str.length()
Step 10 : For i←0 to i<=c step value 1
ch←str.charAt(i)//extracting the characters of the string
if(ch!=) //checking whether the character is a space or not
w←w+ch
else
//starting of else block
a[c] ←w
c←c+1
w←””
ending of else block
ending of for loop
Step 11: For j←0 to je step value 1
42
if(j%2!=0)
starting of if block
B[j-1]←a[j]
b[j] ←a[j-1]
ending of if block
end of for loop
Step 12 : if(c%2!=0)
b[c-1]←a[c-1]
Step 13 : closing of compute() function
Step 14 : Starting of display()
Step 15: For i0 to i<c step value 1
Print b[i]+" "
Step 16: Starting of main()
Step 17: Creating an object ob
Interchange_word ob←new interchange_word()
Step 18: Calling all the functions using the object ob
Step 19: End
CODING
import java.util.*;
class interchange_word
{
int i, j, l, c = 0;
String str, w = "";
char ch;
String a[] = new String[20];
String b[] = new String[20];
void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
str = sc.nextLine();
str = str + " ";
43
}
void compute()
{
l = str.length();//calculating the length of the string
for(i = 0; i < l; i ++)
{
ch = str.charAt(i);//extracting each character
if(ch != ' ')
w = w + ch;
else
{
a[c] = w;//storing the words in an array
c = c + 1;
w = "";
}
}
for(j = 1; j <= c; j ++)
{
if(j % 2 != 0)
{
//Interchanging the words.
b[j - 1] = a[j];
b[j] = a[j - 1];
}
}
if(c % 2 != 0)
b[c - 1] = a[c - 1];
}
void display()
{
System.out.println("The new sentence is : ");
for(i = 0; i < c; i ++)
44
{
System.out.print(b[i] + " ");
}
}
public static void main()
{
interchange_word ob =new interchange_word();//creating the object
ob.input();//calling the function
ob.compute();
ob.display();
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. a[] String More than 2 local To store the words of the sentence.
bytes
7. b[] String More than 2 local Used to store the sentence after
bytes arranging.
45
OUTPUT
46
PROGRAM 9:
Write a program to print the entered string in the given
format.
Example INPUT : COMPUTER IS VERY
INTERESTING SUBJECT
OUTPUT : C I V I S
O S E N U
M R T B
P. Y E J
U R E
T E C
E S T
R T
I
N
G
ALGORITHM
Step 1: Start
Step 2: class-display
Step 3 : starting of the main function
Step 4 : Declaration and initialization of variables
Step 5 : Print “enter the sentence” s
tr←sc.nextLine()
Step 6 : str←str+ “ ”
47
Step 7 : Finding out the length
l←str.length()
Step 8: For i←0 to i<l step value 1
ch←str.charAt(i);
if(ch!='')
wl←wl+ch:
if(ch=='')
{
len w1.length();
if(len>max)
max←len;
w1←””
}
End of i loop
Step 9: For i←0 to i<=max step value 1
For j0 to j<l step value 1
ch←str.charAt(j):
if(ch!='')
w←w+ch:
else
{
11←w.length();
if(11>i)
{
ch1←w.charAt(i);
print ch1+"\t"
}
else
print " "+"\t"
w←"";
End of j loop
End of i loop
48
Step 10 : Print an empty line.
Step 11 : End
CODING
import java.util.*;
class display
{
public static void main()
{
Scanner sc = new Scanner(System.in);
String str, w = "", w1 = "";
char ch, ch1;
int l, len, max = 0, l1, j, i;
System.out.println("Enter a sentence:");
str = sc.nextLine();
str = str + " ";
l = str.length();
for(i = 0; i < l; i ++)
{
ch = str.charAt(i);//extracting the characters.
if(ch != ' ')
w1 = w1 + ch;//forming the word.
if(ch == ' ')
{
len = w1.length();
if(len > max)//comparing the lengths
max = len;//storing the maximum length
w1 = "";//emptying the variable for the next word.
}
}
for(i = 0; i <= max; i ++)
{
for(j = 0; j < l; j ++)
49
{
ch = str.charAt(j);
if(ch != ' ')
w = w + ch;
else
{
l1 = w.length();
if(l1 > i)
{
ch1 = w.charAt(i);
System.out.print(ch1 + "\t");
}
else
System.out.print(" " + "\t");
w = "";
}
}
System.out.println();
}//end of for loop
}//end of function
}//end of class
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
50
5. ch1 char 2 bytes local To extract the characters to be printed.
10. max int 4 bytes local Used to store the maximum length.
OUTPUT
51
PROGRAM 10:
Write a program to encrypt a sentence by rotation
through 13 of each character.
For Example: INPUT: Hello! How are you?
For Example: OUTPUT: Uryyb! Ubj ner lbh?
ALGORITHM
Step 1 : Start
Step 2 : class –encrypt
Step 3 : starting of the main function
Step 4 : Declaration and initialization of variables
Step 5 : Print “enter the sentence to be encrypted”
str←sc.nextLine()
Step 6 : Finding out the length
l←str.length()
Step 7: For i0 to i<l step value 1
ch←str.charAt(i) //extracting the characters
n← (char)ch //conversion of character into its ascii value.
if((n>=65&&n<=90) ||(n>=97&&n<=122)) //checking if it is a letter
start of if block
if((n>=65&&n<=77)||(n>-97&&n<=109))
start of if block
ch1 ← (char)(n+13)
w←w+chl
end of if block
if(n>=78&&n<=90)
start of if block
ch1← (char)(12-(90-n)+65)
w←w+ch1
end of if block
52
if(n>=110&&n<=122)
start of if block
ch1← (char)(12-(122-n)+97)
w←w+ch1
end of if block
else
w←w+ch
end of for loop
Step 8: Print the encrypted sentence
Step 9 : End
CODING
import java.util.*;
class encrypt
{
public static void main()
{
Scanner sc = new Scanner(System.in);
String str, w = "";
int i, l, n;
char ch, ch1;
System.out.println("Enter the sentence to be encrypted:");
str = sc.nextLine();
l = str.length();
for(i = 0; i < l; i ++)
{
ch = str.charAt(i);
n = (int)ch;
if((n >= 65 && n <= 90)||(n >= 97 && n<= 122))//checking if the letter is in between a and z
{
if((n >= 65 && n <= 77)||(n >= 97 && n <= 109))//checking if the letter is in between a and
m
{
53
ch1 = (char)(n + 13);//storing the letter 13 letters after the actual letter
w = w + ch1;
}
if(n >= 78 && n <= 90)//checking if the letter is between M and Z
{
ch1 = (char)(12 - (90 - n) + 65);
w = w + ch1;
}
if(n >= 110 && n <= 122)//checking if the letter is in small and between m and z
{
ch1 = (char)(12 - (122 - n) + 97);
w = w + ch1;
}
}
else
w = w + ch;
}
System.out.println("The new string:");
System.out.println(w);
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
54
5. l int 4 bytes local Used to store the length of the
sentence.
6. n int 4 bytes local Used to store the ascii value.
OUTPUT
55
PROGRAM 11:
Write a program to input a String and reverse the
original string by using recursive function. Display the
new string.
INPUT : Enter a word : COMPUTER
OUTPUT : The reverse word : RETUPMOC
ALGORITHM
Step 1: Start.
Step 2: Define the class ReverseString.
Step 3: Declare the recursive function reverseString(String str) to reverse a string.
Step 3.1: If str is empty (base case), return str.
Step 3.2: Otherwise, return the result of reverseString(str.substring(1)) + str.charAt(0).
Step 4: In the main() method:
Step 4.1: Initialize a Scanner object sc to read input from the user.
Step 4.2: Prompt the user to "Enter a word" and store the input in original.
Step 4.3: Call reverseString(original) to reverse the word and store the result in reversed.
Step 4.4: Display the reversed word by printing reversed.
Step 5: End.
CODING
import java.util.Scanner;
class ReverseString
{
// Recursive function to reverse a string
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
56
}
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String original = sc.nextLine();
String reversed = reverseString(original);
System.out.println("The reverse word: " + reversed);
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
2. original String More than 2 local Stores the input word entered by
bytes the user.
3. reversed String More than 2 local Stores the reversed version of the
bytes input word, generated by the
recursive function.
OUTPUT
57
PROGRAM 12:
Write a program to input 10 numbers in a single
dimensional array. Enter number and search whether the
number is present or not by using binary search
technique. If the number is present then display a
message “Number is present” otherwise display
“Number is not present”. Use a recursive function that
returns 1 if the number to be searched in the array is
found otherwise it returns 0.
ALGORITHM
Step 1: Start.
Step 2: Define the class BinarySearchProgram.
Step 3: In the main() method:
Step 3.1: Initialize a Scanner object sc to read input from the user.
Step 3.2: Declare an integer array arr of size 10.
Step 3.3: Print a prompt to the user to enter 10 numbers.
Step 3.4: Loop i from 0 to 9 and store each input in arr[i].
Step 4: Sort arr using Arrays.sort(arr) to prepare it for binary search.
Step 5: Display the sorted array.
Step 6: Prompt the user to enter a target number to search in the array, and store it in target.
Step 7: Call the binarySearch function with arguments arr, 0, arr.length - 1, and target.
Step 7.1: If the result is 1, print "Number is present".
Step 7.2: Otherwise, print "Number is not present".
Step 8: Define the recursive binarySearch(int[] arr, int left, int right, int target) function.
Step 8.1: Base condition: If left > right, return 0 (target not found).
Step 8.2: Calculate mid as (left + right) / 2.
Step 8.3: If arr[mid] is equal to target, return 1 (target found).
Step 8.4: If arr[mid] is greater than target, call binarySearch(arr, left, mid - 1, target).
Step 8.5: If arr[mid] is less than target, call binarySearch(arr, mid + 1, right, target).
58
Step 9: End
CODING
import java.util.*;
class BinarySearchProgram
{
// Recursive binary search function
static int binarySearch(int[] arr, int left, int right, int target)
{
// Base condition: if left index exceeds right, target not found
if (left > right)
{
return 0;
}
// Find the middle index
int mid = (left + right) / 2;
// Check if the middle element is the target
if (arr[mid] == target)
{
return 1;
}// If target is smaller, search the left half
if (arr[mid] > target)
{
return binarySearch(arr, left, mid - 1, target);
}
// If target is larger, search the right half
return binarySearch(arr, mid + 1, right, target);
}
public static void main()
{
Scanner sc = new Scanner(System.in);
int[] arr = new int[10];
59
// Input 10 numbers into a single-dimensional array
System.out.println("Enter 10 numbers:");
for (int i = 0; i < 10; i++)
{
arr[i] = sc.nextInt();
}
// Sort the array for binary search
Arrays.sort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
// Input the number to search for
System.out.print("Enter the number to search: ");
int target = sc.nextInt();
// Perform binary search and display result
if (binarySearch(arr, 0, arr.length - 1, target) == 1)
{
System.out.println("Number is present");
}
else
{
System.out.println("Number is not present");
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
60
3. target int 4 bytes main The integer number input by the
user to be searched for in the array.
4. left int 4 bytes binarySearch The left index of the subarray to be
searched in binarySearch.
5. right int 4 bytes binarySearch The right index of the subarray to
be searched in binarySearch.
OUTPUT
61
PROGRAM 13:
Write a program to generate the elements of Fibonacci
series up to a given limit entered by the user. The
program follows a recursive function to return Tth
Fibonacci element where T is the term number.
ALGORITHM
Step 1: Start.
Step 2: Define the class FibonacciSeries.
Step 3: Define the fibonacci(int term) function to calculate the Fibonacci term recursively.
Step 3.1: If term <= 1, return term (base cases: F(0) = 0, F(1) = 1).
Step 3.2: Otherwise, return fibonacci(term - 1) + fibonacci(term - 2) to calculate the term
recursively.
Step 4: In the main() method:
Step 4.1: Create a Scanner object scanner to read user input.
Step 4.2: Prompt the user to enter the upper limit for the Fibonacci series.
Step 4.3: Read the user input and store it in limit.
Step 5: Print "Fibonacci series up to limit: " to introduce the output.
Step 6: Initialize an integer term to 0. Begin a while loop to generate Fibonacci terms:
Step 6.1: Calculate fibTerm as fibonacci(term).
Step 6.2: If fibTerm is greater than limit, exit the loop.
Step 6.3: Otherwise, print fibTerm.
Step 6.4: Increment term to continue calculating the next Fibonacci term.
Step 7: End.
CODING
import java.util.*;
public class FibonacciSeries
{
// Recursive function to return the Tth Fibonacci element
static int fibonacci(int term)
62
{
if (term <= 1)
{
return term; // Base cases: F(0) = 0 and F(1) = 1
}
return fibonacci(term - 1) + fibonacci(term - 2); // Recursive case
}
public static void main()
{
Scanner sc = new Scanner(System.in);
// Ask the user for the limit
System.out.print("Enter the limit for Fibonacci series: ");
int limit = sc.nextInt();
System.out.println("Fibonacci series up to " + limit + ":");
// Generate and print Fibonacci series up to the given limit
int term = 0;
int fibTerm;
while ((fibTerm = fibonacci(term)) <= limit)
{
System.out.print(fibTerm + " ");
term++;
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. limit int 4 bytes main The upper limit specified by the user
for the Fibonacci series output.
63
3. fibterm int 4 bytes main Holds the current Fibonacci term
generated by the fibonacci() function in
each iteration.
OUTPUT
64
PROGRAM 14:
Write a program that performs GCD of two numbers
using recursive function.
ALGORITHM
Step 1: Start.
Step 2: Define the class GCD.
Step 3: Define the gcd(int a, int b) function to calculate the GCD recursively.
Step 3.1: If b == 0, return a (base case).
Step 3.2: Otherwise, return gcd(b, a % b) to continue finding the GCD recursively.
Step 4: In the main() method:
Step 4.1: Create a Scanner object scanner to read user input.
Step 4.2: Prompt the user to enter two numbers and store them in num1 and num2.
Step 5: Call the gcd(num1, num2) function to calculate the GCD and store the result in result.
Step 6: Display the result by printing "The GCD of num1 and num2 is: result".
Step 7: End.
CODING
import java.util.Scanner;
public class GCD
{
// Recursive function to find GCD of two numbers
static int gcd(int a, int b)
{
// Base case: if b is 0, GCD is a
if (b == 0)
{
return a;
}
// Recursive case: gcd(b, a % b)
return gcd(b, a % b);
65
}
public static void main()
{
Scanner scanner = new Scanner(System.in);
// Input two numbers from the user
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate GCD using the recursive function
int result = gcd(num1, num2);
// Display the result
System.out.println("The GCD of " + num1 + " and " + num2 + " is: " + result);
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. num1 int 4 bytes main The first integer input by the user for
which the GCD will be calculated.
2. num2 int 4 bytes main The second integer input by the user
for which the GCD will be calculated.
3. result int 4 bytes main Holds the calculated GCD of num1 and
num2.
66
OUTPUT
67
PROGRAM 15:
Write a program to find the saddle point of an double
dimension array. A saddle point is that element which is
maximum in row and minimum in column.
ALGORITHM
Step 1: Start.
Step 2: Define the class SaddlePoint.
Step 3: In the main() method:
Step 3.1: Create a Scanner object sc to read user input.
Step 3.2: Prompt the user to enter the number of rows and columns of the matrix, and
store them in n and m respectively.
Step 4: Declare a 2D integer array matrix of dimensions n x m.
Step 5: Input elements into the matrix.
Step 5.1: For each row i from 0 to n-1:
o Step 5.2: For each column j from 0 to m-1:
Step 5.3: Prompt the user to enter a value, and store it in matrix[i][j].
Step 6: Display the matrix in a structured format.
Step 6.1: For each row i from 0 to n-1:
o Step 6.2: For each column j from 0 to m-1:
Step 6.3: Print matrix[i][j], followed by a tab character.
o Step 6.4: After each row, move to the next line.
Step 7: Initialize a Boolean variable saddlePointFound to false.
Step 8: For each row i from 0 to n-1:
Step 8.1: Set maxInRow to the first element of the row (matrix[i][0]) and colIndex to 0.
Step 8.2: For each column j from 1 to m-1:
o Step 8.3: If matrix[i][j] is greater than maxInRow:
Step 8.4: Update maxInRow to matrix[i][j] and set colIndex to j.
Step 9: Check if maxInRow is the minimum element in its column.
Step 9.1: Initialize a Boolean variable isSaddlePoint to true.
Step 9.2: For each row k from 0 to n-1 in the column colIndex:
68
o Step 9.3: If matrix[k][colIndex] is less than maxInRow, set isSaddlePoint to false
and break out of the loop.
Step 10: If isSaddlePoint remains true, then a saddle point is found.
Step 10.1: Print the coordinates (i, colIndex) and the value maxInRow.
Step 10.2: Set saddlePointFound to true and break out of the main loop.
Step 11: After the loop completes, if no saddle point was found (saddlePointFound is false), print
"No saddle point found in the matrix."
Step 12: End.
CODING
import java.util.*;
class SaddlePoint
{
public static void main()
{
Scanner sc = new Scanner(System.in);
// Input the dimensions of the array
System.out.print("Enter the number of rows: ");
int n = sc.nextInt();
System.out.print("Enter the number of columns: ");
int m = sc.nextInt();
// Declare a 2D array
int[][] matrix = new int[n][m];
// Input elements in the matrix
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = sc.nextInt();
}
}
// Displays the matrix
69
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
// Find and display the saddle point
boolean saddlePointFound = false;
for (int i = 0; i < n; i++)
{
int maxInRow = matrix[i][0];
int colIndex = 0;
// Find the maximum element in the current row
for (int j = 1; j < m; j++)
{
if (matrix[i][j] > maxInRow)
{
maxInRow = matrix[i][j];
colIndex = j;
}
}
// Check if this max element is the minimum in its column
boolean isSaddlePoint = true;
for (int k = 0; k < n; k++)
{
if (matrix[k][colIndex] < maxInRow)
{
isSaddlePoint = false;
break;
}
70
}// If saddle point is found
if (isSaddlePoint)
{
System.out.println("Saddle point found at (" + i + ", " + colIndex + ") with value: " +
maxInRow);
saddlePointFound = true;
break;
}
}
if (!saddlePointFound)
{
System.out.println("No saddle point found in the matrix.");
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
71
7. isSaddlePoint boolean 1 byte main Indicates if maxInRow is the
(inner minimum value in its column,
loop) making it a saddle point.
OUTPUT
72
PROGRAM 16:
Write a program to show the addition, subtraction and
multiplication of two arrays and print the three 2D
arrays.
ALGORITHM
Step 1: Start.
Step 2: Define the class Array2D.
Step 3: In the main() method:
Step 3.1: Create a Scanner object named sc to read user input.
Step 3.2: Prompt the user to enter the number of rows (m) and columns (n) for the 2D arrays.
Step 3.3: Declare two 2D arrays a1 and a2 of size m x n to store the elements.
Step 4: Input the elements for the first 2D array (a1):
Step 4.1: Loop through each row i and column j to read and store the elements in a1[i][j].
Step 5: Input the elements for the second 2D array (a2):
Step 5.1: Loop through each row i and column j to read and store the elements in a2[i][j].
Step 6: Declare three 2D arrays add, sub, and mult to store the results of addition, subtraction, and
multiplication respectively.
Step 7: Perform element-wise operations on the arrays:
Step 7.1: Loop through each row i and column j:
o Step 7.1.1: For add[i][j], calculate the sum: a1[i][j] + a2[i][j].
o Step 7.1.2: For sub[i][j], calculate the difference: a1[i][j] - a2[i][j].
o Step 7.1.3: For mult[i][j], calculate the product: a1[i][j] * a2[i][j].
Step 8: Display the results:
Step 8.1: Print the elements of the first array a1.
Step 8.2: Print the elements of the second array a2.
Step 8.3: Print the add array (addition result).
Step 8.4: Print the sub array (subtraction result).
Step 8.5: Print the mult array (multiplication result).
Step 9: End.
73
CODING
import java.util.*;
public class Array2D
{
public static void main()
{
Scanner sc = new Scanner(System.in);
// Input the dimensions of the 2D arrays
System.out.print("Enter the number of rows: ");
int m = sc.nextInt();
System.out.print("Enter the number of columns: ");
int n = sc.nextInt();
// Declare two 2D arrays
int[][] a1 = new int[m][n];
int[][] a2 = new int[m][n];
// Input elements for the first 2D array
System.out.println("Enter elements for the first 2D array:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
a1[i][j] = sc.nextInt();
}
}
// Input elements for the second 2D array
System.out.println("Enter elements for the second 2D array:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
a2[i][j] = sc.nextInt();
74
}
}
// Declare 2D arrays to store results of operations
int[][] add = new int[m][n];
int[][] sub = new int[m][n];
int[][] mult = new int[m][n];
// Perform addition, subtraction, and multiplication
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
add[i][j] = a1[i][j] + a2[i][j];
sub[i][j] = a1[i][j] - a2[i][j];
mult[i][j] = a1[i][j] * a2[i][j];
}
}
// Print the original array and the three result arrays
System.out.println("First Array:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(a1[i][j] + "\t");
}
System.out.println();
}
System.out.println("Second Array:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(a2[i][j] + "\t");
75
}
System.out.println();
}
System.out.println("Addition of Arrays:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(add[i][j] + "\t");
}
System.out.println();
}
System.out.println("Subtraction of Arrays:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(sub[i][j] + "\t");
}
System.out.println();
}
System.out.println("Multiplication of Arrays:");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(mult[i][j] + "\t");
}
System.out.println();
}
}
}
76
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
77
OUTPUT
78
PROGRAM 17:
Write a program to accept a two dimensional array from
the user. Show the sum of the elements of each row and
each column beside the respective row and column.
INPUT:
3 2 3 2
4 3 8 4
8 6 7 6
9 4 8 2
OUTPUT:
3 2 3 2 10
4 3 8 4 19
8 6 7 6 27
9 4 8 2 23
24 15 26 14
ALGORITHM
Step 1: Start.
Step 2: Define the class ArraySum.
Step 3: Inside the main() method:
Declare necessary variables:
o m for the number of rows in the array.
o n for the number of columns in the array.
o i, j as loop counters for rows and columns.
o sum1 for storing the sum of each row.
o sum2 for storing the sum of each column.
79
Step 4: Prompt the user to input the number of rows (m) and columns (n) for the 2D array.
Step 5: Declare a 2D array a[][] of size m x n to store the elements.
Step 6: Input the elements of the 2D array:
Use nested loops to input elements into the array (a[i][j]), where i represents rows and j
represents columns.
Step 7: Print the 2D array along with the row sums:
Loop through each row and column to print the elements.
Calculate the sum of each row (sum1) by adding each element in the row.
Print the row sum (sum1) after the row elements are printed, and reset sum1 to 0 for the
next row.
Step 8: Print the column sums below the 2D array:
Loop through each column and sum the elements of that column (sum2).
After summing all the elements of a column, print the column sum (sum2) and reset
sum2 to 0 for the next column.
Step 9: End.
CODING
import java.util.*;
class ArraySum
{
public static void main()
{
Scanner sc = new Scanner(System.in);
int m, n, i, j, sum1 = 0, sum2 = 0;
// Input the dimensions of the 2D array
System.out.print("Enter the number of rows: ");
m = sc.nextInt();
System.out.print("Enter the number of columns: ");
n = sc.nextInt();
// Declare the 2D array
int a[][] = new int[m][n];
// Input the elements for the 2D array
System.out.println("Enter the elements of the array:");
80
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
a[i][j] = sc.nextInt();
}
}
// Print the 2D array with row sums
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
System.out.print(a[i][j] + "\t");
sum1 = sum1 + a[i][j];
}
System.out.print(sum1 + "\t"); // Print row sum after each row
sum1 = 0;
System.out.println();
}
// Print the column sums below the 2D array
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
sum2 = sum2 + a[j][i];
}
System.out.print(sum2 + "\t"); // Print column sum below each column
sum2 = 0;
}
}
}
81
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
82
OUTPUT
83
PROGRAM 18:
Write a program to accept the size of an array and its
elements from the user if the entered size is greater than
2 and less than 20 else display invalid input. Display the
mirror matrix.
ALGORITHM
Step 1: Start.
Step 2: Define the class Mirror.
Step 3: Inside the main() method:
Declare necessary variables:
o n for the size of the matrix (number of rows and columns).
o i, j for loop counters.
Step 4: Prompt the user to input the size of the matrix (n).
Step 5: Validate the size of the matrix:
If n <= 2 or n >= 20, display the message "Invalid Input" and terminate the program.
Step 6: If the size is valid, proceed to the next step:
Declare a 2D array a[][] of size n x n.
Step 7: Input the elements of the matrix:
Use nested loops to input the matrix elements (a[i][j]), where i represents rows and j
represents columns.
Step 8: Display the original matrix:
Use nested loops to print the matrix elements in their original form.
Step 9: Display the mirror matrix:
Loop through each row and print its elements in reverse order (i.e., reverse each row).
Step 10: End.
CODING
import java.util.*;
class Mirror
{
84
public static void main()
{
Scanner sc = new Scanner(System.in);
int n, i, j;
// Step 1: Accept the size of the array from the user
System.out.println("Enter the size of the array:");
n = sc.nextInt();
// Step 2: Validate the input size
if (n <= 2 || n >= 20)
{
System.out.println("Invalid Input");
}
else
{
// Step 3: Declare the 2D array of size n x n
int a[][] = new int[n][n];
// Step 4: Accept elements of the matrix
System.out.println("Enter the elements of the matrix:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
a[i][j] = sc.nextInt();
}
}
// Step 5: Display the original matrix
System.out.println("Original Matrix:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
System.out.print(a[i][j] + "\t");
85
}
System.out.println();
}
// Step 6: Display the mirror matrix (reverse of each row)
System.out.println("Mirror Matrix:");
for (i = 0; i < n; i++)
{
for (j = n - 1; j >= 0; j--)
{
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
86
OUTPUT
87
PROGRAM 19:
A class Adder has been defined to add any two accepted
time.
Example: Time A –6 hours 35 minutes
Time B –7 hours 45 minutes
Their sum is –14 hours 20 minutes
(Where 60 minutes = 1 hour)
88
Specify the class Adder giving details of the
constructor( ), void readtime( ), void addtime(Adder,
Adder) and void disptime( ). Define the main( )
function to create objects and call the functions
accordingly to enable the task.
ALGORITHM
Step 1: Start
Step 2: Define the class Adder.
Step 3: Define the constructor Adder()
Initialize the array a[] to store hours and minutes, setting both a[0] (hours) and a[1] (minutes)
to 0.
Step 4: Define the method readtime()
Prompt the user to enter hours and minutes.
Store the entered hours in a[0] and the entered minutes in a[1].
Step 5: Define the method addtime(Adder X, Adder Y)
Add the hours and minutes of objects X and Y.
If the sum of minutes exceeds 60, convert the excess minutes to hours.
Update the calling object's a[] with the result.
Step 6: Define the method disptime()
Print the current time stored in a[] in the format "Hours = a[0], Minutes = a[1]".
Step 7: Define the main() function
Create three objects ob1, ob2, and ob3 of the Adder class.
Call readtime() for both ob1 and ob2 to input times.
Display the times of ob1 and ob2 using disptime().
Call addtime() to add ob1 and ob2 and store the sum in ob3.
Display the sum of the times stored in ob3 using disptime().
Step 8: End
CODING
import java.util.*;
89
class Adder
{
// Data member to hold hours and minutes
int a[] = new int[2]; // a[0] for hours, a[1] for minutes
// Constructor to initialize hours and minutes to 0
Adder()
{
a[0] = 0; // hours
a[1] = 0; // minutes
}
// Method to read time from the user
void readtime()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter hours: ");
a[0] = sc.nextInt();
System.out.print("Enter minutes: ");
a[1] = sc.nextInt();
}
// Method to add the times of two Adder objects (X and Y)
void addtime(Adder X, Adder Y)
{
// Add hours and minutes separately
this.a[1] = X.a[1] + Y.a[1]; // sum of minutes
this.a[0] = X.a[0] + Y.a[0]; // sum of hours
// If minutes are 60 or more, convert into hours
if (this.a[1] >= 60)
{
this.a[0] = this.a[0] + this.a[1] / 60; // add the hours part
this.a[1] = this.a[1] % 60; // keep the remainder as minutes
}
}
90
// Method to display the time
void disptime()
{
System.out.println("Hours = " + a[0] + ", Minutes = " + a[1]);
}
// Main method inside the Adder class
public static void main()
{
// Create two objects of Adder class
Adder ob1 = new Adder();
Adder ob2 = new Adder();
// Read times for both objects
System.out.println("Enter time for the first object:");
ob1.readtime();
System.out.println("Enter time for the second object:");
ob2.readtime();
// Display the input times
System.out.println("First Time:");
ob1.disptime();
System.out.println("Second Time:");
ob2.disptime();
// Create a third object to store the sum of time1 and time2
Adder ob3 = new Adder();
// Add time1 and time2, store the result in sum
ob3.addtime(ob1, ob2);
// Display the sum of times
System.out.println("Sum of the two times:");
ob3.disptime();
}
}
91
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
OUTPUT
92
PROGRAM 20:
A super class Bank has been defined to store the details
of the customer. Define a subclass Accounts that
enables transactions for customer with the bank. The
details of the class are:
Class name: Bank
Data Members/Instance Variables:
name: Store the name of the customer
acc_no: Store the account number of the customer
p: Store the principal amount
Member Functions/Methods:
Bank(….): Parameterized constructor to assign the
values to the instance variable.
void display(): Displays the details of the customer
Class Name – Account
Data Members/Instance Variables:
amt: Store the transaction amount in decimals.
Member Functions/Methods:
Account(…): Parameterized constructor to assign the
values to the instance variables of both the classes.
void deposit(): accept the amount and update the
principal as p = p + amt
93
void withdraw(): accept the amount and update the
principal as p = p - amt
If the withdrawal amount is more than the principal
amount then display the message “insufficient balance”.
If the principal amount after the withdrawal is less than
500 then a penalty is imposed by the formula p = p -
(500 - P) / 10
void display(): Display the details of the customer.
ALGORITHM
Algorithm of class Bank:
Step 1: Start
Step 2: Declaring the class Bank
Step 3: Declare data members:
String name
long acc_no
double p
Step 4: Define the parameterized constructor Bank(String name, int acc_no, double p):
name = n2
acc_no = ac1
p = p2
Step 5: Define the display() method:
Display the name.
Display the acc_no.
Display the p.
94
Step 3: Define the subclass Account:
CODING
class Bank
{
String name;
long acc_no;
95
double p;
Bank(String n2, long ac1, double p2)//constructor to initialize varaiables.
{
name = n2;
acc_no = ac1;
p = p2;
}
void display()
{
System.out.println("Name of customer: " + name);
System.out.println("Account number: " + acc_no);
}
}
import java.util.*;
class Account extends Bank
{
Scanner sc = new Scanner(System.in);
double amt;
Account(String n1, long ac, double p1, double am)
{
super(n1, ac, p1);//passing the values to the constructor of the super class
amt = am;
}
void deposit()
{
System.out.println("Enter the amount to be deposited");
amt = sc.nextDouble();
p = p + amt;//updating the amount
}
void withdraw()
{
96
System.out.println("Enter the amount to be withdrawn");
amt = sc.nextDouble();
if(amt > p)//checking if the withdrawing amount is more than the balance in the account
{
System.out.println("Insufficient balance");
}
else
{
p = p - amt;//updating the balance
}
if(p < 500)
{
p = p - (500 - p) / 10;
}
}
void display()
{
super.display();
System.out.println("Current Balance: " + p);
}
public static void main()
{
Scanner sc = new Scanner(System.in);
String s;
long a;
double pr;
System.out.println("Enter the name of the customer");
s = sc.nextLine();
System.out.println("Enter the account number");
a = sc.nextLong();
System.out.println("Enter the principal amount");
pr=sc.nextDouble();//calling the function
97
Account ob = new Account(s, a, pr, 0.0);//passing the values to the constructor.
ob.deposit();
ob.withdraw();
ob.display();
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. name String More than 2 global Stores the name of the customer.
bytes
2. acc_no long 8 bytes global Stores the account number of the
customer.
5. s String More than 2 local Accepts the name from the user.
bytes
6. a long 8 bytes local Accepts the account number from
the user.
98
OUTPUT
99
PROGRAM 21:
A super class Product has been defined to store the
details of a product sold by a wholesaler to a retailer.
Define a subclass Sales to compute the total amount
paid by the retailer with or without fine along with
service tax.
Some of the members of both the classes are given
below:
Class Name: Product
Data Members/Instance Variables:
name: Stores the name of product.
code: Integer to store product code.
amt: Stores the total sale amount of product.
Member Functions/Methods:
Product(String n, int c, double p): To assign the data
members.
void show(): Display the details of the product.
Class Name: Sales
Data Members/Instance Variables:
day: Store the number of days taken to pay the sale
amount.
tax: Store the service tax in decimals.
100
totamt: Stores the total amount in decimals.
Member Functions/Methods:
Sales(): Parameterised constructor to assign the values
of data members to both the classes.
void compute(): Calculate the service tax 12.4% of the
actual sale amount. Calculate the fine 2.5% of the actual
sale amount only if the amount paid by the retailer to
the whole saler exists 30 days. Calculate the total
amount paid by the retailer. (Actual sale amount + tax +
fine).
void show(): Display the data members of super class
and the total amount.
ALGORITHM
Algorithm of class Product:
Step 1: Start
Step 2: Declaring the class Product
Step 3: Declare data members:
101
Algorithm of class Sales:
Step 1: Start
Step 2: Declaring derived class Sales from base class Product using extend keyword.
Define a parameterized constructor Sales(String n1, int c1, double p1, int d, double tax1,
double totamt1):
o Assign day = d.
Initialize fine = 0.
Calculate the tax using the formula tax = (12.4 / 100) * amt.
o Calculate the fine using the formula fine = (2.5 / 100) * amt.
102
o The product code (code1).
o The number of days taken to pay tax (n).
o The sale amount of the product (a).
Create an object ob of class Sales and pass the inputs to its constructor.
Call the compute() method to calculate the tax, fine, and total amount.
Call the show() method to display the details of the product and calculated values.
Step 3: End
CODING
class Product
{
String name;
int code;
double amt;
Product(String n, int c, double p)
{
name = n;
code = c;
amt = p;
}
void show()
{
System.out.println("Name of product: " + name);
System.out.println("Product code: " + code);
}
}
import java.util.*;
class Sales extends Product
{
int day;
double tax, totamt;
103
Sales(String n1, int c1, double p1, int d, double tax1, double totamt1)
{
super(n1, c1, p1);//passing the values to the constructor of th super class
day = d;
tax = tax1;
totamt = totamt1;
}
void compute()
{
double fine = 0;
tax=(12.4 / 100) * amt;//calculating the tax
if(day > 30)//checking if the number of days is above limit
{
fine = (2.5 / 100) * amt;//calculating the fine
}
totamt = amt + tax + fine;//calculating the total amount
}
void show()
{
super.show();
System.out.println("No.of days taken to pay tax: " + day);
System.out.println("Tax: " + tax);
System.out.println("Total Amount: " + totamt);
}
public static void main()
{
Scanner sc = new Scanner(System.in);
String s;
int n, code1;
double a;
System.out.println("Enter name of product");
s = sc.nextLine();
104
System.out.println("Enter the product code");
code1 = sc.nextInt();
System.out.println("Enter the number of days");
n = sc.nextInt();
System.out.println("Enter the sale amount of product");
a = sc.nextDouble();
Sales ob = new Sales(s, code1, a, n, 0.0, 0.0);//passing the values to the constructor
ob.compute();//calling the function
ob.show();
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. name String More than 2 global Stores the name of the product.
bytes
105
OUTPUT
106
PROGRAM 22:
A super class Stock has been defined to store the details
of the stock of a retailer. 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/Methods:
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
107
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()]. The
main function and algorithm need not be written.
ALGORITHM
Algorithm of class Stock:
Step 1: Start
Step 2: Declaring the class Stock
Step 3: Declare the data members:
item: To store the name of the item (String).
qt: To store the quantity of the item (int).
rate: To store the unit price of the item (double).
amt: To store the net value of the item (double).
Step 4: Define the parameterized constructor Stock(String s, int q, double r, double a):
Assign item = s.
Assign qt = q.
Assign rate = r.
Assign amt = a.
108
Step 5: Define the method display():
Display the name of the item (item).
Display the quantity of the item (qt).
Display the unit price of the item (rate).
Display the net value of the item in stock (qt * rate).
Define the parameterized constructor Purchase(String i, int q1, double r1, double a1, int
p1, double pr):
Display:
109
Step 2 Define the main() method:
Create an object ob of the Purchase class and pass the inputs to its constructor.
Call the update() method to update the quantity, rate, and amount.
Call the display() method to display the updated details of the item.
Step 3: End
CODING
class Stock
{
String item;
int qt;
double rate,amt;
Stock(String s, int q, double r, double a)//constructor
{
item = s;
qt = q;
rate = r;
amt = a;
}
//function for displaying the essential details
void display()
{
System.out.println("Name of item: " + item);
System.out.println("Quantity of item: " + qt);
System.out.println("Unit price of item: " + rate);
110
System.out.println("Net value of item in stock: " + (qt * rate));
}
}
import java.util.*;
class Purchase extends Stock
{
int pqty;
double prate;
Purchase(String i, int q1, double r1, double a1, int p1, double pr)
{
super(i, q1, r1, a1);//passing the values to the constructor of the super class
pqty = p1;
prate = pr;
}
void update()
{
pqty = qt + pqty;//updating the quantity
if(rate != prate)
{
amt = pqty * prate;//updating the amount
}
else
{
amt = pqty * rate;
}
}
void display()
{
super.display();//using the display() function of the super class
System.out.println("After updation:");
System.out.println("Updated quantity: "+ pqty);
111
System.out.println("Updated rate: " + prate);
System.out.println("Updated amount: " + amt);
}
public static void main()
{
Scanner sc = new Scanner(System.in);
String i1;
int q2, p2;
double r2, pr1;
System.out.println("Enter name of item:");
i1 = sc.nextLine();
System.out.println("Enter the initial quantity:");
q2 = sc.nextInt();
System.out.println("Enter the unit price of item:");
r2 = sc.nextDouble();
System.out.println("Enter the purchased quantity:");
p2 = sc.nextInt();
System.out.println("Enter the purchase rate:");
pr1 = sc.nextDouble();
Purchase ob = new Purchase(i1, q2, r2, 0.0, p2, pr1);//passing the values to the constructor
ob.update();
ob.display();
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
1. item String More than 2 global Stores the name of the product.
bytes
112
3. amt double 8 bytes global Stores the total price of the
product.
4. rate double 8 bytes global Stores the price of each item.
OUTPUT
113
PROGRAM 23:
A line on a plane can be represented by coordinates of
the two-end points p1 and p2 as p1(x1, y1) and p2(x2,
y2).
A super class Plane is defined to represent a line and a
subclass Circle to find the length of the radius and the
area of circle by using the required data members of
superclass.
Some of the members of the class are given below:
Class Name: Plane
Data Members/Instance Variables:
x1: to store the x-coordinate of the first endpoint .
y1: to store the y-coordinate of the first endpoint.
Member Functions/Methods:
Plane(int nx, int ny): Parameterized constructor to
assign the data members x1 = nx and y1 = ny.
void show(): To display the coordinates.
Class Name: Circle
Data Members/Instance Variables:
x2: to store the x-coordinate of the second endpoint.
y2: to store the y-coordinate of the second endpoint.
radius: Double variable to store the radius of the circle
114
area: Double variable to store the area of the circle.
Member Functions/Members:
Circle(…): Parameterized constructor to assign the data
members of both the classes.
void findRadius(): to calculate the length of radius
using the formula:
√(𝑥2 − 𝑥1 )2 + (𝑦2 − 𝑦1 )2
2
Assuming that x1, x2, y1 and y2 are the coordinates of
the two ends of the diameter of a circle.
void findArea(): to find the area of circle using the
formula: 𝜋𝑟2
The value of pi(𝜋) is 22/7 or 3.14.
void show(): To display both the coordinates along with
the length of the radius and the area of the circle.
Specify the class Plane by giving the details of the
constructor and void Show(). Using the concept of
inheritance, specify the class Circle giving details of the
constructor, void findRadius(), voidfindArea() and void
show().
ALGORITHM
Algorithm of class Plane:
Step 1: Start
Step 2: Declaring the class Plane
115
Step 3: Declare the data members:
x1: To store the x-coordinate of the first endpoint (int).
y1: To store the y-coordinate of the first endpoint (int).
Step 4: Define the parameterized constructor Plane(int nx, int ny):
Assign x1 = nx.
Assign y1 = ny.
Step 5: Define the method show():
Display the coordinates of the first endpoint (x1, y1).
Define the parameterized constructor Circle(int nx1, int ny1, int nx2, int ny2):
Assign x2 = nx2.
Assign y2 = ny2.
Step 4: Define the method findRadius():
116
o The area of the circle (area).
Create an object ob of the Circle class and pass the inputs to its constructor.
CODING
class Plane
{
int x1, y1;
Plane(int nx, int ny)//constructor
{
x1 = nx;
y1 = ny;
}
void show()
{
System.out.println("Coordinates of the first end points:\t"+x1+"\t"+y1);
}
}
117
import java.util.*;
class Circle extends Plane
{
int x2, y2;
double radius;
double area;
Circle(int nx1, int ny1, int nx2, int ny2)
{
super(nx1, ny1);
x2 = nx2;
y2 = ny2;
}
void findRadius()//function for calculating the radius
{
radius = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)) / 2.0;
}
void findArea()//function for calculating the area
{
area = 3.14 * radius * radius;
}
void show()//function for displaying the details
{
super.show();//using the function of the super class
System.out.println("Coordinates of the second end points:\t" + x2 + "\t" + y2);
System.out.println("Radius of the circle:\t" + radius);
System.out.println("Area of the circle:\t" + area);
}
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first coordinate:");
int x = sc.nextInt();
118
int y = sc.nextInt();
System.out.println("Enter the second coordinate:");
int a = sc.nextInt();
int b = sc.nextInt();
Circle ob = new Circle(x, y, a, b);//creating an object
//calling the functions
ob.findRadius();
ob.findArea();
ob.show();
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
119
OUTPUT
120
PROGRAM 24:
Write a program to create a stack and display the stack
after popping out the elements. Use different functions
for the purpose.
ALGORITHM
Step 1: Start
121
o Decrement sp.
CODING
import java.util.*;
class stack
{
int s[];
int sp, n, i;
stack(int nn)
{
n = nn;
s = new int[n];
122
sp = -1;
}
void pushdata(int item)//data for inserting elements.
{
if(sp == (n - 1))//checking if the stack is filled
{
System.out.println("Stack Overflow");
}
else
{
sp++;
s[sp] = item;
}
}
void popdata()
{
int v;
if(sp == -1)//checking if stack is empty
System.out.println("Stack Underflow");
else
{
v = s[sp];//storing the deleted item
System.out.println("The popped out item is " + v);
sp --;
}
}
void display()
{
if(sp == -1)//checking if the stack is empty
{
System.out.println("Stack Underflow");
}
123
else
{
for(i = sp; i >= 0; i --)
{
System.out.println(s[i]);
}
}
}
public static void main()
{
Scanner sc = new Scanner(System.in);
int n1, t, j;
System.out.println("Enter the total number of items:");
n1 = sc.nextInt();
stack ob = new stack(n1);//creating an object
for(j = 0; j < n1; j ++)
{
System.out.println("Enter item number " + (j + 1) + ":");
t = sc.nextInt();
ob.pushdata(t);//calling the function
}
System.out.println("The stack items are:");
ob.display();
for(j = 0; j < 5; j ++)
{
ob.popdata();
System.out.println("The elements after popping out are:");
ob.display();
}
}
}
124
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
125
OUTPUT
126
PROGRAM 25:
Write a program to create a circular queue and display it
after deleting an element.
ALGORITHM
Step 1: Start
127
o Set front and rear to -1.
Otherwise:
o Update front using ((front + 1) % size).
o Return item.
Prompt the user for the size of the queue and create an object of CQueue.
CODING
import java.util.*;
class CQueue
{
int cq[];
int front, rear, size;
// Constructor to initialize the queue
CQueue(int size)
{
this.size = size;
cq = new int[size];
front = -1; // Indicates the queue is empty
rear = -1; // Indicates the queue is empty
}
128
// Function to insert an element into the queue
void insert(int item) {
if ((rear + 1) % size == front)
{ // Check if the queue is full
System.out.println("Queue Overflow");
}
else
{
if (front == -1)
{ // If inserting the first element
front = 0;
}
rear = (rear + 1) % size; // Circular increment
cq[rear] = item;
}
}
// Function to delete an element from the queue
int delete()
{
if (front == -1)
{ // Check if the queue is empty
System.out.println("Queue Underflow");
return -1;
}
else
{
int item = cq[front];
if (front == rear)
{ // If there was only one element
front = -1;
rear = -1;
}
129
else
{
front = (front + 1) % size; // Circular increment
}
return item;
}
}
// Function to display the queue
void display()
{
if (front == -1)
{ // Check if the queue is empty
System.out.println("Queue is Empty");
}
else
{
System.out.println("Queue elements are:");
int i = front;
while (true)
{
System.out.print(cq[i] + " ");
if (i == rear)
{ // Reached the end of the queue
break;
}
i = (i + 1) % size; // Circular increment
}
System.out.println();
}
}
// Main function to test the Circular Queue
public static void main()
130
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the circular queue: ");
int n = sc.nextInt();
CQueue cq = new CQueue(n);
// Insert elements into the queue
System.out.print("Enter the number of elements to insert: ");
int m = sc.nextInt();
System.out.print("Enter queue elements:");
for (int i = 0; i < m; i++)
{
int item = sc.nextInt();
cq.insert(item);
}
// Display the queue
cq.display();
// Delete an element
System.out.println("Revoming an element...");
int removedItem = cq.delete();
// Display the queue after deletion
cq.display();
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
131
3. rear int 4 bytes global Used as the rear pointer in the
queue.
4. size int 4 bytes global Stores the size of the queue.
OUTPUT
132
PROGRAM 26:
Write a program to create a link list and using switch
case perform one of the
following actions based on the user’s choice :
(i) Counting the number of nodes
(ii) Deleting a node
(iii) Inserting a node in the beginning
(iv) Inserting a node at the end
(v) Inserting a node in the middle
(vi) Display the link list
ALGORITHM
Step 1: Start.
Step 2: Define a class Node with the following:
Step 2.1: Integer variable data to store the node data.
Step 2.2: Object variables link, start, and ptr of type Node to manage links between nodes and
operations on the list.
Step 2.3: A constructor to initialise data to 0 and links to null.
Step 3: Define the create() method to create a linked list.
Step 3.1: Accept the number of nodes (n) and data for each node.
Step 3.2: Set start and ptr to the first node, and link each subsequent node iteratively.
Step 4: Define the countnodes() method to count the nodes.
Step 4.1: Traverse the list using ptr, incrementing a counter until the end of the list is reached.
Step 4.2: Print the count.
Step 5: Define the display() method to print the linked list.
Step 5.1: Traverse the list using ptr, printing the data of each node.
Step 6: Define the insertbeg() method to insert a node at the beginning.
133
Step 6.1: Create a new node, assign data to it, and set its link to start.
Step 6.2: Update start to the new node.
Step 7: Define the insertmiddle() method to insert a node at a specified position.
Step 7.1: Accept the position and data for the new node.
Step 7.2: Traverse the list to the specified position using ptr.
Step 7.3: Insert the new node by updating the links.
Step 8: Define the insertend() method to insert a node at the end.
Step 8.1: Create a new node and traverse the list using ptr to the last node.
Step 8.2: Update the last node's link to the new node.
Step 9: Define the delete() method to delete a node at a specified position.
Step 9.1: Accept the position of the node to delete.
Step 9.2: Traverse the list to the node before the specified position using ptr.
Step 9.3: Update the previous node's link to skip the node being deleted.
Step 10: Define the Search() method to find a node by its value.
Step 10.1: Accept the value to search for.
Step 10.2: Traverse the list using ptr, comparing the node's data with the given value.
Step 10.3: Print whether the search was successful or not.
Step 11: Define the main() method to provide a menu-driven interface.
Step 11.1: Display menu options for creating, displaying, counting, inserting, deleting, and
searching nodes.
Step 11.2: Accept the user's choice and call the corresponding method using a switch
statement.
Step 11.3: For each case, perform the required operations and display the resulting list where
applicable.
Step 12: End.
CODING
import java.util.*;
class Node
{
int data;
Node link,start,ptr;
Node()
134
{
data = 0;
link = null;
start = null;
ptr = null;
}
void create()//for creating the link list
{
int n, i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of nodes to be created:");
n=sc.nextInt();
System.out.println("Enter the first data:");
this.data=sc.nextInt();
ptr = this;
start = this;
Node temp;
for(i = 1; i < n; i ++)
{
temp = new Node();
System.out.println("Enter next data:");
temp.data = sc.nextInt();
temp.link = null;
ptr.link = temp;
ptr = ptr.link;
temp = null;//emptying the temporal node
}
}
void countnodes()
{
ptr = start;
int c = 0;
135
while(ptr != null)
{
c ++;//counting the number of nodes
ptr = ptr.link;
}
System.out.println("Number of nodes = " + c);
}
void display()
{
ptr = start;
while(ptr != null)//loop will continue till the end of the loop
{
System.out.println(ptr.data);
ptr = ptr.link;
}
}
void insertbeg()
{
Scanner sc = new Scanner(System.in);
Node temp = new Node();
System.out.println("Enter the data to be inserted in the beginning:");
temp.data = sc.nextInt();
temp.link = null;
temp.link = start;
start = temp;//storing the value in temp as the first node
temp=null;
}
void insertmiddle()
{
Scanner sc = new Scanner(System.in);
Node temp = new Node();
System.out.println("Enter the data to be entered in the middle:");
136
temp.data = sc.nextInt();
System.out.println("Enter the position number:");
int c = sc.nextInt();
int n = 1;
ptr = start;
while(n < c)//loop will continue till the position entered by the user
{
ptr = ptr.link;
n ++;
}
temp.link = ptr.link;
ptr.link = temp;
}
void insertend()
{
Scanner sc = new Scanner(System.in);
Node temp = new Node();
System.out.println("Enter the number to be entered at the end:");
temp.data = sc.nextInt();
temp.link = null;
ptr = start;
while(ptr.link != null)
{
ptr = ptr.link;
}
ptr.link = temp;
temp = null;
}
void delete()
{
Scanner sc = new Scanner(System.in);
Node ptr = start;
137
Node ptr1 = ptr;
int c = 1;
System.out.println("Enter the node number to be deleted:");
int n = sc.nextInt();
while(c < n)
{
ptr1 = ptr;
ptr = ptr.link;
c ++;
}
if(c == 1)
{
start = ptr.link;
ptr1 = ptr=null;
}
else
{
ptr1.link = ptr.link;
ptr.link = null;
ptr = ptr1 = null;
}
}
void Search()
{
Scanner sc=new Scanner(System.in);
Node ptr = start;
System.out.println("Enter the number to be searched:");
int n = sc.nextInt();
int f = 0;
while(ptr != null)
{
if(ptr.data == n)
138
{
f = 1;//setting the flag value which indicates the value has been found
break;
}
else
{
ptr = ptr.link;
}
}
if(f == 1)
{
System.out.println("Search successful");
}
if(f != 1)
{
System.out.println("Search unsuccessful");
}
}
public static void main()
{
int n, choice;
Scanner sc = new Scanner(System.in);
Node ob1=new Node();
System.out.println("Enter 1 for creating link list");
System.out.println("Enter 2 for counting the number of nodes");
System.out.println("Enter 3 for inserting a node at the beginning");
System.out.println("Enter 4 for inserting a node at the middle");
System.out.println("Enter 5 for inserting a node at the last");
System.out.println("Enter 6 for deleting a node");
System.out.println("Enter 7 for searching an element");
System.out.println("Enter your choice:");
choice=sc.nextInt();
139
switch(choice)
{
case 1:
ob1.create();
ob1.display();
break;
case 2:
ob1.create();
ob1.countnodes();
break;
case 3:
ob1.create();
ob1.display();
ob1.insertbeg();
System.out.println("List after inserting in beginning:");
ob1.display();
break;
case 4:
ob1.create();
ob1.insertmiddle();
System.out.println("List after inserting in middle:");
ob1.display();
break;
case 5:
ob1.create();
ob1.display();
ob1.insertend();
System.out.println("List after inserting in end:");
140
ob1.display();
break;
case 6:
ob1.create();
ob1.display();
ob1.delete();
System.out.println("List after deleting in end:");
ob1.display();
break;
case 7:
ob1.create();
ob1.Search();
break;
default:
System.out.println("Wrong choice");
}
}
}
VARIABLE DESCRIPTION
SL VARIABLE DATA STORAGE SCOPE DESCRIPTION
NO. NAME TYPE
141
5. i int 4 bytes global Used to control the loops.
OUTPUT
142
CONCLUSION
143
BIBLIOGRAPHY
Books:-
SL Writer’s Name Title Publisher
NO.
1. Vijay Kumar Understanding APC
Pandey ISC Computer
Science
2. Sumita Arora ISC Computer Dhanpat Rai
Science with & Co.
JAVA
3. S.Gaur and M. Guided DN
Vijay Bhaskar Computer Publication
Science
References:-
1. www.wikipedia.com
2. www.blueJ.com
3. www.compxpert.co
4. www.quora.com
144