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

Sample Computer Practical File 12

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

Sample Computer Practical File 12

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

QUESTION 1

Write a program to input a positive natural number N and print the possible consecutive
number combination which when added gives N. Example N=27. Combinations are:
2+3+4+5+6+7
8+9+10
13+14

ALGORITHM
Algorithm for accept() function
1. Start
2. Create a scanner object.
3. Take input from the user and store it in n.
4. End
Algorithm for generate() function
1. Start
2. Set i=0,j=1.
3. Repeat steps 3.1 to 3.4 while j<(n/2)+1
3.1. Set d=0
3.2. Repeat steps 3.2.1 to 3.2.6 from i to (n/2)+1 increasing step by 1
3.2.1. Set d=d+i
3.2.2. If d>n then increment j by 1
3.2.3. If d==n repeat steps 3.2.3.1. to 3.2.3.2 from k to i increasing step by 1
3.2.3.1. Print k
3.2.3.2. End of loop
3.2.4. Print i
3.2.5. Set j=i
3.2.6. End of loop
3.3. End of loop
4. End
Algorithm for main() function
1. Start
2. Create a new object
3. Call the functions accept() and generate()
4. End

1 | Page
PROGRAM CODE

import java.util.*;
class combination
{
int n;
//Default constructor
public combination()
{
n=0;
}//End of method
//Parametrized constructor
public combination(int m)
{
n=m;
}//End of method
//Method to accept the number
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("N=");
n=sc.nextInt();
}//End of method
//Method to generate the combination of numbers
public void generate()
{
int i=0,j=1;
while(j<(n/2+1))
{
int d=0;
for(i=j;i<=(n/2+1);i++)
{
d+=i;
if(d>n)
{
j++;
break;
}
else
if(d==n)
{
//loop to print the combination of numbers
for(int k=j;k<i;k++)
{
2 | Page
System.out.print(k+"+");
}
System.out.print(i);
j=i;
System.out.println();
break;
}
}
}
}//End of method
//Main method to initiate the task
public static void main()
{
combination c1=new combination();
c1.accept();
c1.generate();
}//End of method
}//End of class

3 | Page
OUTPUT
OUTPUT 1
N=
27
2+3+4+5+6+7
8+9+10
13+14

OUTPUT 2
N=
36
1+2+3+4+5+6+7+8
11+12+13

4 | Page
QUESTION 2
A Smith number is a composite number the sum of whose digit is the sum of digits of its
prime factors obtained as a result of prime factorization(excluding 1). First few Smith
numbers are 4,22,27,58,85,94,121…. Write a program to input a number and check it is a
Smith Number or not. Example 666: Prime factors are 2,3,3 and 37. Sum of digits are
(6+6+6)=18. Sum of the digits of the factor (2+3+3+(3+7))=18

ALGORITHM
Algorithm for accept() function
1.Start
2. Create a scanner object.
3.Take input from the user and store it in n.
4. End
Algorithm for sumDigits(int x) function
1. Start
2. Set s=0
3. Repeat steps 3.1 to 3.3 while x>0
3.1. Set s=s+x%10
3.2. x=x/10
3.3. end of loop
4. Return s
5. End
Algorithm for prime(int c) function
1. Start
2. Check if c=2 then return true
3. Repeat steps 3.1 to 3.2 from 2 to c increasing step by 1
3.1. Check if c%i=0 then return false
3.2. End of loop
4. Return true
5. End
Algorithm for primeFactors()
1. Start
2. Set d=0,n1=n
3. Repeat steps 3.1 to 3.5 from 2 to n
3.1. Call the function prime(i) to check prime no. and check if n1%i=0
3.2. Set n1=n1/i
3.3. Call the function sumDigits(i) and add it to d;

5 | Page
3.4. Increment by i
3.5. End of loop
4. Return d
5. End
Algorithm for check() function
1. Start
2. Call the function sumDigits(n) and check if it is equal to primeFactors()
3. Print “It is a Smith number” if both are equal
4. Print “It is not a Smith number” if both are not equal
5. End

PROGRAM CODE
import java.util.*;

6 | Page
class smith
{
int n;
//default constructor to initialize the values
public smith()
{
n=0;
}//end of method
//parametrized constructor to initialize the values
public smith(int m)
{
n=m;
}//end of method
//method to accept the number
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("N=");
n=sc.nextInt();
}//end of method
//method to find the sum of digits
public int sumDigits(int x)
{
int s=0;
while(x>0)//loop to find sum of digits
{
s+=x%10;
x/=10;
}//end of loop
return s;
}//end of method
//method to check whether it is a prime no.
public boolean prime(int c)
{
if(c==2)
return true;
for(int i=2;i<c;i++)
{
if(c%i==0)
return false;
}
return true;
}//end of method
//method to find the prime factors

7 | Page
public int primeFactors()
{
int d=0;
int n1=n;
for(int i=2;i<=n;)//loop to find sum of prime factors
{
if(prime(i)==true&&(n1%i==0))
{
n1=n1/i;
d+=sumDigits(i);
}
else
{
i++;
}
}//end of loop
return d;
}//end of method
//method to check whether the sum of digits is equal to prime factors
public void check()
{
if(sumDigits(n)==primeFactors())
{
System.out.println("It is a Smith number");
}
else
{
System.out.println("It is not a Smith number");
}
}//end of method
//main method to initiate the task
public static void main()
{
smith s1=new smith();
s1.accept();
s1.check();
}//end of method
} //end of class

8 | Page
OUTPUT

OUTPUT 1:
N=
666
It is a Smith number

OUTPUT 2:
N=
635
It is not a Smith number

9 | Page
QUESTION 3
Write a program to input a natural number less than 1000 and print in words. Example 372
output: THREE HUNDRED AND SEVENTY TWO

