Computer Project (2)
Computer Project (2)
I am deeply indebted to the Almighty who guided me throughout the project work
and blessed me for the successful completion of this study.
My beloved parents were always ready to help and encourage me in this endeavor.
My gratitude to them is beyond words and my sincere thanks to the respondents
for their sincere participation.
CONTENTS
Sl.No Name Date of submission Page No.
1 Program: 1 1-2
2 Program: 2 3-5
3 Program: 3 6-8
4 Program: 4 9-11
5 Program: 5 12-14
6 Program: 6 15-17
7 Program: 7 18-21
8 Program: 8 22-23
9 Program: 9 24-27
10 Program: 10 28-31
11 Program: 11 32-34
12 Program: 12 35-37
13 Program: 13 38-40
14 Program: 14 41-43
15 Program: 15 44-46
16 Program: 16 47-50
17 Program: 17 51-54
18 Program: 18 55-59
19 Program: 19 60-63
20 Program: 20 64-65
Question:1
Write a Program in java to print all the Twin Prime numbers within a given range.
Note: Twin Prime numbers are a pair of numbers which are both prime and their difference is 2.
Example: Twin Prime numbers in the range 1 to 100 are:
(3,5),(5,7),(11,13),(17,19),(29,31),(41,43),(59,61),(71,73).
Programming Code:
import java.io.*;
class TwinPrimeRange
{
boolean isPrime(int n)// function for checking prime
{
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
return true;
else
return false;
}
public static void main(String args[])throws IOException
{
TwinPrimeRange ob=new TwinPrimeRange();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print("Enter the lower range:");
int p=Integer.parseInt(br.readLine());
System.out.print("Enter the upper range:");
1
int q=Integer.parseInt(br.readLine());
if(p>q)
System.out.println("Invalid Range!");
{
System.out.println("The Twin Prime Numbers within the given range are:");
for(int i=p;i<=(q-2);i++)
{
if(ob.isPrime(i)==true&&ob.isPrime(i+2)==true)
{
System.out.print("("+i+","+(i+2)+")");
}
}
}
}
}
Output:
Enter the lower range: 1
Enter the upper range: 200
The Twin Prime Numbers within the given range are:
(3,5)(5,7)(11,13)(17,19)(29,31)(41,43)(59,61)(71,73)(101,103)(107,109)(137,139)(149,151)(179,181)
(191,193)(197,199)
2
Question: 2
Write a Program in java to fill a square matrices of size ‘n*n’ in a spiral fashion(from the inside)with the
natural numbers from 1 to n*n, taking ‘n’ as input.
For example : if n=5,then n*n=25, hence the array will be filled as given below]
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
Programming Code:
import java.io.*;
class spiral
{
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader bf=new BufferedReader(isr);
System.out.println("Enter the number of elements");
int n=Integer.parseInt(bf.readLine());
int a[][]=new int[n][n];
int k=n*n,c1=0,c2=n-1,r1=0,r2=n-1;
while(k>=1)
{
for(int i=c1;i<=c2;i++)
{
a[r1][i]=k--;
}
for(int j=r1+1;j<=r2;j++)
{
3
a[j][c2]=k--;
}
for(int i=c2-1;i>=c1;i--)
{
a[r2][i]=k--;
}
for(int j=r2-1;j>=r1+1;j--)
{
a[j][c1]=k--;
}
c1++;
c2--;
r1++;
r2--;
}
/*Printing thw circular matrix*/
System.out.println("The spiral matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}
4
Output:
The spiral matrix is:
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
5
Question: 3
A sentence in the Special Fashion can be printed by taking two integers (not beyond total number of
words in the sentence or less than l ). These integers tell the word number of the sentence. Replace only
'those words present at those given integer according to the English Alphabets. If both the integers arc
same then replace only one word, Let us consider the following examples:
Input sentence: He has good Books.
Input integers: 2,4
Output sentence: He ibt good Cpplt
(i.e., word number 2 and 4 have been replaced by the next characters in a circular fashion)
Input sentence: Time and Tide waits for none
Input integers: 3,3
Output sentence: Time and ujef waits for none.
Write a case sensitive program that reads a sentence from console (the characters of a sentence may be
capital or small or mixed) and two positive integers and output the same sentence after replacing those
words present at those given integer places by the next character in a circular fashion according to the
English Alphabets.
In the first example given above, word number 2, i.e. "has" is replaced by next characters and hence it
becomes "ibt". Similarly, word number 4,i.e."Books" is replaced by next characters and hence it becomes
"cpplt".
Programming Code:
import java.io.*;
class special_fashion
{
String repChar(String s)//function doing the work of replacing characters
{
int I=s.length(),a=0;
char ch;
String res="";
for(int i=0;i<1;i++)
{
ch=s.charAt(i);//extracting characters one by one
a=ch+I;//storing ASCII values after adding I to the current character
if((ch=='z')||(ch=='Z'))
6
{
a=a-26;
}
res=res+(char)a;//finally addingthe changed character to the new string
}
return res;
}
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader bf=new BufferedReader(isr);
special_fashion ob=new special_fashion();
System.out.println("Enter any sentence:");//inputing the sentence
String s=bf.readLine();
String ans="";//string variable to store the final result
String word[]=s.split("[.]+");//saving the words of the sentence in the array using split()
int c=word.length;
System.out.print("Enter the 1st word numbers:");
int x=Integer.parseInt(bf.readLine());
System.out.println("Enter the 2nd word number:");
int y=Integer.parseInt(bf.readLine());
if((x<1)||(y<1)||(x>1)||(y>c))//checking whether integers inpuuted are accepatable or not
{
System.out.println("sorry! The word numbers inputted are out of range");
}
else
{
if(x!=y)
{
word[y-1]=ob.repChar(word[y-1]);//sending the wods to the repChar() function
7
}
word[x-1]=ob.repChar(word[x-1]);
for(int i=0;i<c;i++)
{
ans=ans+word[i]+"";
}
System.out.print("output="+ans.trim()+".");
}
}
}
Output:
Enter any sentence:
i love stpius
Enter the 1st word numbers: 0
Enter the 2nd word number: 1
sorry! The word numbers inputted are out of range
8
Question: 4
Write a program in java to fill a square matrix of size ‘n*n’ in a circular fashion(clockwise)with natural
numbers from 1 to n*n, taking n as input.
For example: if n=4,then n*n=16,hence the array will be filled as given below
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Programming Code:
import java.io.*;
class matirx
{
public static void main(String args[])throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader bf=new BufferedReader(isr);
System.out.println("Enter a number:");
int n=Integer.parseInt(bf.readLine());
int A[][]=new int[n][n];
int K=1,c1=0,c2=n-1,r1=0,r2=n-1;
while(K<=n*n)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=K++;
}
for(int j=r1+1;j<=r2;j++)
9
{
A[j][c2]=K++;
}
for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=K++;
}
for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=K++;
}
c1++;
c2--;
r1++;
r2--;
}
System.out.println("The Circular Matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
}
}
10
Output:
Enter a number:
4
The Circular Matrix
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
11
Question 5:
A simple encryption system uses a shifting process to hide a message. The value of the shift can be in the
Text: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T
First an extra space is added to the end of the string to make things little more difficult, spaces within the
original text are replaced with QQ before the text is encrypted. Double Q(QQ) was selected because no
English word ends in Q or contains QQ.
Additionally the coded message is printed in blocks of six characters separated by spaces. The last block
might not contain six characters. Write a program that takes the coded text (less than 100 characters), the
shift value and prints the decoded original text . Your program must reject any non-valid value for shift
and display an error message "INVALID SHIFT VALUE”). Assume all characters are upper case. Test
your program for the following data and some data that you have coded, using the rules given above:
SAMPLE DATA:
1.INPUT:
CODED TEXT:”IJHINBY LKKQCH HYLKK"
SHIFT:7
OUTPUT:
DECODED TEXT:ANOTHER VALUE
2.INPUT:
CODED TEXT:”RUIJGG EVGGBK SAGG"
SHIFT: 11
OUTPUT:
DECODED TEST:BEST OF LUCK
3.INPUT:
CODED TEXT:”DKSMMW NAMMUK QMM"
SHIFT:29
OUTPUT:
INVALID SHIFT VALUE
Programming Code:
import java.io.*;
public class decoder
{
12
public static void main (String args[])throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.print ("Enter coded text:");
String s=bf.readLine();
int i=s.length();
s=s.toUpperCase();// converting the coded text into UpperCase
s=s+" ";//adding a space at the end
if(i>=100)//checking whether length of inputted code is less than 100
System.out.print(" !!!INVALID LENGTH");
else
{
System.out.print("Enter the shift value:");
int shift=Integer.parseInt(bf.readLine());
if(shift<=1||shift>=26)//checking whether shift value is between 1 and 26
System.out.print("INVALID SHIFT");
else
{
int a,b;
char ch1,ch2;
String dec="";//new string for storing the decoded text
for(int I=0;I<1;I++)
{
ch1=s.charAt(I);//extracting characters one by one
ch2=s.charAt(I+1);//extracting the next character
/*Below we are adding shift value to the characters
•if ch1='A' and shift =7,
•then ch1 +shift-1 will give as: 'A'+7-1=65+7-l=71
•which is the ASCII value of 'G' */
a=ch1+shift-1;
13
//storing ASCII values after adding shift to the current characters
b=ch2+shift-1;
//storing ASCII values after adding shift to the next character
/*If the current charater and the next character are both 'Q' then we have a 'space'
*hence the ASCII value should be 32
*/
if((char)a=='Q'&&(char)b=='Q')
{
a=32;
I++;
}
/* if ASCII value after adding the shift becomes more than 90,
*then we subtract 26 from it,to make it circular,
*eg. 'U'+7-1=85+7-1=91, but we want'A'whose ASCII value is 65
*so 91-26 will give us 65 */
if(a>90)
a=a-26;
if(ch1!='0')
dec=dec+(char)a;//finally adding the decoded character to the new string
}
System.out.print("Decoded text"+dec);
}
}
}
}
Output:
Enter coded text: UHINBYLKKQCHHYLKK
Enter the shift value: 27
INVALID SHIFT
14
Question: 6
The International Mobile Station Equipment Identity or IMEI is a number, usually unique, to identify
mobile phones, as well as some satellite phones. It is usually found printed inside the battery
compartment of the phone.
The IMEI number is used by a GSM network to identify valid devices and therefore can be used for
stopping a stolen phone from accessing tat network.
The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin,model and
serial number of the device.
The IMEI is validated in three steps:
1. Starting from the right,double every other digit(e.g, 7 becomes 14).
2. Sum the digits(e.g, 14=1+4)
3. Check if the sum is divisible by 10
For example:
If input is IMEI=490154203237518
IMEI 4 9 0 1 5 4 2 0 3 2 3 7 5 1 8
Double 4 18 0 2 5 8 2 0 3 4 3 14 5 2 8
every other
digits
15
int a=0;
while(n>0)
{
a=a+n%10;
n=n/10;
}
return a;
}
public static void main (String args[])throws IOException
{
IMEI ob=new IMEI();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a 15 digit IMEI code:");
long n=Long.parseLong(bf.readLine());
String s=Long.toString(n);
int1=s.length();
if(1!=15)
System.out.println("Output:Invalid Input");
else
{
int d=0,sum=0;
for(int i=15;i>=i;i++)
{
d=(int)(n%10);
if(i%2==0)
{
d=2*d;
}
sum=sum+ob.sumDig(d);
n=n/10;
16
}
System.out.println("Output:sum="+sum);
if(sum%10==0)
System.out.println("valid IMEI code:");
else
System.out.println("Invalid IMEI code");
}
}
}
Output:
Enter a 15 digit IMEI code: 79927398713
Output: Invalid Input
Enter a 15 digit IMEI code: 490154203237518
Output: The IMEI number is valid.
17
Question 7:
Write a program to declare a square matrix A[][] of (M X M) where ‘M’ is the number of rows and the
number of columns such that M must be greater than 2 and less than 20. Allow the user to input integers
into this matrix. Display appropriate error message for an invalid input. Perform the following tasks:
(a)Display the input matrix.
(b)Create a mirror image matrix
(c)Display the mirror image matrix.
Test your program with the simple data and some random data:
Example 1
INPUT :M=3
4 6 12
8 2 14
6 1 3
OUTPUT:
ORIGINAL MATRIX
4 6 12
8 2 14
6 1 3
MIRROR IMAGE MATRIX
12 16 4
14 2 8
3 1 6
Example 2:
INPUT :M=22; OUTPUT:SIZE OUT OF RANGE
Programming Code:
import java.io.*;
class mirror
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
18
System.out.print("Enter the order of the matrix");
int m=Integer.parseInt(br.readLine());
if(m>2&& m<20)//checking given condition
{
int A[][]=new int[m][m];
System.out.println("Inputting the elements in the matrix");
System.out.println("******************");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print("Enter the elements at["+i+"]"+j+"]:");
A[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("******************");
System.out.println("The original matrix");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
} //creating the image matrix
int B[][]=new int[m][m];
for(int j=m-1;j>0;j--)
{
int k=0;
for(int i=m-1;j>0;j--)
19
{
B[i][k]=A[i][j];
k++;
}
}
//Printing both the matrix
System.out.println("******************");
System.out.println("The mirror image is");
System.out.println("******************");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(B[i][j]+"\t");
}
System.out.println();
}
}
else
System.out.println("Output:size out of range");
}
}//End of if
Output:
Enter the order of the matrix: 4
Inputting the elements in the matrix
******************
Enter the elements at[0][0]:1
Enter the elements at[0][1]:2
Enter the elements at[0][2]:3
Enter the elements at[0][3]:4
20
Enter the elements at[1][0]:5
Enter the elements at[1][1]:6
Enter the elements at[1][2]:7
Enter the elements at[1][3]:8
Enter the elements at[2][0]:9
Enter the elements at[2][1]:10
Enter the elements at[2][2]:11
Enter the elements at[2][3]:12
Enter the elements at[3][0]:13
Enter the elements at[3][1]:14
Enter the elements at[3][2]:15
Enter the elements at[3][3]:16
******************
The original matrix
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
******************
The mirror image is
******************
4 3 2 1
8 7 6 5
12 11 10 9
16 15 14 13
21
Question 8:
Write a program in java to input a number and check whether it is a keith number or not.
Note: A keith number is an integer N with 'd' digits with the following property:
If a Fibonacci-like sequence (in which each term in the sequence is the sum of the 'd' previous tenns) is
formed, with the first 'd' terms being the decimal digits of the number N, then N itself occurs as a term
in the sequence.
1 ,9.7,17,33,57 107,197,
some keith numbers are:14,19,28,47,61,75,197,742,1104,1537………….
Programming Code:
import java.io.*;
class keith
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number:");//inputting the number
int n=Integer.parseInt(br.readLine());
int copy=n;
String s=Integer.toString(n);
int d=s.length();//finding the length of digits(d) in the number
int arr[]=new int[n];// array for storing the terms of the series
for(int i=d-1;i>=0;i--)
{
arr[i]=copy%10;//storing the digits of the number in the array
copy=copy/10;
}
int i=d,sum=0;
while(sum<n)//finding the sum till it is less than the number
{
sum=0;
22
for(int j=1;j<=d;j++)//loop for generating and adding the previous 'd' terms
{
sum=sum+arr[i-j];
}
arr[i]=sum;//Storing the sum in the array
i++;
}
/*when the control comes out of the while loop,either the
Sum is equal to the number or greater than it*/
if(sum==n)//if sum is equal to the numbcr,then it is a keith number
System.out.println("The number is a keith number");
else
System.out.println("The number is not a keith number");
}
}
Output:
Enter the number:197
The number is a keith number
23
Question 9:
Write a program to declare a square matrix A [ ][ ] of order 'n'. Allow the user to input positive integers
into this matrix. Perform the following tasks on the matrix:
[Note: A saddle point is an element of the matrix such that it is minimum clement for the row to which it
belongs and the maximum element for the column to which it belongs. Saddle point for a given matrix is
always unique.]
4 5 6
7 8 9
5 1 3
Saddle point = 7 because it is the minimum of row 2 and maximum element column 1.
Programming Code:
import java.io.*;
class saddle
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the order of the matrix");
int n=Integer.parseInt(br.readLine());
int A[][]=new int[n][n];
System.out.println("Inputting the elements in the matrix");
System.out.println("****************");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
24
{
System.out.print("Enter the elements at["+i+"]"+j+"]:");
A[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("****************");
System.out.println("The original matrix is");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
int max,min,x,f=0;
for(int i=0;i<n;i++)
{
min=A[i][0];
x=0;
for(int j=0;j<n;j++)
{
if(A[i][j])
x=j;
}
}
max=A[0][x];
for(int k=0;k<n;k++)
{
if(A[k][x]>max)
{
max=A[k][x];
25
}
}
if(max==min)
{
System.out.println("****************");
System.out.println("Saddle point"+max);
System.out.println("****************");
f=1;
}
}
if(f==0)
{
System.out.println("****************");
System.out.println("no saddle point");
System.out.println("****************");
}
}
Output:
Enter the order of the matrix: 3
Inputting the elements in the matrix
******************
Enter the elements at[0][0]:1
Enter the elements at[0][1]:2
Enter the elements at[0][2]:3
Enter the elements at[0][3]:4
Enter the elements at[1][0]:5
Enter the elements at[1][1]:6
Enter the elements at[1][2]:7
26
Enter the elements at[1][3]:8
Enter the elements at[2][0]:9
Enter the elements at[2][1]:10
Enter the elements at[2][2]:11
******************
The original matrix is
4 5 6
7 8 9
5 1 3
******************
Saddle point is 7
27
Question: 10
A sequence of Fibonacci Strings is generated as follows:
A,b,ba,bab,babba,babbabab,………………..n terms.
Design a class FiboString to generate Fibonacci strings. Some of the members of the class are given
below:
Member functions/methods:
FiboString() : constructor to assign x=”a”,y=”b”,z=”ba”
Void accept() : to accept the number of terms 'n'
Void generate() : to generate and print the fibonacci strings.
The sum of('+'i.e.concatenation) first two strings is the third string.Eg."a" is the first string,"b" is the
second string then the third string will be "ba" and fourth will be "bab" and so on. Specify the class
FiboString, giving details of the constructor(),void accept()and void generate().Define the main()function
to create an object and call the functions accordingly to enable the task.
Programming code:
import java.io.*;
class FiboString
28
String x,y,z;
int n;
FiboString()//constructor
x="a";
y="b";
n=Integer.parseInt(bf.readLine());
void generate()
29
System.out.print("\nThe fibanocci string series is:");
System.out.print(x);
System.out.print(x+","+y);
for(int i=3;i<=n;i++)
z=y+x;
System.out.print(","+z);
x=y;
y=z;
30
FiboString ob=new FiboString();
ob.accept();
ob.generate();
Output:
31
Question 11:
An Emirp number is a number which is prime backwards and forwards. Example: 13 and 31 are both
Prime numbers. Thus, 13 is an Emirp number,
Design a class Emirp to check if a given number is Emirp number or not. Some of the members of the
class are given below:
Void isEmirp() : reverse the given number and check if both the original number and the reverse number
are prime, by invoking the function isprime(int) and display the result with an appropriate message.
Specify the class Emirp giving details of the constructor (int), int isprime(int) and void isEmirp().
Define the main () function to create an object and call the methods to check for Emirp number.
Programming Code:
import java.io.*;
class Emirp
int n,rev,f;
Emirp(int nn)
n=nn;
32
rev=0;
f=2;
int isprime(int x)
if(f<=x)
if(x%f!=0)
f++;
isprime(x);
if(f==x)
return 1;
else
return 0;
void isEmirp()
int copy=n,d;
while(copy>0)
33
d=copy%10;
rev=rev*10+d;
copy=copy/10;
int a=isprime(n);
f=2;
int b=isprime(rev);
if(a==1&&b==1)
else
int n=Integer.parseInt(br.readLine());
ob.isEmirp();
Output:
13 is an Emirp number
34
Question: 12
A happy number is a number in which the eventual sum of the square of the digits of the number equal to
1.
Design a class Happy to check if the given number is a happy number. Some of the members of the class
are given below:
Member functions
Void getnum (int nn): to assign the parameter value to the number n=nn
Int sum_sq_digits(int x): returns the sum of the square of the digits of the number x, using the recursive
technique
Void ishappy():checks if the given number is a happy number by calling the function
sum_sq_digits(int)and displays an appropriate message
Specify the class Happy giving details of the constructor (),void getnum(int),int sum_sq_digits(int) and
void ishappy(). Also define a main() function to create an object and call the methods to check for happy
number.
Programming Code:
import java.io.*;
class Happy
35
int n;
Happy()
n=0;
n=nn;
int sum_sq_digits(int x)
if(x==0)
return 0;
else
int d=x%10;
return(d*d+sum_sq_digits(x/10));
void ishappy()
int a=sum_sq_digits(n);
while(a>9)
36
{
a=sum_sq_digits(a);
if(a==1)
else
int n=Integer.parseInt(br.readLine());
ob.ishappy();
Output:
28 is an Happy number
37
Question 13:
ROT13
A/a B/b C/c D/d E/e F/f G/g H/h I/i J/j K/k L/l M/m
N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/w X/x Y/y Z/z
Write a program to accept a plain text of length L, where L mustbe greater than 3 and less than 100.
Test your program with the sample data and some random data:
Example 1:
Example 2:
INPUT:You
Programming Code:
import java.util.*;
class CaesarCipher
void convert(String w)
38
char ch;
int a=0;
String ans="";
for(int i=0;i<w.length();i++)
ch=w.charAt(i);
if(Character.isLetter(ch))
a=ch+13;
a=a-26;
ch=(char)a;
ans=ans+ch;
39
System.out.println("Enter a sentence:");
String s=sc.nextLine();
int L=s.length();
if(L<4||L>99)
System.out.println("INVALID LENGTH");
else
ob.convert(s);
Output:
Enter a sentence:
Enter a sentence:
You
INVALID LENGTH
40
Question14:
A Circular Prime is a prime number that remains prime under cyclic shifts of its digits.when the leftmost
digit is removed and replaced at the end of the remaining string of digits, the generated number is still
prime. The process is repeated util the original number is reached again.
Example:
131
311
113
Test your program with the sample data and some random data.
Programming Code:
import java.util.*;
class CircularPrime
boolean isPrime(int n)
int c=0;
for(int i=1;i<=n;i++)
if(n%i==0)
c++;
if(c==2)
41
return true;
else
return false;
int circulate(int n)
String s=Integer.toString(n);
String p=s.substring(1)+s.charAt(0);
int a=Integer.parseInt(p);
return a;
void isCircularPrime(int n)
int f=0,a=n;
do
System.out.println(a);
if(isPrime(a)==false)
f=1;
break;
a=circulate(a);
42
}
while(a!=n);
if(f==1)
else
System.out.println("Enter a number");
int n=sc.nextInt();
ob.isCircularPrime(n);
Output:
Enter a number
87
87
43
Question 15:
A company manufactures packing cartons in four sizes ,i.e. cartons to accommodate 6 boxes,12 boxes .
24 boxes and 48 boxes. Design a program to accept the number of boxes to be packed (N) by the user
(maximum up to 1000 boxes) and display the break-up of the cartons used in descending order of
capacity (i.e. preference should be given to the highest capacity available, and if boxes left are less than 6,
an extra carton of capacity 6 should be used.) Test your program with sample data and some random data.
Example 1:
INPUT: N= 726
OUTPUT: 48*15= 720 ,6*1= 6
Remaining boxes= 0
Total number of boxes= 726
Total number of cartons= 16
Programming Code:
import java.util.*;
class BoxPacking
int N=sc.nextInt();
if(N<1||N>1000)
System.out.println("INVALID INPUT");
else
44
int cart[]={48,24,12,6};
int copy=N;
int totalCart=0,count=0;
System.out.println("OUTPUT:");
for(int i=0;i<4;i++)
count=N/cart[i];
if(count!=0)
System.out.println("\t"+cart[i]+"\tx\t"+count+"\t="+cart[i]*count);
totalCart=totalCart+count;
N=N%cart[i];
if(N>0)
totalCart=totalCart+1;
else
45
System.out.println("\tTotal number of boxes ="+copy);
Output:
815
OUTPUT:
48 x 16 =768
24 x 1 =24
12 x 1 =12
6 x 1 =6
RemainingBoxes 5x 1=5
46
Question 16:
A composite Magic number is a positive integer which is composite as well as a magic number.
Composite number:
A composite number is a number which has more than two factors.
For example: 10
Factors are: 1,2,5,10
Magic number:
A Magic number is a number in which the eventual sum of the digits is equal to 1.
For Example: 28= 2+8= 10= 1+0=1
Accept two positive integers m and n, where m is less than n as user input. Display the number of
Composite magic integers that are in the range between m and n(both inclusive) and output them along
with frequency, in the format specified below:
Example 1:
INPUT:
m=10
n=10
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
10,28,46,55,64,82,91,100
47
Programming Code:
import java.io.*;
class magiccomposite
{
boolean iscomposite(int n)
{
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count>2)
return true;
else
return false;
}
int sumDig(int n)
{
int s=0;
while(n>0)
{
s=s+n%10;
n=n/10;
}
return s;
}
boolean isMagic(int n)
{
int a=sumDig(n);
48
while(a>9)
{
a=sumDig(a);
}
if(a==1)
return true;
else
return false;
}
public static void main(String args[])throws IOException
{
magiccomposite ob=new magiccomposite();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader bf=new BufferedReader(isr);
System.out.println("Enter the lower limit(m):");
int m=Integer.parseInt(bf.readLine());
System.out.println("Enter the upper limit(n):");
int n=Integer.parseInt(bf.readLine());
int c=0;
if(m<n)
{
System.out.println("The composite magic numbers are:");
for(int i=m;i<=n;i++)
{
if(ob.iscomposite(i)==true&&ob.isMagic(i)==true)
{
if(c==0)
System.out.print(i);
else
System.out.print(","+i);
49
c++;
}
}
System.out.println("The frequency of composite magic numbers is:"+c);
}
else
System.out.println("OUT OF RANGE");
}
}
Output:
Enter the lower limit(m):
1200
Enter the upper limit(n):
1300
The composite magic numbers are:
1207,1216,1225,1234,1243,1252,1261,1270,1288
The frequency of composite magic numbers is:9
50
Question 17:
A super class Detail has been defined to store the detail of a customer. Define a subclass Bill to computer
the monthly telephone charge of the customer as per the given below:
Number of calls
1-100
101-200
201-300
Above 300
Rate
Only Rental charge
60 paisa per call + rental charge
80 paisa per call + rental charge
1 rupee per call + rental charge
The detail of both the classes are given below:
Class Name: Detail
Data members/lnstance variables:
Name: to store the name of the customers.
Address: to store the address of the customers.
telno: to store the phone number of the customer.
Rent: to store the monthly rental charge.
Member function:
Detail(…): parameterized constructor to assign values to data members.
Void show (): to display the detail of the customer.
Class Name: Bill
Data members/Instance variables:
n: to store the number of calls.
amt: to store the amount to be paid by the customer.
Member function:
Bill (...): parameterized constructor to assign values to data members of both classes and to initialize
Amt=0.0.
Void cal (): calculates the monthly telephone charge as per the charge given above.
Void show (): to display the detail of the customer and amount to be paid.
51
Specify the class Detail giving details of the constructor ( ) and void show ( ). Using the concept of
inheritance, specify the class Bill giving details of the constructor ( ),void call ( ) and void show ( ).
The main function and algorithm need not be written.
[Note: We will be writing the main() function also in this program so as to familiarize the students
on how to run programs based on the concept of inheritance.]
Programming Code:
import java.io.*;
class Detail
{
String name,address;
long telno;
double rent;
Detail(String n1,String a1,long t1,double r1)
{
name=n1;
address=a1;
telno=t1;
rent=r1;
}
void show()
{
System.out.println("Name of customer="+name);
System.out.println("Address="+address);
System.out.println("Telephone Number="+telno);
System.out.println("Monthly rental=Rs."+rent);
}
}
class Bill extends Detail
{
int n;
double amt;
Bill(String n1,String a1,long t1,double r1,int c)
{
super(n1,a1,t1,r1);
n=c;
amt=0.0;
52
}
void cal()
{
if(n>=1&&n<=100)
amt=rent;
else if(n>=101&&n<=200)
amt=0.6*n+rent;
else if(n>=201&&n<=300)
amt=0.8*n+rent;
else
amt=1*n+rent;
}
void show()
{
super.show();
System.out.println("No.of calls="+n);
System.out.println("Amount to be paid=Rs."+amt);
}
}
public class Test
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the name:");
String n1=br.readLine();
System.out.print("Enter the address:");
String a1=br.readLine();
System.out.print("Enter the telephone number:");
long t1=Long.parseLong(br.readLine());
System.out.print("Enter the monthly rental:");
double r1=Double.parseDouble(br.readLine());
System.out.print("Enter the number of calls:");
int c=Integer.parseInt(br.readLine());
Bill ob=new Bill(n1,a1,t1,r1,c);
System.out.println("***output***");
53
ob.cal();
ob.show();
}
}
Output:
Enter the name:java for school
Enter the address:123,sample street
Enter the telephone number:1234567890
Enter the monthly rental:180
Enter the number of calls:270
***output***
Name of customer=java for school
Address=123,sample street
Telephone Number=1234567890
Monthly rental=Rs.180.0
No.of calls=270
Amount to be paid=Rs.396.0
54
Question 18:
The result of a quiz competition is to be prepared as follows:
The quiz has five questions with four multiple choices (A,B,C,D), with each question carrying 1 mark for
the correct answer. Design a program to accept the number of participants N such that N must be greater
than 3 and less than 1l . Create a double dimensional array of size (N*5) to store the answers of each
participant row-wise. Calculate the marks for each participant by matching the correct answers stored in a
single dimensional array of size 5. Display the scores for each participant and also the participants having
the highest score.
Example: If the value of N=4, then the array would be:
Q1 Q2 Q.3 Q.4 Q.5
A B B C A
Participant 1
D A D C B
Participant 2
A A B A C
Participant 3
D C C A B
Participant 4
D C C A B
Key to the question:
55
Example 1
INPUT:
Participant l: D A B C C
Participant2: A A D C B
Participant3: B A C D B
Participant4: D A D C B
Participant5: B A D C B
Key: B C D A A
OUTPUT:
Participant l=0
Participant2=1
Participant3=1
Participant4=1
Participant5=2
Highest score: Participant 5
Programming Code:
import java.util.*;
class Quiz
{
char A[][],K[];
int S[],n;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter number of participants:");
n=sc.nextInt();
if(n<4||n>10)
{
System.out.println("INPUT SIZE OUT OF RANGE");
System.exit(0);
}
A=new char[n][5];//array to store the answers of every participants
K=new char[5];//Array to store answer key
56
S=new int[n];//Array to store score of every participant
System.out.println("\n*Enter answer of each participant row-wise in a single line*\n");
for(int i=0;i<n;i++)
{
System.out.print("Participant"+(i+1)+":");
for(int j=0;j<5;j++)
{
A[i][j]=sc.next().charAt(0);
}
}
System.out.print("\nEnter Answer key:");
for(int i=0;i<5;i++)
{
K[i]=sc.next().charAt(0);
}
}
void CalcScore()//Function to calculate score of every participant
{
for(int i=0;i<5;i++)
{
S[i]=0;
for(int j=0;j<5;j++)
{
if(A[i][j]==K[j])//Checking the answers of the participants
{
S[i]++;
}
}
}
}
void printScore()
{
int max=0;
57
System.out.println("\nSCORES:");
for(int i=0;i<n;i++)
{
System.out.println("\tParticipant"+(i+1)+"="+S[i]);
if(S[i]>max)
{
max=S[i];//storing the highest score
}
}
System.out.println();
System.out.println("\tHighest Score:"+max);
System.out.println("\tHighest Scorers:");
for(int i=0;i<n;i++)//Printing all those participant number who got highest score
{
if(S[i]==max)
{
System.out.println("\t\t\tPartcipant"+(i+1));
}
}
}
public static void main(String args[])
{
Quiz ob=new Quiz();
ob.input();
ob.CalcScore();
ob.printScore();
}
}
58
Output:
Enter number of participants:5
Participant1:A B A D C
Participant2:B A C D B
Participant3:D A C B A
Participant4:C D B C A
Participant5:B D C B A
SCORES:
Participant1=1
Participant2=1
Participant3=1
Participant4=1
Participant5=3
Highest Score:3
Highest Scorers:
Partcipant5
59
Question 19:
Write a program to declare a matrix A[ ][ ] of order ( M X N ) where ‘M’ is the number of rows and
‘N’ is the number of columns such that the values of both ‘M’ and ‘N’ must be greater than 2 and
less than 10.
Allow the user to input integrs into this matrix. Perform the following tasks on the matrix:
(a)Display the original matrix.
(b)Sort each row of the matrix in ascending order using any standard sorting technique.
(c)Display the changed matrix after sorting each row. Test your program for the following data and
some random data.
Example 1:
INPUT:
M=4
N=3
ENTER THE ELEMENTS OF THE MATRIX
11 -2 3
5 16 7
9 0 4
3 1 8
OUTPUT:
THE ORIGINAL MATRIX
11 -2 3
5 16 7
9 0 4
3 1 8
MATRIX AFTER SORTING THE ROWS
-2 3 11
5 7 16
0 4 9
1 3 8
Programming Code:
import java.util.*;
public class twodarr
{
void sort(int a[])
{
int i,j,n=a.length.tmp;
60
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
tmp=a[j];
a[j]=a[j+1];
a[j+1]=tmp;
}
}
}
}
void display(int a[][])
{
int i,j;
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
void sort2d(int a[][])
{
int i,j;
for(i=0;i<a.length;i++)
{
sort(a[i]);
}
}
public static void main()
{
Scanner sc=new Scanner(System.in);
61
twodarr obj=new twodarr();
int a[][],m,n,i,j;
System.out.println("Enter the number of rows");
m=sc.nextInt();
System.out.println("Enter the number of columns");
n=sc.nextInt();
if(m<3||m>9||n<3||n>9)
{
System.out.println("Enter the values for tha matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Original Matrix");
obj.display(a);
obj.sort2d(a);
obj.display(a);
}
}
}
Output:
Enter the number of rows
3
Enter the number of columns
3
62
Enter the values for the matrix
9
8
8
7
6
5
4
3
2
1
Original matrix
9 8 7
6 5 4
3 2 1
Ordered matrix
7 8 9
4 5 6
1 2 3
63
Question 20:
The names of the 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 teams, where 2<N<9 and display them in vertical order,side by side with a horizontal tab(I.e
eight spaces). Test your program for the following data and some random data.
Example 1:
INPUT:N=3
Team 1:Emus, Team 2:Road Ro, Team 3:Coyote
OUTPUT:
E R C
M o o
u a y
s d o
t
R e
o
Programming Code:
import java.util.*;
public class Stringex
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String ar[];
int n,i,j;
System.out.println("Enter the number of the names");
n=sc.nextInt();
ar=new String[n];
System.out.println("Enter the names");
for(i=0;i<n;i++)
{
ar[i]=sc.nextLine();
}
int max=0;
for(i=0;i<n;i++)
{
64
if(max<ar[i].length())
max=ar[i].length();
}
System.out.println("output:");
for(i=0;i<max;i++)
{
for(j=0;j<n;j++)
{
if(i<ar[j].length())
System.out.print(ar[j].charAt(i)+"\t");
else
System.out.print("\t");
}
System.out.println();
}
}
}
Output:
Enter the number of the names
3
Enter the names
Emus
Road Ro
Coyote
output:
E R C
m o o
u a y
s d o
t
R e
o
65