ALGORITHM
Algorithm for accept() function
1. Start
2. Create a scanner object.
3. Take input from the user and store it in n.
4. Check if n>1000 or n<1 then print ”Invalid input”
5. End
Algorithm for print() function
6. Start
7. If n<100 follow steps 2.1 to 2.3
2.1. Call the function inWords(n/10) and print the value
2.2. Print “TY”
2.3. Call the function inWords(n%10) and print the value
8. If n>100 follow steps 3.1 to 3.3
3.1. Call the function inWords(n/100) and print the value
3.2. Print “HUNDRED”
3.3. Call the function inWords((n/10)%10) and print the value
3.4. Print “TY”
3.5. Call the function inWords(n%10) and print the value
9. End
Algorithm for inWords() function
1. Start
2. Set s=””
3. Check c and store the word form of the digit in s
4. Return s
5. End
Algorithm for main()
1. Start
2. Create a object
3. Call the function accept() and print()
4. End
PROGRAM CODE
import java.io.*;
10 | Page
public class ISC2011Q1
{
//Declaring Instance variables
int n;
//Method to take input
void inputNumber() throws IOException
{
BufferedReader inp=new BufferedReader(new InputStreamReader(System.in));
System.out.println("INPUT");
n=Integer.parseInt(inp.readLine());
}
//Method to Extract digits , call other methods and display output
public void extract()
{
String str="",str1="",str2="";
int hund=0,tens=0,units=0,i=0;
if(n<1 || n>999)
System.out.println("OUT OF RANGE");
else
{
while(n!=0)
{
if(i==0)
units=n%10;
else if(i==1)
tens=n%10;
else if(i==2)
hund=n%10;
i++;
n=n/10;
}
if(hund>0)
str=word1(hund)+ " HUNDRED ";
if(tens>1)
str1= word2(tens);
if(tens==1)
str2= word3(units);
else
str2=word1(units);
if((!str.equals(""))&&(!str1.equals("") || !str2.equals("")))
str=str+ "AND ";
if(!str1.equals(""))
str=str+ str1+ " ";
if(!str2.equals(""))

11 | Page
str=str+ str2;
System.out.println("OUTPUT:\t"+str);
}//EndElse
}
//Method to convert digits 0-9
String word1(int x)
{
String s="";
switch(x)
{
case 1:
s="ONE";
break;
case 2:
s="TWO";
break;
case 3:
s="THREE";
break;
case 4:
s="FOUR";
break;
case 5:
s="FIVE";
break;
case 6:
s="SIX";
break;
case 7:
s="SEVEN";
break;
case 8:
s="EIGHT";
break;
case 9:
s="NINE";
break;
}
return s;
}
//Method to convert numbers 20, 30,40,…..90
String word2(int x)
{
String s="";

12 | Page
switch(x)
{
case 2:
s="TWENTY";
break;
case 3:
s="THIRTY";
break;
case 4:
s="FOURTY";
break;
case 5:
s="FIFTY";
break;
case 6:
s="SIXTY";
break;
case 7:
s="SEVENTY";
break;
case 8:
s="EIGHTY";
break;
case 9:
s="NINETY";
break;
}
return s;
}
//Method to convert numbers 10 – 19
String word3(int x)
{
String s="";
switch(x)
{
case 0:
s="TEN";
break;
case 1:
s="ELEVEN";
break;
case 2:
s="TWELVE";
break;

13 | Page
case 3:
s="THIRTEEN";
break;
case 4:
s="FOURTEEN";
break;
case 5:
s="FIFTEEN";
break;
case 6:
s="SIXTEEN";
break;
case 7:
s="SEVENTEEN";
break;
case 8:
s="EIGHTEN";
break;
case 9:
s="NINETEEN";
break;
}
return s;
}
// Main method to call other methods
public static void main(String args[]) throws IOException
{
ISC2011Q1 obj=new ISC2011Q1();
obj.inputNumber();
obj.extract();
}

14 | Page
OUTPUT

OUTPUT 1:
Enter a number less than 1000
485
FOUR HUNDRED EIGHTTY FIVE

OUTPUT 2:
Enter a number less than 1000
9874
Invalid input

QUESTION 4
Write a program to accept a day number between 1 and 366, year(4 digits) from user to
display the corresponding date. Also display the future date corresponding to N days after
generated date. Input: Day number 233 year: 2008 Day after: 17
Output 20th August 2008. Date after 17 days: 6th September 2008

ALGORITHM
Algorithm for accept() function
1. Start
2. Create a scanner object
3. Input a valid day no.,year, future date store it in respective variables
15 | Page
4. End
Algorithm for checkLeap() function
1. Start
2. If year%400=0 then return true
3. If year%4=0 and year%100!=0 then return true
4. End
Algorithm for generate() function
1. Start
2. Set i=0
3. Initialize an array d with the days of month
4. Check if the year is a leap year then set d[1]=29
5. Repeat steps 5.1 to 5.2 while day>d[i] increasing step by 1
5.1. Set day= day-d[i]
5.2. End of loop
6. Print the date
7. Set day=day+n
8. Repeat steps 8.1 to 8.4 while day>d[i]
8.1. If i=11 follow steps 8.1.1 to 8.1.3
8.1.1. Set i=0
8.1.2. Set year=year+1
8.1.3. Check if the year is a leap year then set d[1]=29
8.2. Set day=day-d[i]
8.3. Increment i by 1
8.4. End of loop
9. Print the generated date
10. End

Algorithm for word() function


1. Start
2. Set t=day%10
3. If day=11,day=12,day=13 then return day+”th”
4. Else return the corresponding suffix for each date
5. End
Algorithm for month(int j) function
1. Start
2. Initialize a array mth[] with the names of the month
3. Return the value of jth index of the array mth[]
4. End
Algorithm main() function

16 | Page
1. Start
2. Create a object
3. Call the functions accept() and generate()
4. End

PROGRAM CODE
import java.util.*;
public class Find_Date_P
{
static int year;
static int n;
static int af;
public static int checkLY(int y) // function to check Leap Year

17 | Page
{
if( (y%4==0 && y%100!=0) || y%400==0 )
return 1;
else
return 0;
} // end of checkLY()
public static int checkDayNum(int y, int dyn)
{
// function to check day number of a year
if(checkLY(y)==1 && dyn>=1 && dyn<=366)
return 1;
else if(checkLY(y)==0 && dyn>=1 && dyn<=365)
return 1;
else
return 0;
} // end of checkDayNum()
public static String suffix(int x)
{
// function to return suffix of the days(dd) [ e.g. 21st , 30th, etc.]
String str="";
if( x==1 || x==21 || x==31)
str="st";
else if( x==2 || x==22)
str="nd";
else if( x==3 || x==23)
str="rd";
else
str="th";
return str;
} // end of suffix()
18 | Page
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter day number(1-366): ");
n=sc.nextInt();
System.out.print("\nEnter a year (yyyy): ");
year=sc.nextInt();
if(year>=1000 && year<=9999 && checkDayNum(year,n)==1)
{
System.out.print("Enter day number after the initial one : ");
af=sc.nextInt();
int days1[]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days2[]={31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// given above are the two arrays that stores days of each month

String

months[]={"","January","February","March","April","May","June","July","August","Septemb
er","October","November","December"};
// given above is the array that stores month names
int i=0, j=0;
int next=n+af; // stores the sum of initial day number and number ofdays after the former
if( af<=0 || next>731 || ( next>730 && checkLY(year+1)==0 &&
checkLY(year)==0 ) )
{
System.out.println("Limit exceeds.");
main();
}
else
{

19 | Page
if(checkLY(year)==1)
{
while(n>days2[i])
n=n-days2[i++]; // stores the day(dd) of the given day number
System.out.print("Date is : "+ n + suffix(n) + " "+ months[i+1]+","+year);
System.out.print("\nDate after "+af+" day(s) is : ");
if(next>366)
{
year=year+1;
next=next-366;
while(next>days1[j])
next=next-days1[j++]; // stores the future day(dd)
System.out.print( next + suffix(next) + " "+ months[j+1]+" "+year); // displays the future
date
}
else
{
while(next>days2[j])
next=next-days2[j++]; // stores the future day(dd)
System.out.print( next + suffix(next) + " "+ months[j+1]+","+year); // displays the future
date
}
}
else if(checkLY(year)==0)
{
while(n>days1[i])
n=n-days1[i++]; // stores the day(dd) of the given day number
System.out.print("Date is : "+ n + suffix(n) + " "+ months[i+1]+","+year);
System.out.print("\nDate after "+af+" day(s) is : ");
if(next>365)

20 | Page
{
year=year+1;
next=next-365;
if(checkLY(year)==1)
{
while(next>days2[j])
next=next-days2[j++]; // stores the future day(dd)
System.out.print( next + suffix(next) + " "+ months[j+1]+","+year); // displays the future
date
}
else{
while(next>days1[j])
next=next-days1[j++]; // stores the future day(dd)
System.out.print( next + suffix(next) + " "+ months[j+1]+","+year); // displays the future
date
}
}
else{
while(next>days1[j])
next=next-days1[j++]; // stores the future day(dd)
System.out.print( next + suffix(next) + " "+ months[j+1]+" "+year); // displays the future
date
}
}
System.out.println();
}
}
else
{
System.out.println("Invalid input");
main();
21 | Page
}
} // end of main()

} // end of class

OUTPUT
OUTPUT 1:
Enter a valid day
233
Enter a valid year
2008
Enter a future day
17
20th AUGUST 2008
6th SEPTEMBER 2008

OUTPUT 2:
Enter a valid day
256
Enter a valid year
2019
Enter a future day
14
13th SEPTEMBER 2019
27th SEPTEMBER 2019

22 | Page
QUESTION 5
Write a program to accept a date in string format dd/mm/yyyy and accept the name of the
day on 1st January of the corresponding year. Find the day for the given date. Example:
Date: 5/7/2019 Day on 1st January 2019: Tuesday Day on 5/7/2002: Friday

ALGORITHM
Algorithm for accept() function
1. Start
2. Create a scanner object
3. Input the date and store it in d
4. Input the first day of the year in n
5. End
Algorithm for checkLeap() function
1. Start
2. Check if year%400=0 then return true
3. Check if year%4=0 and year%100!=0 then return true
4. Else return false
5. End
Algorithm for generate() function
1. Start
2. Extract the date and store it in dt
3. Extract the month and store it in mt
4. Extract the year and store it in yr
5. Set dd=0
6. Declare an array of months with the no. of days in a month
7. Check if year is leap then set February month as 29 days
8. Repeat steps 8.1 to 8.2 from 0 to mt-2 increasing step by 1
8.1. Set dd=mth[i]
8.2. End of loop
9. Set dd=dd+dt
10. Set h= dd%7
11. Print the day of the week by calling the week() function
12. End

23 | Page
Algorithm for week() function
1. Start
2. Declare a string array w with the days of the week
3. Set i=0,str=””
4. Repeat steps 4.1. to 4.2 from 0 to 6 increasing step by 1
4.1. Check if n=w[i] then break
4.2. End of loop
5. Check if t=0 and i=0 then set str=w[6] else set str= w[i-1]
6. Else repeat steps 6.1 to 6.4 from t to 0 decreasing step by 1
6.1. Check if i=7 then set i=0
6.2. Set str =w[i]
6.3. Increment I by 1
6.4. End of loop
7. Return the value of str
8. End

24 | Page
PROGRAM CODE
import java.util.*;
class day
{
String d;
String n;
//Default constructor
public day()
{
d="";
n="";
}//end of method
//Parametrized constructor
public day(String d1,String n1)
{
d=d1;
n=n1;
}//end of method
//Function to accept the date
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Date(dd/mm/yyyy)");
d=sc.nextLine();
System.out.println("Day on 1st January");
n=sc.nextLine();
}//end of method
//Function to check leap year
public booleancheckLeap(int year)

25 | Page
{
if(year%400==0)
return true;
if(year%4==0&&year%100!=0)
return true;
else
return false;
}//end of method
//Method to generate the date
public void generate()
{
StringTokenizerst=new StringTokenizer(d,"/");
int dt=Integer.valueOf(st.nextToken());//Extracting the date
int mt=Integer.valueOf(st.nextToken());//Extracting the month
int yr=Integer.valueOf(st.nextToken());//Extracting the year
int dd=0;
int mth[]={31,28,31,30,31,30,31,31,30,31,30,31};
if(checkLeap(yr)==true)
mth[1]=29;
//Loop to generate the day number
for(int i=0;i<mt-1;i++)
{
dd+=mth[i];
}
dd+=dt;
int h=dd%7;
System.out.println("Day on "+d+" is: "+week(h));
}//end of method
//Method to generate the day of the week
public String week(int t)
26 | Page
{ String
w[]={"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};
int i=0;
String str="";
for(;i<7;i++)
{ if(n.equalsIgnoreCase(w[i])==true)
break; }
if(t==0)
{ if(i==0)
str=w[6];
else
str=w[i-1]; }
else
{ for(;t>0;t--)
{ if(i==7)
{ i=0;
} str=w[i];
i++;
} }
return str;
}//end of method
//Main method to initiate the above task
public static void main()
{ day dy=new day();
dy.accept();
dy.generate();
}//end of method
}//end of class

27 | Page
OUTPUT
Enter Date(dd/mm/yyyy)
14/10/2019
Day on 1st January
TUESDAY
Day on 14/10/2019 is: MONDAY
Enter Date(dd/mm/yyyy)
5/7/2020
Day on 1st January
WEDNESDAY
Day on 5/7/2020 is: SUNDAY

28 | Page
QUESTION 6
Write a program to input two valid dates each comprising of a day (2 Digits),month(2 Digits)
and year(4 Digits) and calculate the day elapsed between two dates.
First Date:
Day:20
Month: 08
Year:2008
Second Date:
Day:06
Month:09
Year:2008
Day Elapsed:17

ALGORITHM
Algorithm for accept() function
1. Start
2. Input day,month ,year in corresponding variables
3. End
Algorithm for generate() function
1. Start
2. Set dt=0
3. Initialize an array mth[] with the days of the month
4. Check if the year is a leap year or not then set mth[1]=29
5. Repeat steps 5.1 to 5.2 from i to mm-1 increasing step by 1
5.1. Set dt=dt+mth[i];
5.2. End of loop
6. Return dt+dd
7. End
Algorithm for calculate(elapsed e) function
1. Start
2. Set ed=0
3. Check if the year of calling object is greater than parametrized object then print
“wrong input”
4. If the year of both the calling and parametrized object are equal then call
e.generate()-this.generate() and store it in ed
5. Else follow steps 5.1 to 5.4
5.1. Check if the year is leap or not and set ed accordingly 366
or365-this.generate()

29 | Page
5.2. Repeat steps 5.2.1 to 5.2.2 from yr+1 to e.yr-1 increasing step by 1
5.2.1. Check if the year is leap or not and add accordingly 366 or365 to ed
5.2.2. End of loop
5.3. Set ed=ed+e.generarte()
6. Print the day elased or ed
7. End
Algorithm for checkLeap() function
5. Start
6. If year%400=0 then return true
7. If year%4=0 and year%100!=0 then return true
8. End
Algorithm main() function
5. Start
6. Create a object e1 and e2
7. Call the functions accept() one by one
8. Call the function calculate() by e1 with e2 as parameter
9. End

PROGRAM CODE

30 | Page
import java.util.*;
class elapsed
{
int dd;
int mm;
int yr;
//Default constructor
public elapsed()
{
dd=mm=yr=0;
}//End of method
//Parametrized constructor
public elapsed(int m,intd,int y)
{
dd=d;
mm=m;
yr=y;
}//End of method
//Method to accept the two dates
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Day:");
dd=sc.nextInt();
System.out.println("Month:");
mm=sc.nextInt();
System.out.println("Year:");
yr=sc.nextInt();
}//End of method
//Method to check the leap year
31 | Page
public booleancheckLeap(int year)
{
if(year%400==0)
return true;
if(year%4==0&&year%100!=0)
return true;
else
return false;
}//End of method
//Method to calculate the day number
public int generate()
{
int dt=0;
int mth[]={31,28,31,30,31,30,31,31,30,31,30,31};
if(checkLeap(yr)==true)
mth[1]=29;
for(int i=0;i<mm-1;i++)
{
dt+=mth[i];
}
return dt+dd;
}//End of method
//Method to calculate the elapsed day
public void calculate(elapsed e)
{
int ed=0;
if(this.yr>e.yr)
{
System.out.println("Wrong input");
}
32 | Page
else
if(this.yr==e.yr)
{
ed=e.generate()-this.generate();
}
else
{ ed=(checkLeap(this.yr)==true?366:365)-this.generate();
//Loop to calculate the elapsed day
for(int i=yr+1;i<e.yr;i++)
{
if(checkLeap(i)==true)
ed+=366;
else
ed+=365;
} ed+=e.generate();
} System.out.println("Day elapsed: "+ed);
}//End of method
//Main method to initiate the task
public static void main()
{ elapsed e1=new elapsed();
e1.accept();
elapsed e2=new elapsed();
e2.accept();
e1.calculate(e2);
}//End of method
} //End of class

33 | Page
OUTPUT
Day:
20
Month:
08
Year:
2008
Day:
06
Month:
09
Year:
2008
Day elapsed: 17

34 | Page
Day:
15
Month:
07
Year:
2019
Day:
06
Month:
08
Year:
2019
Day elapsed: 22

35 | Page
QUESTION 7
Write a program to input month number(mm), day of the month(dd) and year(yyyy) and
calculate and the print the corresponding day of the year(1-366). Example
Input: month:05 day: 03 year: 1966 corresponding day of the year is
124(31+29+31+30+3=124)

ALGORITHM
Algorithm for accept() function
4. Start
5. Input day,month ,year in corresponding variables
6. End
Algorithm for generate() function
8. Start
9. Set doy=0
10. Initialize an array mth[] with the days of the month
11. Check if the year is a leap year or not then set mth[1]=29
12. Repeat steps 5.1 to 5.2 from i to mm-1 increasing step by 1
12.1. Set doy=doy+mth[i];
12.2. End of loop
13. Print doy+dd
14. End
Algorithm for checkLeap() function
9. Start
10. If year%400=0 then return true
11. If year%4=0 and year%100!=0 then return true
12. End
Algorithm for main() function
1. Start
2. Create a object
3. Call the functions accept() and generate()
4. End

36 | Page
PROGRAM CODE
import java.util.*;
class dayofyear
{ int dd;
int mm;
int yyyy;
//Default constructor to initialize the variables
public dayofyear()
{ dd=mm=yyyy=0;
}//End of method
//Parametrized constructor to initialize the variables
public dayofyear(int m,intd,int y)
{ dd=d;
mm=m;
yyyy=y;
}//End of method
//Method to accept the values from user
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Month:");
mm=sc.nextInt();
System.out.println("Day:");
dd=sc.nextInt();
System.out.println("Year:");
yyyy=sc.nextInt();
}//End of method
//Method to check leap year
public booleancheckLeap(int year)

37 | Page
{
if(year%400==0)
return true;
if(year%4==0&&year%100!=0)
return true;
else
return false;
}//End of method
//Method to generate the day of year
public void generate()
{
int doy=0;
int mth[]={31,28,31,30,31,30,31,31,30,31,30,31};
if(checkLeap(yyyy)==true)
mth[1]=29;
//Loop to generate the day of year
for(int i=0;i<mm-1;i++)
{
doy+=mth[i]; }
doy+=dd;
System.out.println("Corrresponding day on the year:"+doy);
}//End of method
//Main method to execute the above task
static void main()
{ dayofyear d1=new dayofyear();
d1.accept();
d1.generate();
}//End of method
}//End of class

38 | Page
OUTPUT

OUTPUT1:
Month:
07
Day:
31
Year:
2019
Corrresponding day on the year:212

OUTPUT 2:
Month:
12
Day:
14
Year:
2005
Corrresponding day on the year:348

39 | Page
QUESTION 8
Write a program to input a N x N matrix and display it. Find and print the saddle point in the
matrix. Saddle point means highest in column and lowest in row. Example
123
456
789
Saddle point 7

ALGORITHM
Algorithm for main() function
1. Start
2. Input the no. of rows m from the user
3. Check if m>=3 and m<=10 if not then display an appropriate message.
4. Declare an integer 2d array arr having row and column as m.
5. Repeat steps 5.1 to 5.2 from 0 to m-1 increasing step by 1.
5.1. Repeat steps 5.1.1 to 5.1. 2 from 0 to m-1 increasing step by 1.
5.1.1. Input values of 2D array from index 0 to m-1 from the user.
5.1.2. End of loop.
5.2. End of loop.
6. Repeat steps from 6.1 to 6.2 increasing step by 1, to display the elements of matrix.
6.1. Repeat steps 6.1.1 to 6.1.2 increasing step by 1.
6.1.1. Print the elements of array from position i,j.
6.1.2. End of loop.
6.2. End of loop
7. Set small=arr[0][0],pos=0
8. Repeat steps 8.1 to 8.2 From 0 to m-1 increasing step by 1
8.1. Repeat steps 8.1.1 to 8.1.3 from 0 to m-1 increasing step by 1
8.1.1. Check if small>arr[i][j]
8.1.2. Set small=arr[i][j],pos =j
8.1.3. End of loop
8.2. End of loop
9. Set large =arr[0][pos]
10. Repeat steps 10.1 to 10.2 From 0 to m-1 increasing step by 1
10.1. Repeat steps 10.1.1 to 10.1.3 from 0 to m-1 increasing step by 1
10.1.1. Check if large<arr[i][pos]
10.1.2. Set large=arr[i][pos]
10.1.3. End of loop
10.2. End of loop
11. Print the saddle point

PROGRAM CODE
40 | Page
import java.util.*;
class matrix8
{
//Main method to initiate the task
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array:");
int n=sc.nextInt();
int arr[][]=new int[n][n];//Creating a 2d array of n x n
System.out.println("Enter the elements of array:");
for(int i=0;i<n;i++)//Loop to input the elements to array
{
for(int j=0;j<n;j++)
{
arr[i][j]=sc.nextInt();
}
}//End of loop
System.out.println("The elements of array:");
for(int i=0;i<n;i++)//Loop to display the elements of matrix
{
for(int j=0;j<n;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}//End of loop
int small=arr[0][0],pos=0;
//Loop to find the saddle point of matrix
for(int i=0;i<n;i++)
{

41 | Page
for(int j=0;j<n;j++)
{
if(small>arr[i][j])
{
small=arr[i][j];
pos=j;
}
}
}//end of loop
int large=arr[0][pos];
for(int i=0;i<n;i++)
{
if(large<arr[i][pos])
large=arr[i][pos];
}
System.out.println("Saddle point: "+large);
}//End of method
}//End of class

42 | Page
OUTPUT
Enter the size of array:
4
Enter the elements of array:
1234
5678
9101112
13141516
The elements of array:
1234
5678
9 10 11 12
13 14 15 16
Saddle point: 13

43 | Page
QUESTION 9
Write a program to input a N x N matrix, print it and check whether the matrix is a magic
square or not. A matrix is said to be a magic square if the sum of all rows, columns,
diagonals are equal.

ALGORITHM
Algorithm for main() function
1. Start
2. Input m to store the no. of rows.
3. Declare an integer 2D array with row and column of size m.
4. Repeat steps 4.1 to 4.2 from 0 to m-1 increasing step by 1.
4.1. Repeat steps 4.1.1 to 4.1. 2 from 0 to m-1 increasing step by 1.
4.1.1. Input values of 2D array from index 0 to m-1 from the user.
4.1.2. End of loop.
4.2. End of loop.
5. Repeat steps 5.1 to 5.2 from 0 to m-1 increasing step by 1.
5.1. Repeat steps 5.1.1 to 5.1. 2 from 0 to m-1 increasing step by 1.
5.1.1. Print the element
5.1.2. End of loop.
6. End of loop
7. Set sumr,sumc,sumld,sumrd,c=0
8. Repeat steps 8.1 to 8.2 from 0 to m-1 increasing step by 1
8.1. Store the sum of left and right diagonals in the respective variables
8.2. End of loop
9. Check if sum of left diagonal != sum of right diagonal then print a appropriate
message and set c=1
10. Repeat steps 10.1. to 10.2. from 0 to m-1 increasing step by 1
10.1. Set sumr ,sumc=0
10.2. Repeat steps 10.2.1. to 10.2.2 from 0 to m-1 increasing step by 1
10.2.1. Store the sum of rows and columns in respective variables
10.2.2. End of loop
10.3. Check if sum of row or columns !=sum of the diagonals then print a
appropriate message and set c=1
10.4. End of loop
11. Check if c=0 then print a message “the matrix is a magic square”
12. End

PROGRAM CODE
44 | Page
import java.util.*;
class matrix9
{
//Main method to initiate the task
public static void main()
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter the no of rows");
int m=sc.nextInt();
int arr[][]=new int[m][m];//Creating a 2d array with m x m
for(int i=0;i<m;i++)//Loop to input the elements to array
{
for(int j=0;j<m;j++)
{
arr[i][j]=sc.nextInt();
}
}//End of loop
System.out.println("Elements of array");
for(int i=0;i<m;i++)//Loop to display the elements of array
{
for(int j=0;j<m;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}//End of loop
int sumr=0,sumc=0,sumld=0,sumrd=0,c=0;
for(int j=0;j<m;j++)//Loop to find the sum of diagonals
{
sumld+=arr[j][j];
sumrd+=arr[j][m-j-1];
}//End of loop
if(sumld!=sumrd)
{
System.out.println("The matrix is not a magic square");
c=1;
}
for(int i=0;i<m;i++)//Loop to find the sum of rows and columns
{
sumr=0;
sumc=0;
for(int j=0;j<m;j++)
{
sumr+=arr[i][j];

45 | Page
sumc+=arr[j][i];
}
if(sumr!=sumld||sumc!=sumld)
{
System.out.println("The matrix is not a magic square");
c=1;
break;
}
}//End of loop
if(c==0)
{
System.out.println("The matrix is a magic square");
}
}//End of method
}//End of class

46 | Page
OUTPUT

Enter the no of rows


3

276
951
438
Elements of array
276
951
438
The matrix is a magic square

47 | Page
QUESTION 10
Write a program to input a N x N matrix and display it. Now sort the non-boundary elements
of the matrix using any standard sorting method.

ALGORITHM
Algorithm for main() function
1. Start
2. Input the no. of rows m from the user
3. Check if m>=3 and m<=10 if not then display an appropriate message.
4. Declare an integer 2d array having row and column as m.
5. Repeat steps 5.1 to 5.2 from 0 to m-1 increasing step by 1.
5.1. Repeat steps 5.1.1 to 5.1. 2 from 0 to m-1 increasing step by 1.
5.1.1. Input values of 2D array from index 0 to m-1 from the user.
5.1.2. End of loop.
5.2. End of loop.
6. Repeat steps from 6.1 to 6.2 increasing step by 1, to display the elements of matrix.
6.1. Repeat steps 6.1.1 to 6.1.2 increasing step by 1.
6.1.1. Print the elements of array from position i,j.
6.1.2. End of loop.
6.2. End of loop.
7. Set k=(m*m)-(4*(m-1))
8. Declare a integer 1d array nd with size k.
9. Set k=0;
10. Repeat steps 10.1 to 10.2 from 1 to m-2 increasing step by 1
10.1. Repeat steps 10.1.1 to 10.1.3 from 1 to m-2 increasing step by 1
10.1.1. Store the element at I,jthpositon of 2d array to the kth positon of 1d array
10.1.2. Increment k by 1.
10.1.3. End of loop.
10.2. End of loop

11. Repeat steps 11.1 to 11.7 from 0 to nb.length-1 increasing step by 1


11.1. Set pos=i.
11.2. Repeat steps 11.2.1 to 11.2.3 from i+1 to nb.length increasing step by 1
11.2.1. Check if nb[pos]>nb[j]
11.2.2. Set pos=j.
11.2.3. End of loop.
11.3. Check if pos!=i
11.4. Set temp =nb[pos]
11.5. nb[pos]=nb[i]
11.6. nb[i]=temp
11.7. End of loop
12. Set k=0
13. Repeat steps 13.1 to 13.2 from 1 to m-2 increasing step by 1
13.1. Repeat steps 13.1.1 to 13.1.3 from 1 to m-2 increasing step by 1

48 | Page
13.1.1. Store the element at the kth positon of 1d array to the I,jthpositon of 2d
array
13.1.2. Increment k by 1.
13.1.3. End of loop.
13.2. End of loop
14. Repeat steps from 14.1 to 14.2 increasing step by 1, to display the elements of sorted
matrix.
14.1. Repeat steps 6.1.1 to 6.1.2 increasing step by 1.
14.1.1. Print the elements of array from position i,j.
14.1.2. End of loop.
14.2. End of loop.
15. End.

PROGRAM CODE
import java.util.*;
49 | Page
class matrix10
{
//Main method to initiate tthe task
public void main()
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter the no of rows");
int m=sc.nextInt();
int arr[][]=new int[m][m];//Craete a 2d array with dimensions as m x m
for(int i=0;i<m;i++)//loop to input the elements into array
{
for(int j=0;j<m;j++)
{
arr[i][j]=sc.nextInt();
}
}//End of loop
System.out.println("Elements of matrix");
for(int i=0;i<m;i++)//loop to display the elements of matrix
{
for(int j=0;j<m;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}//End of loop
int d=(m*m)-(4*(m-1));
int nb[]=new int[d];
int k=0;
for(int i=1;i<m-1;i++)//loop to take out the non boundary elements
{
50 | Page
for(int j=1;j<m-1;j++)
{
nb[k]=arr[i][j];
k++;
}
}//End of loop
for(int i=0;i<nb.length-1;i++)//loop to sort the elements
{
int pos=i;
for(int j=i+1;j<nb.length;j++)
{
if(nb[pos]>nb[j])
{
pos=j;
}
}
if(pos!=i)
{
int temp=nb[pos];
nb[pos]=nb[i];
nb[i]=temp;

}
}//End of loop
k=0;
for(int i=1;i<m-1;i++)//loop to put the elements back into matrix
{
for(int j=1;j<m-1;j++)
{
arr[i][j]=nb[k];
51 | Page
k++;
}
}//End of loop
System.out.println("Sorted matrix");
for(int l=0;l<m;l++)//Printing the matrix
{
for(int j=0;j<m;j++)
{
System.out.print(arr[l][j]+" ");
}
System.out.println();
}//End of loop
}//End of method
}//End of class

52 | Page
OUTPUT
Enter the no of rows
4
1234
5678
9-51490
13752144
Elements of matrix
1234
5678
9 -5 14 90
13 75 21 44
Sorted matrix
1234
5 -5 6 8
9 7 14 90
13 75 21 44

53 | Page
QUESTION 11
Write a program to input a N x N matrix and display it. Check whether it is a symmetric
matrix or not. A matrix is said to be symmetric if the element at the ith row and jth column is
equal to jth row and ith column

ALGORITHM
Algorithm for main() function
1. Start
2. Input the no. of rows m from the user
3. Declare an integer 2d array having row and column as m.
4. Repeat steps 5.1 to 5.2 from 0 to m-1 increasing step by 1.
4.1. Repeat steps 5.1.1 to 5.1. 2 from 0 to m-1 increasing step by 1.
4.1.1. Input values of 2D array from index 0 to m-1 from the user.
4.1.2. End of loop.
4.2. End of loop.
5. Repeat steps from 6.1 to 6.2 increasing step by 1, to display the elements of matrix.
5.1. Repeat steps 6.1.1 to 6.1.2 increasing step by 1.
5.1.1. Print the elements of array from position i,j.
5.1.2. End of loop.
5.2. End of loop.
6. Set flag = true
7. Repeat steps 7.1 to 7.2 from 0 to m-1 increasing step by 1
7.1. Repeat steps 7.1.1. to 7.1.2 from 0 to m-1 increasing step by 1
7.1.1. Check if the i.jth element of the array is not equal to j,i the element of the
array,then set flag =false
7.1.2. End of loop
7.2. End of loop
8. Check if flag=true then print “The matrix is symmetric” else print “The matrix is not
symmetric”
9. End

PROGRAM CODE
54 | Page
import java.util.*;
class matrix11
{
//main method to initiate the task
public void main()
{ Scanner sc =new Scanner(System.in);
System.out.println("Enter the no of rows");
int m=sc.nextInt();
int arr[][]=new int[m][m];//creating a 2d array with dimensions as mxm
for(int i=0;i<m;i++)//loop to input the elements into array
{
for(int j=0;j<m;j++)
{
arr[i][j]=sc.nextInt(); }
}//End of loop
System.out.println("Elements of matrix");
for(int i=0;i<m;i++)//loop to display the elements of matrix
{ for(int j=0;j<m;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}//End of loop
boolean flag=true;
for(int i=0;i<m;i++)//loop to check whether the matrix is symmetric
{ for(int j=0;j<m;j++)
{
if(arr[i][j]!=arr[j][i])
flag=false;
break;
}
}//End of loop
if(flag==true)
{
System.out.println("THE MATRIX IS SYMMETRIC");
}
else
{ System.out.println("THE MATRIX IS NOT SYMMETRIC");
}
}//End of method
}//End of class

55 | Page
OUTPUT

Enter the no of rows


3
123
245
356
Elements of matrix
123
245
356
THE MATRIX IS SYMMETRIC

Enter the no of rows


4
1234
5678
910 1112
13141516
Elements of matrix
1234
5678
9 10 11 12
13 14 15 16
THE MATRIX IS NOT SYMMETRIC

56 | Page
QUESTION 12
Two matrices are said to be equal if they have same dimension and their corresponding
elements are also equal. Example :
Matrix 1 Matrix 2
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
Design a class EqMat to check whether two matrices are equal or not
Data members
a[][]:to store integer element
m: store number of rows
n: store number of columns
Member Functions
EqMat(int mm,intnn): parametrized constructor to initialize m=mm and n=nn
void readarray(): to enter elements in array
int check(EqMatP,EqMat Q): check if the parametrized object P and Q are Equal and returns
1 if true else returns 0
void print(): display the array elements
Write a main method to create objects and call functions. Also print whether the matrices
are equal or not

ALGORITHM
Algorithm for readarray() function
1. Start
2. Create a scanner object
3. Repeat steps 3.1 to 3.2 from 0 to m-1 increasing step by 1.
3.1. Repeat steps 3.1.1 to 3.1.2 from 0 to m-1 increasing step by 1.
3.1.1 Input values of 2D array from index 0 to m-1 from the user.
3.1.2. End of loop
3.2.End of loop
4. End
Algorithm for check() function
1. Start
2. Check if the size of rows and columns both the arrays are equal,if not then return 0
3. Repeat steps 3.1 to 3.2 from 0 to m-1 increasing step by 1
3.1. Repeat steps 3.1.1 to 3.1.2 from 0 to n-1 increasing step by 1
3.1.1. Check if the i,jth element of both the array are equal or not if not return 0
3.1.2. End of loop

57 | Page
3.2. End of loop
4. Return 1
5. End
Algorithm for print() function
1. Start
2. Repeat steps 2.1 to 2.2 from 0 to m-1 increasing step by 1
2.1. Repeat steps 2.1.1 to 2.1.2 from 0 to n-1 increasing step by 1
2.1.1. Print the I,jth element of array
2.1.2. End of loop
2.2. End of loop
3. End
Algorithm for main() function
1. Start
2. Input the no of rows r1 and columns c1 from the user
3. Create an object e1 with r1 and c1
4. Input the no of rows r2 and columns c2 from the user
5. Create an object e2 with r2 and c2
6. Call the function readarray() with two objects one by one
7. Print the two matrices one by one by calling the print() function
8. Call the function check() with e1 and e2 as parameters
9. If the function returns 1 then print “The two matrices are equal” else print “The two
matrices are not equal”
10. End

PROGRAM CODE

import java.util.*;
class EqMat
58 | Page
{
int a[][];
int m,n;
//Parametrized constructor to initialize the data members
public EqMat(int mm,intnn)
{
m=mm;
n=nn;
a=new int[m][n];
}//end of method
//Method to store the elements into array
public void readarray()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the elements of array");
for(int i=0;i<m;i++)//loop to enter elements into array
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}//End of loop
}//end of method
//Method to check whether the matrices are equal or not
public int check(EqMatP,EqMat Q)
{
if(P.m!=Q.m||P.n!=Q.n)//checking the dimensions of array
return 0;
else
{
for(int i=0;i<m;i++)//loop to check whether the matrix is symmetric
{
for(int j=0;j<n;j++)
{
if(P.a[i][j]!=Q.a[i][j])
return 0;
}
}//end of loop
return 1;
}
}//end of method
//method to print the elements of array
void print()
{

59 | Page
for(int i=0;i<m;i++)//loop to print the elemnts of array
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}//end of loop
}//end of method
//main method to execute the above task
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of rows of array 1");
int r1=sc.nextInt();
System.out.println("Enter no. of columns of array 1");
int c1=sc.nextInt();
EqMat e1=new EqMat(r1,c1);
e1.readarray();
System.out.println("Enter no. of rows of array 2");
int r2=sc.nextInt();
System.out.println("Enter no. of columns of array 2");
int c2=sc.nextInt();
EqMat e2=new EqMat(r2,c2);
e2.readarray();
System.out.println("MATRIX 1");
e1.print();
System.out.println("MATRIX 2");
e2.print();
if(e1.check(e1,e2)==1)
{
System.out.println("THE TWO MATRICES ARE EQUAL");
}
else
{
System.out.println("THE TWO MATRICES ARE NOT EQUAL"); }
}//end of method
}//end of class

60 | Page
OUTPUT

Enter no. of rows of array 1


3
Enter no. of columns of array 1
3
Enter the elements of array
987
654
321
Enter no. of rows of array 2
3
Enter no. of columns of array 2
3
Enter the elements of array
987
654
321

61 | Page
MATRIX 1
987
654
321
MATRIX 2
987
654
321
THE TWO MATRICES ARE EQUAL

62 | Page
QUESTION 13
Write a program to declare a single dimension array a[] and a square matrix b[][] of size N
where n>2 and N<10. Allow user to input positive integers into single dimension array.
Perform the following task:
i. Sort the element of single dimension array in descending order using any standard sorting
technique
ii. Fill the square matrix b[][] in the following format
a[]={5,2,8,1} after sorting a[]={8,5,2,1}
The matrix b should be filled in the following format
8 5 2 1
8 5 2 8
8 5 8 5
8 8 5 2
iii. Display the filled matrix

ALGORITHM
Algorithm for main() function
12. Start
13. Input the no. of rows n from the user
14. Check if n>2 and n<10 if not then display an appropriate message.
15. Declare an integer 1d array a[] having row asn.
16. Repeat steps 5.1 to 5.2 from 0 to n-1 increasing step by 1.
16.1. Input values of 1D array from index 0 to m-1 from the user.
16.2. End of loop.
17. Repeat steps 6.1 to 6.7 from 0 to n-1 increasing step by 1
17.1. Set pos=i.
17.2. Repeat steps 6.2.1 to 6.2.3 from i+1 to n-1 increasing step by 1
17.2.1. Check if a[j]>a[pos]
17.2.2. Set pos=j.
17.2.3. End of loop.
17.3. Check if pos!=i
17.4. Set temp =a[pos]
17.5. a[pos]=a[i]
17.6. a[i]=temp
17.7. End of loop
18. Declare a integer 2d array b[][] with row and column as n
19. Repeat steps 8.1 to 8.4 from 0 to n-1 increasing step by 1
19.1. Set k=0
19.2. Repeat steps 8.2.1 to 8.2.3 from 0 to n-i-1 increasing step by 1
19.2.1. Set i,jth element of b[][]=j th element of a[]
19.2.2. Increment k by 1
19.2.3. End of loop
19.3. Repeat steps 8.3.1 to 8.3.3 from 0 to i-1 increasing step by 1
19.3.1. Set i,kth element of b[][]=p th element of a[]
63 | Page
19.3.2. Increment k by 1
19.3.3. End of loop
19.4. End of loop
20. Repeat steps from 9.1 to 9.2 increasing step by 1, to display the elements of matrix.
20.1. Repeat steps 9.1.1 to 9.1.2 increasing step by 1.
20.1.1. Print the elements of array from position i,j.
20.1.2. End of loop.
20.2. End of loop.
21. End

PROGRAM CODE
64 | Page
import java.util.*;
class matrix13
{ //Main method to execute the task
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array(>2 and <10)");
int n=sc.nextInt();
if(n<=2||n>=10)//checking the validity of input
{
System.out.println("Invalid size of array");
System.exit(0);
}
else {
int a[]=new int[n];
System.out.println("Enter the elements of array");
for(int i=0;i<n;i++)//loop to enter the elements into array
{
a[i]=sc.nextInt();
}//end of loop
for(int i=0;i<n;i++)//loop to sort the array
{
int pos=i;
for(int j=i+1;j<n;j++)
{
if(a[j]>a[pos])
pos=j;
}
if(pos!=i) {
int temp=a[pos];
a[pos]=a[i];

65 | Page
a[i]=temp;
}
}//end of loop
int b[][]=new int [n][n];
for(int i=0;i<n;i++)//loop to fill the elements back into array
{
int k=0;
for(int j=0;j<n-i;j++)
{
b[i][j]=a[j];
k++;
}
for(int p=0;p<i;p++)
{
b[i][k]=a[p];
k++;
}
}//end of loop
System.out.println("The elements of array");
for(int i=0;i<n;i++)//printing the elements of array
{ for(int j=0;j<n;j++)
{ System.out.print(b[i][j]+" ");
}
System.out.println();
}//end of loop
}//end of if
}//end of method
}//end of class

66 | Page
OUTPUT

OUTPUT 1:
Enter the size of array(>2 and <10)
4
Enter the elements of array
5
9
7
1
The elements of array
9751
9759
9797
9975

OUTPUT 2:
Enter the size of array(>2 and <10)
11
Invalid size of array

67 | Page
QUESTION 14
Write a program to create a file and store n numbers in it. Now display all the magic
numbers from that file. A number is said to be a magic number if the eventual sum of digits
of the number is equal to 1. For example 127: (1+2+7=10=1+0=1)

ALGORITHM
Algorithm for main() function
1. Start
2. Create a new text file magic.txt.
3. Create an object of file writer stream
4. Input the no. of numbers from the user store it in n
5. Repeat steps 4.1 to 4.3 from 1 to n-1 increasing step by 1
5.1. Input the number from the user and store it in the file
5.2. End of loop
6. Create an object of file reader stream
7. Repeat steps 6.1 to 6.3 until all the words from the file has been read
7.1. Read the numbers from the file and store it in m
7.2. Check if the checkMagic(m) function returns true
7.3. Print the word
7.4. End of loop
8. End
Algorithm for checkMagic() function
1. Start
2. Set d=x
3. Repeat steps from 3.1 to 3.4 while d>9
3.1. Set d=0
3.2. Repeat steps 3.2.1 to 3.2.3 while x>0
3.2.1. Set d=d+x%10
3.2.2. Set x=x/10
3.2.3. End of loop
3.3. Set x=d
3.4. End of loop
4. Check if d=1 the return true else return false
5. End

PROGRAM CODE
68 | Page
import java.io.*;
import java.util.*;
class magic
{
//Main method to execute the task
public void main()throws IOException
{
FileWriterfw=new FileWriter("Magic.txt",true);
BufferedWriterbw =new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no. of numbers to enter");
int n=sc.nextInt();
for(int i=1;i<=n;i++)//loop to input the numbers into file
{
pw.println(sc.nextInt());
}//end of loop
pw.close();
bw.close();
pw.close();
FileReaderfr=new FileReader("Magic.txt");
BufferedReaderbr =new BufferedReader(fr);
System.out.println("The magic numbers are:");
for(int i=1;i<=n;i++)//loop to print the magic numbers from the file
{
int m=Integer.parseInt(br.readLine());
if(checkMagic(m)==true)
System.out.println(m);
}//end of loop
br.close();
69 | Page
fr.close();
}//end of method
//method to check whether the number is magic or not
booleancheckMagic(int x)
{
int d=x;
while(d>9)//loop to find out the sum of digits of number
{
d=0;
while(x>0)
{
d+=x%10;
x/=10;
}
x=d;
}//end of loop
if(d==1)
return true;
else
return false;
}//end of method
}//end of class

70 | Page
OUTPUT
Enter the no. of numbers to enter
5
1
100
54
36
58
The magic numbers are:
1
100

71 | Page
QUESTION 15
Write a program to accept a sentence which may be terminated by either ‘.’,’?’,or’!’ only. The
words are to be separated by a single blank space and are in upper case.
Perform the following task:
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 last character). Example: The reverse
for HELP would be LEH(omitting the new alphabet) and by concatenating both, the
new palindrome word is HELPLEH. The word ends which ends with repeated
alphabets for e.g. ABB would become ABBA and not ABBBA. Words spell from either
side is said to be palindrome.
c. Display the original word and the converted sentence
THE BIRD IS FLYING
THEHT BIRDRIB ISI FLYINGNIYLF

ALGORITHM
Algorithm for main() function
1. Start
2. Input a sentence from the user and store it in s after converting it to upper case
3. Check if the sentence ends with ‘.’,’?’,’!’ else print an appropriate message
4. Create a string tokenizer object str
5. Count the no. of tokens in the tokenizer and store it in l
6. Set ns=””
7. Repeat steps 7.1 to 7.7 from 0 to l-1 increasing step by 1
7.1. Store the next token in str
7.2. Create a string buffer object with s1
7.3. Reverse the contents of string buffer
7.4. Convert the string buffer to string and store it from the 1st index of string in s2
7.5. Check for the repeated characters and delete the characters from the
reversed string
7.6. Concatenate the string s1 to s2
7.7. Concatenate the string to ns with a space in between
7.8. End of loop
8. Print the original sentence and the converted sentence
9. End

PROGRAM CODE
import java.util.*;

72 | Page
class sentence
{
//Main method to initiate the task
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence ending with(.,?,!)");
String s=sc.nextLine().toUpperCase();
//checking for the validity of input
if(s.charAt(s.length()-1)!='.'&&s.charAt(s.length()-1)!='?'&&s.charAt(s.length()-1)!='!')
{
System.out.println("Wrong input");
System.exit(0);
}
StringTokenizer str=new StringTokenizer(s,".,?,,! ");
int l=str.countTokens();
String ns="";
for(int i=0;i<l;i++)//loop to reverse the string and concatenate it
{
String s1=str.nextToken();
StringBuffersb=new StringBuffer(s1);
sb=sb.reverse();
String s2=sb.toString();
s2=s2.substring(1);
if(s1.length()!=1)
{
while(true)//loop to check repeated charcters
{
if(s2.charAt(0)!=s1.charAt(s1.length()-1))
break;
else
s2=s2.substring(1);
}
}
s1=s1+s2;
ns+=s1+" ";
}//end of loop
System.out.println(s);
System.out.println(ns);
}//end of method
}//end of class

73 | Page
OUTPUT

OUTPUT 1
Enter a sentence ending with(.,?,!)
THIS IS ABBB.
THIS IS ABBB.
THISIHT ISI ABBBA

OUTPUT 2
Enter a sentence ending with(.,?,!)
APPLE
Wrong input

QUESTION 16

74 | Page
The names of teams participating in a competition should be displayed on a banner
vertically to accommodate as many teams as possible in a single banner. Design a program
to accept the names of N team where 2<N<9 and display them in vertical order side by side
with horizontal tab. Example N=3 Team 1: Emus Team 2: Road Rol Team 3: Coyote
E R C
m o o
u a y
s d o
t
R e
o
l

ALGORITHM
Algorithm for main() function
1. Start
2. Input the number of teams and store it in n
3. Check if 2 < n < 9 ,if not print an appropriate message
4. Set l=0
5. Declare a string array s[] with size as n
6. Repeat steps from 6.1 to 6.3 from 0 to n-1 increasing step by 1
6.1. Input the names of teams and store it in the ith index of the array s[]
6.2. Store the size of the longest word in l
6.3. End of loop
7. Repeat steps 7.1 to 7.2 from 0 to l-1 increasing step by 1
7.1. Repeat steps 7.1.1 to 7.1.2 from 0 to n-1 increasing step by 1
7.1.1. Check if i<length of the word, then print the character from the ith index
of the string else print a tab space
7.1.2. End of loop
7.2. End of loop
8. End

PROGRAM CODE
import java.util.*;
class banner
75 | Page
{
//main method to initiate the task
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the no. of teams(2<n<9)");
int n=sc.nextInt();
if(n<=2||n>=9)//checking the validity of input
{
System.out.println("Wrong input");
System.exit(0);
}
int l=0;
sc.nextLine();
String s[]=new String[n];
System.out.println("Enter the name of teams");
for(int i=0;i<n;i++)//loop to input the names of teams
{
System.out.println("Team "+(i+1));
s[i]=sc.nextLine();
if(l<s[i].length())
{
l=s[i].length();
}
}//end of loop
for(int i=0;i<l;i++)//loop to print the names of teams vertically
{
for(int j=0;j<n;j++)
{
if(i<s[j].length())
{
System.out.print(s[j].charAt(i)+"\t");
}
else
{ System.out.print("\t");
} }
System.out.println();
}//end of loop
}//end of method
}//end of class

76 | Page
OUTPUT

OUTPUT 1
Enter the no. of teams(2<n<9)
3
Enter the name of teams
Team 1
Hogan
Team 2
Greisen
Team 3
Buntain

H G B
o r u
g e n
a i t
n s a
e i
n n

OUTPUT 2
Enter the no. of teams(2<n<9)
10
Wrong input

77 | Page
QUESTION 17
Ceaser Cipher is an encryption technique which is implemented as ROT13(rotate by 13
places). It is a simple letter substitution cipher that replaces a letter with the letter 13 places
after it in the alphabets with other characters remaining unchanged.
Write a program to accept a plain text of length L where l>3 and l<100. Encrypt the text if
valid as per the ceaser cipher.
Input: Hello! How are you?
Output: Uryyb! Ubjnerlbh?

ALGORITHM
Algorithm for main() function
1. Start
2. Create a new scanner object
3. Accept the input from the user and store it in s
4. Store the length of the word in l
5. Check if l<3 or l>100 ,then print a appropriate message
6. Declare s1=””
7. Repeat steps 7.1 to 7.8 from 0 to l-1 increasing step by 1
7.1. Store the character at ith position of s inch
7.2. Check if the character is letter or not
7.3. Set c=ch+13
7.4. Check if the character is in upper case and check if c>91 then set c=(c-91)+65
7.5. Check if the character is in lower case and check if c>122 then set
c=(c-122)+96
7.6. Typecast c to character and store it in ch
7.7. Set s1=s1+ch
7.8. End of loop
8. Print the sentence
9. End

78 | Page
PROGRAM CODE
import java.util.*;
class ceaser
{
//mian method to initiate the task
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a text");
String s=sc.nextLine();
int l=s.length();
if(l<=3||l>=100)//checking the validity of input
{
System.out.println("Invalid length of text");
System.exit(0);
}
String s1="";
for(int i=0;i<l;i++)//loop to rotate the characters by 13 places
{
char ch=s.charAt(i);
//checking whether the letter is a character
if(Character.isLetter(ch)==true)
{
int c=ch+13;
if(Character.isUpperCase(ch)==true)
{
if(c>91)
{
c=(c-91)+65;
}
}
else
{ if(c>122)
{
c=(c-122)+96;
} }
ch=(char)c;
}
s1+=ch;
}//end of loop
System.out.println(s1);
}//end of method
}//end of class

79 | Page
OUTPUT

OUTPUT 1:
Enter a text
Hello! How are you?
Uryyb! Ubjnerlbh?

OUTPUT 2:
Enter a text
M
Invalid length of text

QUESTION 18
80 | Page
Write a program to implement STACK using an array

ALGORITHM
Algorithm for isEmpty() function
1. Start
2. Check if top =-1 then return true else return false
3. End
Algorithm for isFull() function
1. Start
2. Check if top =size-1 then return true else return false
3. End
Algorithm for push() function
1. Start
2. Check if isFull()=true then print a message
3. Else set top =top+1 and put the element in the top position array
4. End
Algorithm for pop() function
1. Start
2. Check if isEmpty() = true then print an appropriate message and return -999
3. Else store the element in top position of array in x
4. Set top=top-1
5. Return the value x
6. End
Algorithm for peep() function
1. Start
2. Check if isEmpty() = true then print an appropriate message and return -999
3. Else store the element in top position of array in x
4. Return the value x
5. End
Algorithm for display() function
1. Start
2. Check if isEmpty() = true then print an appropriate message
3. Else print the elements of stack
4. Repeat steps 4.1 to 4.2 from 0 to top increasing step by 1
4.1. Print the element in the I th position of the array
4.2. End of loop
5. End
81 | Page
Algorithm for main() function
1. Start
2. Create a scanner object
3. Set c=0
4. Repeat steps from 4.1 to 4.3 until c is not equal to 5
4.1. Accept the choice from the user
4.2. Then perform the appropriate task by calling the specified function
4.3. End of loop
5. End

PROGRAM CODE
import java.util.*;
class stack
82 | Page
{
int arr[];
int top;
int size;
//default constructor to initialize the values
public stack()
{
size=5;
arr=new int[size];
top=-1;
}//end of method
//parametrized constructor to initialize the values
public stack(int s)
{
size=s;
arr=new int[size];
top=-1;
}//end of method
//method to check if the stack is empty
public booleanisEmpty()
{
if(top==-1)
return true;
else
return false;
}//end of method
//method to check if the stack is full
public booleanisFull()
{
if(top==(size-1))
83 | Page
return true;
else
return false;
}//end of method
//method to push values into stack
public void push(int val)
{
if(isFull()==true)
{
System.out.println("Stack Overflow");
}
else
{
top+=1;
arr[top]=val;
}
return;
}//end of method
//method to pop out values from the stack
public int pop()
{
if(isEmpty()==true)
{
System.out.println("Stack Underflow");
return -999;
}
else
{
int x=arr[top];
top-=1;
84 | Page
return x;
}
}//end of method
//method to peep values from the stack
public int peep()
{
if(isEmpty()==true)
{
System.out.println("Stack Underflow");
return -999;
}
else
{
int x=arr[top];
return x;
}
}//end of method
//method to display elements of stack
public void display()
{
if(isEmpty()==true)
{
System.out.println("Stack empty");
return;
}
else
{
System.out.println("Contents of Stack");
for(int i=0;i<=top;i++)//loop to print contents of stack
{
85 | Page
System.out.println(arr[i]+" ");
}
}
}//end of method
//main method to execute the above task
public static void main(int n)
{
Scanner sc=new Scanner(System.in);
stack s1=new stack(n);
int c=0;
while(c!=5)//loop to perform various operations
{
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peep");
System.out.println("4. Display");
System.out.println("5. Exit");
c=sc.nextInt();
switch(c)
{
case 1:
System.out.println("Enter the value");
s1.push(sc.nextInt());
break;
case 2:
System.out.println(s1.pop());
break;
case 3:
System.out.println(s1.peep());
break;
86 | Page
case 4:
s1.display();
break;
case 5:
System.out.println("Program exits");
break;
default:
System.out.println("Enter choice properly");
}
}//end of loop
}//end of method
}//end of class

87 | Page
OUTPUT
1. Push
2. Pop
3. Peep
4. Display
5. Exit
1
Enter the value
5
1. Push
2. Pop
3. Peep
4. Display
5. Exit
4
88 | Page
Contents of Stack
5
1. Push
2. Pop
3. Peep
4. Display
5. Exit
5
Program exits

QUESTION 19

89 | Page
Write a program to implement DEQUEUE using array.

ALGORITHM
Algorithm for addfront() function
1. Start
2. Check if fr=-1 then set fr=re=0 and arr[fr]=val
3. Check if fr=0 then print aa appropriate message
4. Else decrease fr by 1 and set arr[fr]=val
5. End
Algorithm for addrear() function
1. Start
2. Check if re=-1 then set fr=re=0 and arr[re]=val
3. Check if re=0 then print aa appropriate message
4. Else increase re by 1 and set arr[re]=val
5. End
Algorithm for popfront() function
1. Start
2. Check if fr=-1 then print an appropriate message and return -999
3. Check if fr=re then store the value set fr=re=-1 and then return the value
4. Else store the value and increase fr by 1 and return the value
5. End
Algorithm for poprear() function
1. Start
2. Check if fr=-1 then print an appropriate message and return -999
3. Check if fr=re then store the value set fr=re=-1 and then return the value
4. Else store the value and decrease re by 1 and return the value
5. End
Algorithm for main() function
1. Start
2. Input the choice of the user as input or output restricted and store it in ch
3. Set d=0
4. Check the value of ch and perform the following steps
4.1. If ch=1 then repeat steps 4.1.1. to 4.1.2. till d!=3
4.1.1. Store the choice of the user to push pop or exit in d
4.1.2. Check the value of d and perform the following steps
4.1.2.1. If d=1 then input the value from the user and call the method
addfront()

90 | Page
4.1.2.2. If d=2 then ask the user to pop from front or rear and call the
method accordingly
4.1.2.3. If d=3 then exit
4.2. If ch=2 then repeat steps 4.2.1. to 4.2.2. till d!=3
4.2.1. Store the choice of the user to push pop or exit in d
4.2.2. Check the value of d and perform the following steps
4.2.2.1. If d=2 then call the method popfront()
4.2.2.2. If d=1 then ask the user to push from front or rear and call the
method accordingly with the inputted value
4.2.2.3. If d=3 then exit
4.3. Else print an appropriate message
5. End

PROGRAM CODE
import java.util.*;

91 | Page
class deQueue
{
int arr[];
int size,fr,re;
//parametrized constructor to initialize the values
public deQueue(int s)
{
size=s;
arr=new int[size];
fr=-1;re=-1;
}//end of method
//method to add values from front
public void addfront(int val)
{
if(fr==-1)
{
fr=re=0;
arr[fr]=val;
}
else
if(fr==0)
{
System.out.println("Overflow from front");
}
else
{
fr--;
arr[fr]=val;
}
}//end of method
92 | Page
//method to add values from rear
public void addrear(int val)
{
if(re==-1)
{
fr=re=0;
arr[re]=val;
}
else
if(re==size-1)
{
System.out.println("Overflow from rear");
}
else
{
re++;
arr[re]=val;
}
}//end of method
//method to pop values from front
public int popfront()
{
if(fr==-1)
{
System.out.println("Queue is empty");
return -9999;
}
else
if(fr==re)
{
93 | Page
int val=arr[fr];
fr=re=-1;
return val;
}
else
{
int val=arr[fr];
fr++;
return val;
}
}//end of method
//method to pop values from rear
public int poprear()
{
if(fr==-1)
{
System.out.println("Queue is empty");
return -9999;
}
else
if(fr==re)
{
int val=arr[re];
fr=re=-1;
return val;
}
else
{
int val=arr[re];
re--;
94 | Page
return val;
}
}//end of method
//main method to initiate the task
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("1. Input Restricted Queue");
System.out.println("2. Output Restricted Queue");
int ch=sc.nextInt();
int d=0;
switch(ch)//performs operation according to choice of user
{
case 1:
while(d!=3)
{
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Exit");
d=sc.nextInt();
switch(d)
{
case 1:
System.out.println("Enter the value");
int m=sc.nextInt();
addfront(m);
break;
case 2:
System.out.println("1. Front");
System.out.println("2. Rear");
95 | Page
int n=sc.nextInt();
if(n==1)
{
System.out.println(popfront());
}
else
{
System.out.println(poprear());
}
break;
case 3:
System.out.println("Exits");
break;
default:
System.out.println("Wrong Choice");
} }
break;
case 2:
while(d!=3)
{
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Exit");
d=sc.nextInt();
switch(d)
{ case 2:
System.out.println(popfront());
break;
case 1:
System.out.println("1. Front");
96 | Page
System.out.println("2. Rear");
int n=sc.nextInt();
System.out.println("Enter the value");
int m=sc.nextInt();
if(n==1)
{
addfront(m); }
else
{ addrear(m); }
break;
case 3:
System.out.println("Exits");
break;
default:
System.out.println("Wrong Choice");
} }
break;
default:
System.out.println("Wrong Choice");
}//end of switch
}//end of method
}//end of class

97 | Page
OUTPUT
1. Input Restricted Queue
2. Output Restricted Queue
1
1. Push
2. Pop
3. Exit
1
Enter the value
6
1. Push
2. Pop
3. Exit
3Exits

QUESTION 20
98 | Page
Write a program to implement Circular QUEUE using array

ALGORITHM
Algorithm for addElement() function
1. Start
2. Check if fr=0 and re=size-1 or fr=re=-1 then print queue is full
3. Check if fr=-1 the set fr=re=0 and arr[fr]=val
4. Check if re=size-1 and fr!=0 then set arr[re]=val
5. Else increase re by 1 and set arr[re]=val
6. End
Algorithm for removeElement() function
1. Start
2. Check if fr=-1 then print queue is empty
3. Set x=arr[fr] and set arr[fr]=-1
4. Check if fr=size-1 then set fr=0
5. Else increase fr by 1
6. Return the value of x
7. End
Algorithm for display() function
1. Start
2. Check if fr=-1 then print queue is empty
3. Check if fr<=re, then repeat steps 3.1 to 3.2 from fr to re increasing step by 1
3.1. Print the I th element of array
3.2. End of loop
4. Else repeat steps 4.1 to 4.2 from fr to size-1 increasing step by 1
4.1. Print the I th element of array
4.2. End of loop
5. End
Algorithm for main() function
1. Start
2. Set c=0
3. Repeat steps 3.1 to 3. while c!=4
4. Store the choice of the user to add remove or display in c
5. Check the value of c and perform the following steps
5.1. If c=1 then input the value from the user and call the method addElement()
5.2. If c=2 call the method removeElement()
5.3. If c=3 call the method display()
5.4. If c=4 then exit
6. End
PROGRAM CODE
import java.util.*;

99 | Page
class cirQueue
{
int arr[],size,fr,re;
//default constructor to initialize the values
public cirQueue()
{
size=5;
arr=new int[size];
fr=re=-1;
}//end of method
//parametrized constructor to initialize the values
public cirQueue(int s)
{
size=s;
arr=new int[size];
fr=re=-1;
}//end of method
//method to add elements into circular queue
public void addElement(int val)
{
if(fr==0&&fr==(size-1)||re==fr-1)
{
System.out.println("Queue is full");
return;
}
else
if(fr==-1)
{
fr=re=0;
arr[re]=val;
100 | Page
}
else
if(re==(size-1)&&fr!=0)
{
re=0;
arr[re]=val;
}
else
{
re++;
arr[re]=val;
}
}//end of method
//method to remove elements from circular queue
public int removeElement()
{
if(fr==-1)
{
System.out.println("Queue is empty");
return -999;
}
int x=arr[fr];
arr[fr]=-1;
if(fr==re)
{
fr=re=-1;
}
else
{
if(fr==size-1)
101 | Page
fr=0;
else
fr++;
}
return x;
}//end of method
//method to display elements from circular queue
public void display()
{ if(fr==-1)
{System.out.println("Queue is empty");
return; }
if(fr<=re)
{ for(int i=fr;i<=re;i++)
{ System.out.print(arr[i]+",");
} }
else
{ for(int i=fr;i<size;i++)
{ System.out.print(arr[i]+","); }
for(int i=re;i<size;i++)
{ System.out.print(arr[i]+",");
} }
System.out.println();
}//end of method
//main method to initiate the task
public static void main(int n)
{ Scanner sc=new Scanner(System.in);
cirQueue q1=new cirQueue(n);
int c=0;
while(c!=4)//loop to perform the task
{ System.out.println("1. Add elements to queue");
102 | Page
System.out.println("2. Remove elements from queue");
System.out.println("3. Display");
System.out.println("4. Exit");
c=sc.nextInt();
switch(c)
{ case 1:
System.out.println("Enter the value");
q1.addElement(sc.nextInt());
break;
case 2:
System.out.println(q1.removeElement());
break;
case 3:
q1.display();
break;
case 4:
System.out.println("Program exits");
break;
default:
System.out.println("Enter choice properly");
}
}//end of loop
}//end of method
}//end of class

103 | Page
OUTPUT
1. Add elements to queue
2. Remove elements from queue
3. Display
4. Exit
1
Enter the value
8
1. Add elements to queue
2. Remove elements from queue
3. Display
4. Exit
2
8
1. Add elements to queue
2. Remove elements from queue
3. Display
4. Exit
4Program exits

QUESTION 21
Write a program to add and delete elements from any position in a LINKED LIST
104 | Page
ALGORITHM
Algorithm for addatbeg() function
1. Start
2. Declare a new node n with val
3. Set node t= root
4. Check if root= null then set root=n
5. Else set the node of n as t and root as n
6. End
Algorithm for addatend() function
1. Start
2. Declare a new node n with val
3. Set node t= root
4. Repeat steps 4.1 to 4.2 while the node of t != null
4.1. Set t=t.getnode()
4.2. End of loop
5. Set the node of t as n
6. End
Algorithm for countnodes() function
1. Start
2. Set t= root
3. Check if the node part of t is null then retun 0
4. Else set c=0 and repeat steps 4.1 to 4.3 while t!=null
4.1. Set t=t.getnode()
4.2. Increase c by 1
4.3. End of loop
5. Return the value of c
6. End
Algorithm for addatpos() function
1. Start
2. Set t=root
3. Declare a new node n with val
4. Check if root=null or c=1 then call addatbeg() function
5. Check if c=total no of nodes then call addatend()function
6. Check if c>total no of nodes then print the specified position does not exist
7. Else set d=1 and repeat steps 7.1 to while t!=null
7.1. Set t=t.getnode()
7.2. Check if d=c then set the node part of n as node part of t and node part t as n
7.3. Increase d by 1

105 | Page
7.4. End of loop.
8. End
Algorithm for delfrompos() function
1. Start
2. Set p= root
3. Check if root is empty then print list is empty
4. If c=1 then set p =p.getnode() and set root =p
5. If c>total no.of nodes and c!=total no. of nodes+1 then print specified position does
not exist
6. Else set node t=p, set d=0 and repeat steps 6.1 to 6.4 while the condition is true
6.1. Set t=p and p=p.getnode()
6.2. Check if d=c-1 then set node of t as p
6.3. Increase d by 1
6.4. End of loop
7. Set root =t
8. End
Algorithm for display() function
1. Start
2. Set t=root
3. Repeat steps 3.1 to 3.2 from 0 to total no. of nodes-1 increasing step by 1
3.1. Print the value of the nodes
3.2. End of loop
4. End

PROGRAM CODE
class node
{

106 | Page
private int info;
private node next;
//default constructor
public node()
{
info=0;
next=null;
}//end of method
//parametrized constructor
public node(node n)
{
info=n.info;
next=null;
}//end of method
//parametrized constructor
public node(int x)
{
info=x;next=null;
}//end of method
//method to set values
public void setinfo(int x)
{
info=x;
}//end of method
//method to get the values
public int getinfo()
{
return info;
}//end of method
//method to set node
107 | Page
public void setnode(node m)
{
next=m;
}//end of method
//method to get node
public node getnode()
{
return next;
} //end of method
}//end of class
import java.util.*;
class linklist
{
node root;
//default constructor to initialize the variables
public linklist()
{
root=null;
}//end of method
//parametrized constructor to initialize the variables
public linklist(node n)
{
root =n;
}//end of method
//method to add values at beginning
public void addatbeg(int val)
{
node n=new node(val);
node t=root;
if(root==null)
108 | Page
{
root=n;
}
else
{
n.setnode(t);
root=n;
}
}//end of method
//method to delete values from end
public void addatend(int val)
{
node n=new node(val);
node t=root;
while(t.getnode()!=null)
{
t=t.getnode();
}
t.setnode(n);
}//end of method
//method to count the number of nodes
public int countnodes()
{
node t=root;
if(t.getnode()==null)
return 0;
else
{
int count=0;
while(t!=null)
109 | Page
{
t=t.getnode();
count++;
}
return count;
}
}//end of method
//method to add node at a particular position
public void addatpos(int c,intval)
{
node t=root;
node n=new node(val);
if(root==null||c==1)
{
addatbeg(val);
}
else
if(c==countnodes())
{
addatend(val);
}
else
if(c>countnodes())
{
System.out.println("Specified position does not exist");
}
else
{
int d=1;
while(t!=null)
110 | Page
{
t=t.getnode();
if(d==c)
{
n.setnode(t.getnode());
t.setnode(n);
break;
}
d++;
}
}
}//end of method
//method to delete nodes from a specified position
public void delfrompos(int c)
{
node p=root;
if(root==null)
{
System.out.println("List is empty");
}
else
if(c==1)
{
p=p.getnode();
root=p;
}
else
if(c>countnodes()&&c!=countnodes()+1)
{
System.out.println("Specified position does not exist");
111 | Page
}
else
{
node t=p;;
int d=0;
while(true)
{
t=p;p=p.getnode();
if(d==c-1)
{
t.setnode(p);
break;
}
d++;
}
root=t;
}
}//end of method
//method to display the nodes
public void display()
{
node t=root;
for(int i=0;i<countnodes();i++)//loop to display the nodes
{
System.out.println(t.getinfo());
}//end of loop
}//end of method
public void main()
{
112 | Page
Scanner sc=new Scanner(System.in);
System.out.println("1. Add");
System.out.println("2. Delete");
int ch=sc.nextInt();
System.out.println("Enter position");
int pos=sc.nextInt();
switch(ch)//performs the operation
{
case 1:
System.out.println("Enter value");
addatpos(pos,sc.nextInt());
break;
case 2:
delfrompos(pos);
break;
case 3:
System.out.println("Wrong choice");
}
}//end of method
}//end of class

113 | Page
OUTPUT
1. Add
2. Delete
1
Enter position
2
Enter value
36

QUESTION 22
114 | Page
Write a program to input a number in decimal form and convert it into binary, octal and
hexadecimal using RECURSION.

ALGORITHM
Algorithm for toBinary() function
1. Start
2. Check if n>=2 then call the function toBinary() recursively by reducing n by ½
3. Print the value of n%2
4. End
Algorithm for toOctal() function
1. Start
2. Check if n>=8 then call the function toOctal() recursively by reducing n by 1/8
3. Print the value of n%8
4. End
Algorithm for toHexadecimal() function
1. Start
2. Initialize a character array ch with{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}
3. Check if n>=16 then call the function toHexadecimal() recursively by reducing n by
1/16
4. Print the value of the n%16th index of the array ch
5. End
Algorithm for main() function
1. Start
2. Input the number from the user and store it in m
3. Call the functions toBinary(),toOctal(),toHexadecimal() with m as parameter
4. End

PROGRAM CODE
import java.util.*;
115 | Page
class conversion
{
//method to convert decimal to binary
public void toBinary(int n)
{
if(n>=2)
{
toBinary(n/2);
}
System.out.print(n%2);
}//end of method
//method to convert decimal to octal
public void toOctal(int n)
{
if(n>=8)
{
toOctal(n/8);
}
System.out.print(n%8);
}//end of method
//method to convert decimal to hexadecimal
public void toHexadecimal(int n)
{
char ch[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
if(n>=16)
{
toHexadecimal(n/16);
}
System.out.print(ch[n%16]);
}//end of method
116 | Page
//main method to initiate the task
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int m=sc.nextInt();
toBinary(m);
System.out.println();
toOctal(m);
System.out.println();
toHexadecimal(m);
}//end of method
}//end of class

117 | Page
OUTPUT
Enter a number
458
111001010
712
1CA

Enter a number
24
11000
30
18

118 | Page
QUESTION 23
Write a program to implement binary search using RECURSION

ALGORITHM
Algorithm for accept() function
1. Start
2. Repeat steps 2.1 to 2.2 from 0 to n-1increasing step by 1
2.1. Input the value fro user and store it in ith index of the array arr
2.2. End of loop
3. Input the value to be searched from the user and store it in s
4. End
Algorithm for binary() function
1. Start
2. Set mid=(l+u)/2
3. Check if l<=u and check if arr[mid]=s then return mid else return -1
4. If arr[mid]<s then call the function recursively with parameters as mid ,u
5. If arr[mid]>s then call the function recursively with parameters as l,mid
6. End
Algorithm for main() function
1. Start
2. Create a object b
3. Call the function accept()
4. Call the function binary with 0,l-1 and check if it is not equal to -1 then print
searched element found else searched element not found
5. End

119 | Page
PROGRAM CODE
import java.util.*;
class binary
{
int arr[];int n;int s;
//parametrized constructor to initialize the variables
public binary(int m)
{
n=m;
arr=new int[n];
}//end of method
//method to accept values into array
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter elements to array");
for(int i=0;i<n;i++)//loop to input elements into array
{
arr[i]=sc.nextInt();
}//end of loop
System.out.println("Enter value to be searched");
s=sc.nextInt();
}//end of method
//method to perform binary search
public int binary(int l,int u)
{
int mid=(l+u)/2;
if(l<=u)
{

120 | Page
if(arr[mid]==s)
return mid;
else if(arr[mid]<s)
return binary(mid+1,u);
else if(arr[mid]>s)
return binary(l,mid-1);
}
return -1;

}//end of method
//main method to execute the above task
public static void main(int l)
{
binary b=new binary(l);
b.accept();
if(b.binary(0,l-1)!=-1)
{
System.out.println("Searched element found at position "+b.binary(0,l-1));
}
else
{
System.out.println("Searched element not found");
}
}//end of method
}//end of class

121 | Page
OUTPUT

Enter elements to array


9
10
25
36
45
Enter value to be searched
45
Searched element found at position 4

QUESTION 24
122 | Page
A super class Account contains employee details and a sub class Simple calculates the
employee’s simple interest. The details of the two classes are given below:
Class name: Account
Data Members:
Name : stores the employee name
Pan : stores the employee PAN number
Principal : stores the principal amount
acc_no : stores the employee bank account number
Member functions:
account(….):parametrized constructor to assign value to data members
void display(): to display the employee details
Class name: Simple
Data Members:
time: stores the time duration
rate: stores the rate of interest
interest: stores the simple interest
Member functions:
Simple(…..): parametrized constructor to assign value to data members of both the classes
void calculate(): calculates the simple interest as (Principal x rate x time)/100
void display(): display the employee details along with rate, time and interest
Using the concept of inheritance, specify the class Account and Simple giving details of
constructor and functions. The super class and main function has to be written.

ALGORITHM
Algorithm for the class Account
Algorithm for display() function
1. Start
2. Print the name, pan, principal, account no. of the user.
3. End
Algorithm for the class Simple
Algorithm for calculate() function
1. Start
2. Calculate and store interest as principal*rate*time/100
3. End
Algorithm for display() function
1. Start
2. Call the super class’s display() function
3. Print the rate, time, interest of the user
4. End

PROGRAM CODE

123 | Page
class Account
{
String name;
long pan;
double principal;
long acc_no;
//parametrized constructor to initialize the values
public Account(String n,longp,doublepr,long ac)
{
name=n;
pan=p;
principal=pr;
acc_no=ac;
}//end of method
//method to display the details of employee
public void display()
{
System.out.println("Name: "+name);
System.out.println("PAN: "+pan);
System.out.println("Principal: "+principal);
System.out.println("Account no.: "+acc_no);
}//end of method
}//end of class
class Simple extends Account
{ int time;float rate;
double interest;
//parametrized constructor to initialize the values
public Simple(String n,longp,doublepr,longac,intt,float r)
{
super(n,p,pr,ac);
124 | Page
time =t;rate=r;
interest=0.0d;
}//end of method
//method to calculate the interest
public void calculate()
{
interest=(principal*rate*time)/100;
}//end of method
//method to display the details of employee
public void display()
{
super.display();
System.out.println("Rate: "+rate);
System.out.println("Time: "+time);
System.out.println("Interest: "+interest);
}//end of method
}//end of class
class exec
{
//main method to execute task
public static void main()
{
Simple s1=new Simple("F",123456,20.15,789456,3,8);
s1.calculate();
s1.display();
}//end of method
}//end of class

125 | Page
OUTPUT
Name: RAJ SHARMA
PAN: 79842
Principal: 20000.15
Account no.: 789456
Rate: 8.0
Time: 3
Interest: 4800.036

QUESTION 25
126 | Page
An interface shape is defined with a method area() which returns the area of the
implementing shape. Create the classes circle and rectangle which implements the interface
shape. These classes have attributes which reflect their dimensions which are set by their
constructors. The details of the members of the interface and both the classes are given
below:
Interface name: Shape
Member Functions
double area(): returns the area of implementing shape
Class name circle
Data members
radius: to store radius of the circle
Member fuctions
Circle(int r): parametrized constructor to initialize radius=r
double area(): to calculate area of the circle
Class name: Rectangle
Data members
length: to store length of the rectangle
breadth: to store breadth of the rectangle
Member functions
Rectangle(int l,int b):parametrized constructor to initialize length=l,breadth=b
double area(): to calculate area of the rectangle
Define the interface shape. Using the concept of inheritance , specify the classes Circle and
Rectangle giving details of their constructors and double area() respectively.

ALGORITHM
Algorithm for rectangle class
Algorithm for area() function
4. Start
5. Calculate and return the value of area of rectangle as length*breadth
6. End
Algorithm for circle class
Algorithm for area()function
1. Start
2. Calculate and return the value of area of circle as 3.14*radius*radius
3. End
Algorithm for area class
Algorithm for main() function
1. Start
2. Print the area of circle after inputting the radius from the user
3. Print the area of rectangle after inputting the length and breadth from the user
4. End

127 | Page
PROGRAM CODE
interface shape
{
double area();
}//end of interface
class circle implements shape
{
double radius;
//default constructor to initialize the variables
public circle(double r)
{
radius =r;
}//end of method
//method to calculate area
public double area()
{
return 3.14*radius*radius;
}//end of method
}//end of class
class rectangle implements shape
{
double length,breadth;
//default constructor to initialaize the variables
public rectangle(double l,double b)
{
length=l;
breadth=b;
}//end of method
//method to calculate area

128 | Page
public double area()
{
return length*breadth;
}//end of method
}//end of class
import java.util.*;
class area
{
//main method to execute the task
public static void main()
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter the radius of circle");


circle c1=new circle(sc.nextDouble());
System.out.println("The area of circle: "+c1.area());
System.out.println("Enter the length and breadth of rectangle");
rectangle r1=new rectangle(sc.nextDouble(),sc.nextDouble());
System.out.println("The area of rectangle: "+r1.area());
}//end of method
}//end of class

129 | Page
OUTPUT

Enter the radius of circle


23.4
The area of circle: 1719.3383999999999
Enter the length and breadth of rectangle
16.2
25.1
The area of rectangle: 406.62

130 | Page

You might also like