Computer Class 12 Isc Project File
Computer Class 12 Isc Project File
. Thank You!!
- Harshit Sharma
Foreword
Java is a popular third generation programming
language which can be used to do any of the thousands
of things that a computer software can do .With the
features it offers, java has become a language of choice
for internet and internet application java plays an
important role for the proper functioning of many
software-based devices attached to a network .The kind
of functionality the java offers has contributed a lot
towards the popularity of java.
- Harshit….
Index
S . n o. Name of the program
1. Program for sorting non-boundary elements and finding the
sum of diagonals
19. Program for converting a string into lower case and finding
a frequency of each alphabet present in the string
21. Program for accepting 2 dates in string format and find the
difference in days between the 2 dates
23. Program for filling a 2D array with the first 'm*n' prime
numbers , where 'm' is the number of rows and 'n' is the
number of columns
25. Program for defining a class Stack and performing the given
operations by using the given data members
27. Program for defining a class date and perform the given
operations by using the given data member
Algorithm:
STEP 1: Start
STEP 2 : Accept the size of array in variable m and array element in a[][].
1
STEP 3: With the help of statement if(i==0||i==(m-1)||j==0||j==(m-1)) Count the
number of non boundary elements and store it in variable k.
STEP 5: Store the non boundary elements in array b[] with help of condition
if(i==0||i==(m-1)||j==0||j==(m-1)).
STEP 6: Sort the array b[] in ascending order using bubble sort.
STEP 8: Insert the boundary elements and the sorted non boundary elements of
array b[] in array c[][] using condition if(i==0||i==(m-1)||j==0||j==(m-1)).
STEP 9: Print the original array a[][] and rearranged array c[][].
STEP 10: Print the diagonal elements and their sum using condition
if((i+j)%(m-1)==0||(i==j)).
STEP 11 : End.
Source Code:
import java.util.*;
class Boundary
{ int temp=0,k=0,l=0,r=0,sum=0;
int m=sc.nextInt();
2
int a[][]=new int [m][m];
for(inti=0;i<m;i++)
{ for(int j=0;j<m;j++)
{ a[i][j]=sc.nextInt();
} for(inti=0;i<m;i++)
{ for(int j=0;j<m;j++)
{ if(i==0||i==(m-1)||j==0||j==(m-1))
{continue; }
else
{ k++;}}}
for(inti=0;i<m;i++)
{ for(int j=0;j<m;j++)
{ if(i==0||i==(m-1)||j==0||j==(m-1))
{ continue; }
else{
b[r]=a[i][j];
r++;}}}
for(inti=0;i<k;i++)
3
{ for( int j =0;j<k-i-1;j++)
{ if(b[j]>b[j+1]) {
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;}}}
for(inti=0;i<m;i++)
{for(int j=0;j<m;j++)
{ if(i==0||i==(m-1)||j==0||j==(m-1))
c[i][j] = a[i][j];
else{
c[i][j]=b[l];
l++;
}}}
for(inti=0;i<m;i++)
{ for(int j=0;j<m;j++)
{ System.out.print(a[i][j]+" ");
4
System.out.println(" ");
for(inti=0;i<m;i++)
{ for(int j=0;j<m;j++)
{ System.out.print(c[i][j]+" ");
System.out.println(" ");
for(inti=0;i<m;i++)
{ if((i+j)%(m-1)==0||(i==j))
{sum=sum+c[i][j];
System.out.print(c[i][j]+" ");
}else
{ System.out.print(" ");}}
System.out.println(" ");}
System.out.println("Sum is "+sum);
}}
5
Variable Description:
SNo Variable Data Type Description
1. m int For accepting the size of array
6
Input/Output:
7
Program-2
Write a program to accept the year, month and the weekday name of the 1st day of that month
and generate its calendar.
Example :
INPUT :
Year : 2016
Month : February
1st day of February : Monday
OUTPUT :
---------------------------------
February 2016
---------------------------------
SUN MON TUE WED THU FRI SAT
---------------------------------
1 2 3 4 5 6
---------------------------------
7 8 9 10 11 12 13
---------------------------------
14 15 16 17 18 19 20
---------------------------------
21 22 23 24 25 26 27
---------------------------------
28 29
---------------------------------
Algorithm:
Step 1: Accept the year,month and week day in variable y,mname and wname.
8
Step 5: Repeat step 4 till the loop for(int i=1; i<=12; i++) runs and return max.
Step 8: Repeat step 8 till the loop for(int i=0; i<7; i++) runs and return f;
Source Code:
import java.util.*;
class CalendarProgram
int D[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if((y%400==0) || ((y%100!=0)&&(y%4==0))){
D[2]=29;}
int max = 0;
if(mname.equalsIgnoreCase(months[i])){
max = D[i]; }}
9
return max;
} //Function to match the given weekday name and return its weekday no.
"Saturday"};
int f = 0;
if(wname.equalsIgnoreCase(days[i]))
{f = i; //Saving week day no. given day (e.g. '0' for Sunday)
}}
return f;}
int x = 1, z = f;
for(int i=0;i<6;i++){
if(x<=max){
A[i][j] = x;
x++;}}
f = 0;}
void printCalendar(int A[][], String mname, int y) //Function for printing the
calendar
System.out.println("\n\t----------------------------------------------------");
System.out.println("\t----------------------------------------------------");
System.out.println("\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT");
System.out.println("\t----------------------------------------------------");
if(A[i][j]!=0)
System.out.print("\t "+A[i][j]);
else
System.out.print("\t ");}
System.out.println("\n\t----------------------------------------------------"); }}
int f = ob.findDayNo(wname);
ob.fillCalendar(max,f,mname,y);
}}
Variable description:
S.No. Variable Data Type Description
1. months[],D[],days[] String,int, Array to store month
String name,max days and week
days.
2. Mname,y,wname String,int To store the month
,String name,year and week day.
3. max int To store the maximum
days of month.
4. f int To store the day number.
5. A[][] int To store the dates.
6. x,z int Assists in generating
calender.
7. i,j int Loop controlling variables.
12
Input/Output:
13
Program-3
Accept a paragraph of text consisting of sentences that are terminated by either ‘.’ (full stop), ‘!’
(exclamation mark) or a ‘?’ (question mark). Assume that there can be maximum 10 sentences
in a paragraph. Write a program to arrange the sentences in increasing order of their number of
words.
Example :
INPUT : Please come and attend the party. Hello! How are you?
OUTPUT :
Hello = 1
How are you = 3
Please come and attend the party = 6
Algorithm:
Step 1: Start.
Step 2: Create a function to count the number of word using String tokenizer.
Step 3: Create a function to sort the string in ascending order of their no. of
words (Step 4-5 ).
Step 4: generate a loop from 0 to n-1 and then generate another loop from i+1 to
n.
Step 5: check whether p[i] is greater than p[j], if so then swap it.
Step 6: create a function to display the results.
Step 7: END
Source code:
import java.util.*;
class sortParagraph{
int c = str.countTokens();
return c;} // Function to sort the sentences in ascending order of their no. of
words
int n = w.length, t1 = 0;
String t2 = "";
t1 = p[i];
p[i] = p[j];
p[j] = t1;
t2 = w[i];
w[i] = w[j];
w[j] = t2;}}}
printResult(w,p); }
int n = w.length;
15
for(int i=0; i<n; i++){
System.out.println(w[i]+"\t=\t"+p[i]);}}
String pg = sc.nextLine();
else{
sent[i] = str.nextToken().trim();
p[i] = ob.countWords(sent[i]); }
ob.sort(sent,p);}}}
16
Variable Description:
S.No. Variable Data Type Description
1. c int Counts the token
2. w[] String to store tokens of string
3. p[] int to store no. of words
4. sent[] String Array to store sentences of
paragraph.
5. n int Stores the length of w[].
6. pg String Accepts the paragraph.
7. t1,t2 Int,String Assists in sorting.
Input/Output:
17
Program-4
Write a Program in Java to input a number and check whether it is a Bouncy Number or not.
Increasing Number : Working from left-to-right if no digit is exceeded by the digit
to its left it is called an increasing number; for example, 22344.
Decreasing Number : Similarly if no digit is exceeded by the digit to its right it is
called a decreasing number; for example, 774410.
Bouncy Number : We shall call a positive integer that is neither increasing nor
decreasing a “bouncy” number; for example, 155349. Clearly there cannot be any
bouncy numbers below 100.
Algorithm:
Step 1: Start
Step 2: Accept the number in variable in the main function.
Step 3: In the function boolean isIncreasing(int n) check whether the no. is
increasing and return true or false .
Step 4: In the function boolean isDecreasing(int n) check whether the no. is
decreasing or not and return true or false.
Step 5: In the function void isBouncy(int n) check wheher the no is bouncy.
Number will be bouncy if both the function boolean isIncreasing(int n) and
boolean isDecreasing(int n) returns false.
Step 6: Print if the number is bouncy or not.
Step 7: End.
Source Code:
import java.util.*;
class BouncyNumber{
18
boolean isIncreasing(int n) //Function to check whether a number is
Increasing
{
String s = Integer.toString(n);
char ch;
int f = 0;
for(int i=0; i<s.length()-1; i++){
ch = s.charAt(i);
if(ch>s.charAt(i+1)){
f = 1;
break;}}
if(f==1)
return false;
else
return true;}
boolean isDecreasing(int n){
String s = Integer.toString(n);
char ch;
int f = 0;
for(int i=0; i<s.length()-1; i++){
ch = s.charAt(i);
if(ch<s.charAt(i+1)){
f = 1;
19
break;}}
if(f==1)
return false;
else
return true;}
void isBouncy(int n){
if(isIncreasing(n)==true)
System.out.println("The number " + n + " is Increasing and Not Bouncy");
else if(isDecreasing(n)==true)
System.out.println("The number " + n + " is Decreasing and Not Bouncy");
else
System.out.println("The number " + n + " is bouncy");}
public static void main(){
Scanner sc = new Scanner(System.in);
BouncyNumber ob = new BouncyNumber();
System.out.print("Enter a number : ");
int n = sc.nextInt();
ob.isBouncy(n);}}
20
Variable Description:
S.No Variable Data Type Description
Input/Output:
21
Program-5
Given a square matrix M [ ] [ ] of order ‘n’. The maximum value possible for ‘n’ is 10. Accept
three different characters from the keyboard and fill the array according to the instruction
given below.
Fill the upper and lower elements formed by the intersection of the diagonals by character 1.
Fill the left and right elements formed by the intersection of the diagonals by character 2.
Fill both the diagonals by character 3.
Output the result in format given below:
Example 1
ENTER SIZE : 4
INPUT : FIRST CHARACTER : ‘*’
SECOND CHARACTER : ‘?’
THIRD CHARACTER : ‘#’
Algorithm:
Step 1: Start
Step 2: Accept the size of matrix in variable n and check whether the size is valid
or not.
Step 3: Accept the first ,second and third character in variable c1,c2and c3.
Step 4: if(i==j || (i+j)==(n-1)) then A[i][j] = c3; else A[i][j] = c2;
Step 5: Repeat Step 4 till the loop
for(int i=0; i<n; i++)
{ for(int j=0; j<n; j++)}} executes.
Step 6: A[i][j] = c1; A[n-1-i][j] = c1;
Step 7: Repeat step 6 till the loop
for(int i=0; i<n/2; i++)
{ for(int j=i+1; j<n-1-i; j++)}} executes.
Step 8: Print the matrix A[][].
22
Step 9: End.
Source Code:
import java.util.*;
class MatrixFill{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of the matrix : ");
int n = sc.nextInt();
if(n<2 || n>10)
System.out.println("Size out of Range");
else{
char A[][]=new char[n][n];
System.out.print("Enter the 1st character : ");
char c1 = sc.next().charAt(0);
System.out.print("Enter the 2nd character : ");
char c2 = sc.next().charAt(0);
System.out.print("Enter the 3rd character : ");
char c3 = sc.next().charAt(0);
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(i==j || (i+j)==(n-1))
23
else
for(int j=i+1; j<n-1-i; j++) {A[i][j] = c1; // Filling the upper positions formed by
intersection of diagonals
A[n-1-i][j] = c1; // Filling the lower positions formed by intersection of diagonals
}}System.out.println("\nOutput : \n");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
System.out.print(A[i][j]+" ");}
System.out.println();}}}}
Variable Description:
S.No. Variable Data Type Description
1. n int Stores the size of matrix
2. A[][] char Array to store characters.
3. c1,c2,c3 char Stores first,second and third
character.
4. i,j int Looping variables.
24
Input/Output:
25
Program-6
Write a Program in Java to input a number and check whether it is an Evil
Number or not.
Evil Number : An Evil number is a positive whole number which has even number
Design a program to accept a positive whole number and find the binary equivalent
of the number and count the number of 1’s in it and display whether it is a Evil
number or not with an appropriate message. Output the result in format given below:
Example 1
INPUT : 15
BINARY EQUIVALENT : 1111
NO. OF 1’s : 4
OUTPUT : EVIL NUMBER
Algorithm:
STEP 1: Accept the number from the user in variable n .
STEP 2: Store the value of n in variable num.
STEP 3: num=num/2,d++
STEP 4 : Repeat step 3 while (num!=0) and variable d stores the number of digits
of the inputted number.
STEP 5: Declare an array a[] of size [d].
STEP 6: r=n%2,a[i]=r
26
STEP 7 : n=n/2,i++
STEP 8 : Repeat step 6 and 7 while(num != 0).
STEP 9 : Count the number of 1’s in the array a*+ and store it in variable c.
STEP 10: if(c%2 == 0) print number is evil else number is not evil.
STEP 11 : End.
Source Code:
import java.util.*;
class Evil
{
public static void main()
{int num=0,d=0,i=0,r=0,c=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int n=sc.nextInt();
num=n;
while(num!=0){
num=num/2;
d++;}
int a[]=new int[d];
while(n!=0){
r=n%2;
a[i]=r;
27
n=n/2;
++i;}
for(int j=0;j<a.length;j++){
if(a[j] == 1)
{c++;}}
if(c%2 == 0)
{System.out.println("The number is a evil number");}
else{System.out.println("The number is not evil number");}}}
Variable Description:
S.No. Variable Data Type Description
1. n int Accepts the number.
2. num int Stores the copy of the number.
3. d int Counter variable that counts the
number of digits.
4. a[] int Array to store binary equivalent.
5. I int Helps in storing binary equivalent of
the no. in array a[].
6. r int Assists in finding binary equivalent.
7. c int Counter variable that counts the no.
of 1’s.
8. j int Loop variable.
28
Input/Output:
29
Program-7
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. Print an error message if the input does not
terminate with ‘.’ or ‘?’. You can assume that no word in the sentence exceeds 15 characters, so
that you get a proper formatted output.
Example 1
OUTPUT:
Intelligence Plus Character Is Education
Intelligence 5 7
Plus 1 3
Character 3 6
Is 1 1
Education 5 4
30
Algorithm:
Step 1: Start
Step 2: Create a function countVowel( ) to convert the inputted string s into
Uppercase and further calculates the no of vowels.(Step: 3)
Step 3: if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') ; count++;
Step 4: Create a function countVowel( ) that converts the first letter of a word of a
String to Uppercase.
Step 5: Create a function addSpace( ) that adds space after one word of String.
Step 6: Finally create main method that executes the entire program.
Step 7: End.
Source Code:
import java.util.*;
class sentence{
int countVowel(String s) {
s = s.toUpperCase();
int count = 0;
char ch;
for(int i=0; i<s.length(); i++){
ch = s.charAt(i);
if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U'){
count++;}}
return count;}
31
String convert(String s) {
char ch = s.charAt(0);
ch = Character.toUpperCase(ch);
String f = ch + s.substring(1);
return f;}
String addSpace(String s, int max) {
int x = max-s.length();
for(int i=1; i<=x; i++){
s = s+" ";}
return s;}
public static void main(String args[]){
sentenceob = new sentence();
Scanner sc=new Scanner(System.in);
System.out.print("Enter a sentence : ");
String s=sc.nextLine();
int l = s.length();
char last = s.charAt(l-1);
if(last != '.' &&last != '?'){
System.out.println("Invalid Input. End a sentence with either '.' or '?'");}
else{
StringTokenizer str = new StringTokenizer(s," .?");
int x = str.countTokens();
String ans="";
32
String word[]=new String[x];
int vow, con, max=0;
for(int i=0; i<x; i++){
word[i] = str.nextToken();
ans = ans + " " + ob.convert(word[i]);
if(word[i].length()>max){
max = word[i].length();}}
System.out.println("Sentence = "+ans.trim());
String y=ob.addSpace("Word",max);
System.out.println(y+"\tVowels\tConsonant");
for(int i=0; i<x; i++){
vow = ob.countVowel(word[i]);
con = word[i].length()-vow;
y = ob.addSpace(word[i],max);
System.out.println(y+"\t"+vow+"\t"+con);}}}}
33
Variable Description:
S.No. Variable Data Type Description
Input/Output:
34
Program-8
Write a program to declare a square matrix A* +* + of order MxM where ‘M’ is the number of
rows and the number of columns, such that M must be greater than 2 and less than 10. Accept
the value of M as user input. Display an appropriate message for an invalid input. Allow the
user to input integers into this matrix. Perform the following tasks:
(c) Find the sum of the elements of the four corners of the matrix.
Test your program for the following data and some random data:
Example 1
INPUT :
M=3
OUTPUT :
ORIGINAL MATRIX
Algorithm:
35
Step 1: Start
Step 2: Accept the size of matrix in variable m and check whether the size is valid
or not.
Step 3: Accept the matrix in array A[][].
Step 4: Print the original matrix.
Step 5: Rotate the matrix by using loopfor(int i=0;i<m;i++)
{ for(int j=m-1;j>=0;j--)}}
And print A[j][i].
Step 6: Calculate the sum of corner elements in variable sum and print the sum.
Step 7:End.
Source Code:
import java.util.*;
class clockwise {
public static void main(String args[])throws Exception{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix : ");
int m=sc.nextInt();
if(m<3 || m>9)
System.out.println("Size Out Of Range");
else{
int A[][]=new int[m][m];
System.out.println("Enter an element : ");
for(int i=0;i<m;i++){
36
for(int j=0;j<m;j++){
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();}}
System.out.println("*************************");
System.out.println("The Original Matrix is : ");
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
System.out.print(A[i][j]+"\t");}
System.out.println();}
System.out.println("*************************");
System.out.println("Matrix After Rotation is : ");
for(int i=0;i<m;i++){
for(int j=m-1;j>=0;j--){
System.out.print(A[j][i]+"\t");}
System.out.println();}
System.out.println("*************************");
int sum = A[0][0]+A[0][m-1]+A[m-1][0]+A[m-1][m-1];
System.out.println("Sum of the corner elements = "+sum);}}}
37
Variable Description:
S.No. Variable DataType Descrption
1. m int Accepts the size of matix.
2. A[][] int Accepts the matrix inputted by the
user.
3. i,j int Loop vriables.
4. sum int Stores the sum of corner elements
Input/Output:
38
Program-9
Write a Program in Java to input a word and print its anagrams..
Note: Anagrams are words made up of all the characters present in the original word by re-
arranging the characters.
Example: Anagrams of the word TOP are: TOP, TPO, OPT, OTP, PTO and POT.
Algorithm:
STEP-1: Start.
STEP 2: Accept a string from a user.
STEP 3: Store the string in string variable „s‟.
STEP 4: Find out the length of the string and store it in „l‟ , i.e. l=s.length().
STEP 5: Make a new character type array of length „l‟ ,i.e. char ch*+=new char*l+.
STEP 6: Set a for loop from 0to( l-1) i.e. for(x=0;x<=l-1;x++) and store each
character of string in this array.
STEP 7: Set a for loop i.e. for(x=0 ; x<l ; x++) .In this loop swap each & every
character of the array with the first character of the same array ch[0]=ch[x].
STEP 8: Set another loop from 1 to less than l.inside this loop set another loop i.e.
for(z=1; z<l-1 ; z++).
STEP 9: Inside the previous loop keep on swapping the adjacent characters.
STEP 10: After swapping adjacent characters print the whole array using loop in
the previous loop.
STEP 11: End
Source Code:
import java.io.*;
39
class permutation
{
public static void main(String s)
{
int pt=1;
System.out.println("INPUT--");
System.out.println(s);
System.out.println("OUTPUT--");
int l=s.length();
char ch[]=new char[l];
char tmp1,tmp2;
for(int z=0; z<l; z++)
ch[z]=s.charAt(z);
for(int x=0;x<l;x++){
for(int z=1;z<l-1;z++){
tmp1=ch[z];
ch[z]=ch[z+1];
ch[z+1]=tmp1;
System.out.print(pt+".");
pt++;
for(int p=0;p<l;p++){
System.out.print(ch[p]);}
System.out.println();}}}}}
40
Variable Description:
S.No. Variable Data Type Description
1. s String Accepts the string.
2. l int Stores the length of s.
3. ch[] char Array to store the characters
4. tmp1,tmp2 char Variables used for swapping
characters.
5. pt int Counter variable.
6. x,z,p int Looping variables.
Input/Output:
41
Program-10
Write a Program in Java to input a 2-D square matrix and check whether it is an Upper
Triangular Matrix or not.
Upper Triangular Matrix : An Upper Triangular matrix is a square matrix in which all the entries
below the main diagonal () are zero. The entries above or on the main diagonal themselves may
or may not be zero.
Example:
Algorithm:
Step 1: Start
Step 2: Accept the size of matrix in variable m and the matrix in array a[][].Declare
variable k=1.
Step 3: if(a[i][j]!=0)then k=0;
Step 4:k=0; break;
Step 5: Repeat step 4 and 5 till loop
for(int i=0;i<m;i++)
{
for(int j=(i-1);j>0;j--)
{ }} executes.
Step 6: if(k==1)print upper triangular matrix else if(k==0) print not a upper
triangular matrix.
Step 7: End.
42
Source Code:
import java.util.*;
class UpprTriangular{
public static void main(){int k=1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of m");
int m=sc.nextInt();
int a[][]=new int [m][m];
System.out.println("Enter the values of array");
for(int i=0;i<m;i++){
for(int j =0;j<m;j++){
a[i][j]=sc.nextInt();}}
for(int i=0;i<m;i++){
for(int j=(i-1);j>0;j--){
if(a[i][j]!=0)
{k=0;
break;}}}
if(k == 1)
{System.out.println("Matrix is an Upper triangular matrix");}
else if(k==0)
{System.out.println("Matrix is not an Upper triangular matrix");}}}
43
Variable Description:
S.No. Variable Data Type Description
Input/Output:
44
Program-11
Write a Program in Java to input two 2-D arrays and perform Matrix Multiplication:.
Algorithm:
Step 1: Start
Step 2: Accept the number of rows and columns of first matrix in variable m and n
and rows and columns of second matrix in variable p and q.
Step 3: Accept the first matrix in array first[] and second matrix in array second[].
Step 4: if ( n != p ) output matrix cannot be multiplied.
Step 5: for ( c = 0 ; c < m ; c++ ){(loop 1)
Step 6: for ( d = 0 ; d < q ; d++ ){(loop 2)
Step 7: for ( k = 0 ; k < p ; k++ ){(loop 3)
Step 8: sum = sum + first[c][k]*second[k][d];
Step 9: multiply[c][d] = sum;sum = 0;
loop 1,2 and 3 ends.
Step 10: print matrix multiply[][].
Step 11:End.
Source Code:
import java.util.Scanner;
class MatrixMultiplication{
public static void main() {
45
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ ){
for ( d = 0 ; d < n ; d++ ){
first[c][d] = in.nextInt();}}
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each
other.");
else{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ ){
for ( d = 0 ; d < q ; d++ ){
second[c][d] = in.nextInt();}}
for ( c = 0 ; c < m ; c++ ){
46
for ( d = 0 ; d < q ; d++ ){
for ( k = 0 ; k < p ; k++ ){
sum = sum + first[c][k]*second[k][d];}
multiply[c][d] = sum;
sum = 0;}}
System.out.println("Product of entered matrices:-");
for ( c = 0 ; c < m ; c++ ){
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");}}}}
Variable Description:
S.No Variable Data Type Description
1. m,n int Accepts the rows and columns of
first matrix
2. p,q int Accepts the rows and columns of
second matrix
3. first[] int Accepts the first matrix
4. second[] int Accepts the second matrix.
multiply[] int Stores he product of two matrices
5. sum int Assists in multiplying two matrices
6. c,d,k int Loop variables
47
Input/Output:
48
Program-12
Write a program to input a word from the user and remove the duplicate characters present in
it.
Example:
INPUT – abcabcabc
OUTPUT – abc
INPUT – javaforschool
OUTPUT – javforschl
INPUT – Mississippi
OUTPUT – Misp
Algorithm:
Step 1: Start
Step 2: Accept the word in variable s and store its length in l.
Step 3: for(int i=0; i<l; i++)//loop 1
Step 4: ch = s.charAt(i);
Step 5: if(ch!=' ')
Step 6: ans = ans + ch;
Step 7: s = s.replace(ch,' ');//loop 1 ends.
Step 8: Print ans.
Step 9: End.
49
Source Code:
import java.util.*;
class RemoveDupChar{
public static void main(){
Scanner br = new Scanner(System.in);
System.out.print("Enter any word : ");
String s = br.next();
int l = s.length();
char ch;
String ans="";
for(int i=0; i<l; i++){
ch = s.charAt(i);
if(ch!=' ')
ans = ans + ch;
s = s.replace(ch,' ');}
System.out.println("Word after removing duplicate characters : " + ans);}}
50
Variable Description:
S.No. Variable Data Type Description
1. s String Accepts the word.
2. l int Stores the length of string s.
3. ch char Assists in removing duplicate
characters.
4. ans String Assists in removing duplicate letters.
Input/Output:
51
Program-13
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 the minimum element 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.]
Saddle point = 7 because it is the minimum element of row 2 and maximum element of column
1
Algorithm:
STEP 1: Start
52
STEP 10: if f=0 then print no saddle point .
STEP 11: end.
Source Code:
import java.util.*;
class SaddlePoint{
public static void main()
{
Scanner br=new Scanner(System.in);
System.out.print("Enter the order of the matrix : ");
int n=br.nextInt();
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++){
System.out.print("Enter Element at ["+i+"]["+j+"] : ");
A[i][j]= br.nextInt();}}
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]<min){
53
min = 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];}}
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("********************");
}
}
}
54
Variable Description:
S.No. Variable Data Type Description
1. n int Stores the order of matrix
2. A[][] int Array of size [n][n]
3. i,j int Looping variables
4. max int Stores the maximum element.
5. min int Stores the minimum element.
6. x int Assists in finding saddle point.
7. f int Counter variable that displays if the
matrix has no saddle point.
Input/Output:
55
Program-14
Write a Program in Java to fill a square matrix of size ‘n*n” in a spiral fashion (from the inside)
with
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.
Algorithm:
STEP 1: Start.
56
STEP 10: print the matrix .
STEP 11: End
Source Code:
import java.util.*;
class Circular_Matrix {
public static void main()
{
Scanner br=new Scanner(System.in);
System.out.print("Enter the number of elements : ");
int n= br.nextInt();;
while(k>=1){
for(int i=c1;i<=c2;i++){
A[r1][i]=k--;
}
for(int j=r1+1;j<=r2;j++) {
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 is:"); /* Printing the Circular matrix */
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++){
57
System.out.print(A[i][j]+ "\t");}
System.out.println(); }}
}
Variable Description:
S.No. Variable Data Type Description
1. n int Accepts the number of elements.
2. A[][] int Array of size [n][n].
3. c1,c2,r1,r2 int Loop variables
4. k int Counter variable that assists in
printing the matrix in spiral fashion.
Input/Output:
58
Program-15
Write a program in Java to input the first 14 digits of an IMEI number and find the check (last)
digit of it.
The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin,
model, and serial
number of the device.
The check digit (x) is obtained by computing the sum of digits then computing 9 times that
value modulo 10.
Algorithm:
STEP 1: Start
STEP 2: create a function and intiliaze int a .
STEP 3: hatch the values and return a.
STEP 4: enter the first fourteen digits of IMEI code with string s.
STEP 5: if I is not equal to 14 then print output is invalid else for(int i=14; i>=1; i--)
and d is equal to (int)(n%10).
STEP 6: if i%2 is equal to 0 then d = 2*d.
STEP 7:int dig = (9*sum)%10 and print the digit.
STEP 8 :End
59
Source Code:
import java.util.*;
class IMEI_CheckDig{
int sumDig(int n) {
int a = 0;
while(n>0){
a = a + n%10;
n = n/10;}return a;}
public static void main(){
IMEI_CheckDig ob = new IMEI_CheckDig();
Scanner br=new Scanner(System.in);
System.out.print("Enter first 14 digits of IMEI code : ");
long n = br.nextLong();
String s = Long.toString(n);
int l = s.length();
if(l!=14)
System.out.println("Output : Invalid Input");
else{
int d = 0, sum = 0;
for(int i=14; i>=1; i--){
d = (int)(n%10);
if(i%2 == 0)
60
{ d = 2*d; }
sum = sum + ob.sumDig(d);
n = n/10;}
System.out.println("Sum = "+sum);
int dig = (9*sum)%10;
System.out.println("Output : The check digit = "+dig);}}}
Variable Description:
S.No. Variable Data Type Description
1. n long Accepts the number
2. s String Converts the number into string.
3. l int Stores the length of s
4. d int Stores the remainder
5. sum int Stores the sum.
6. dig int Stores the check digit
7. a int Assists in reversig the number.
Input/Output:
61
Program-16
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
terms) 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.
Some keith numbers are: 14 ,19, 28 , 47 , 61, 75, 197, 742, 1104, 1537……………
Algorithm:
STEP 1: Start
STEP 2: enter the value of n.
STEP 3: define an array arr[] and initialize the length of the string equal to
s.length().
STEP 4:while sum<n then initialize sum =0.
STEP 5: for(int j=1; j<=d; j++) then sum equal to sum+arr[i-j].
STEP 6:arr[i] is equal to sum then increase the value of by 1.
STEP 7: if the value of sum is equal to n then check whether it is a keith no or not.
STEP 8: print whether it is a keith or not.
STEP 9: end
62
Source Code:
import java.util.*;
class Keith{
public static void main(String args[]){
Scanner br=new Scanner(System.in);
System.out.print("Enter the number : ");
int n= br.nextInt();;
int copy=n;
String s=Integer.toString(n);
int d=s.length();
intarr[]=new int[n];
for(inti=d-1; i>=0; i--){
arr[i]=copy%10;
copy=copy/10;}
int=d,sum=0;
while(sum<n) {
sum = 0;
for(int j=1; j<=d; j++) {
sum=sum+arr[i-j];}
arr[i]=sum; //storing the sum in the array
i++;}
if(sum==n)
63
System.out.println("The number is a Keith Number");
else
System.out.println("The number is a not a Keith Number");}}
Variable Description:
S.No. Variable Data Type Description
1. n int Accepts the number
2. copy int Stores another copy of number
3. s String Stores the number in String form
4. d int Stores the length of String s
5. Arr[] int Stores the new
number
Input/Output:
64
Program-17
A positive natural number, (for e.g. 27), can be represented as follows:
2+3+4+5+6+7
8+9+10
13+14
where every row represents a combination of consecutive natural numbers, which add up to
27.
Write a program which inputs a positive natural number N and prints the possible consecutive
number combinations,
Test your program for the following data and some random data.
SAMPLE DATA
INPUT:
N=9
OUTPUT:
4+5
2 + 3+ 4
Algorithm:
STEP 1: Start
STEP 2: enter a number n.
STEP 3: for(int i=1 ;i<n;i++) then sum =1.
STEP 4: while(sum <n) then sum = sum +j and j++.
STEP 5: for(int k=i;k<j;k++) ,if value of k is equal to I then print the value of k.
STEP 6: End.
65
Source Code:
import java.util.*;
class Consecutive
{
public static void main(){
Scanner br=new Scanner(System.in);
System.out.print("Enter a number : ");
int n= br.nextInt();;
int sum=0,j=0;
for(int i=1;i<n;i++){
sum=i;
j=i+1;
while(sum<n){
sum=sum+j;
j++;}
if(sum==n){
for(int k=i;k<j;k++){
if(k==i)
System.out.print(k);
else
System.out.print(" + "+k);}
System.out.println();}}}}
66
Variable Description:
S.No Variable Data Type Description
1. n int Accepts the number.
2. sum int Calculates the sum.
3. j int Counter variable which assists in
printing consecutive numbers.
4. i int Loop Variable
5. k int Loop variable
Input/Output:
67
Program-18
Given a time in numbers we can convert it into words. For example :
5:00—— five o’clock
5:10 —— ten minutes past five
5:15 —— quarter past five
5:30 ——half past five
5:40 —— twenty minutes to six
5:45 ——quarter to six
5 : 47 —— thirteen minutes to six
Write a program which first inputs two integers, the first between 1 and 12 (both inclusive)
and second between 0
and 59 (both inclusive) and then prints out the time they represent, in words.
SAMPLE DATA :
1. INPUT :
TIME : 3,0
OUTPUT : 3 : 00 Three o’ clock
2. INPUT :
TIME : 7,29
OUTPUT : 7 : 29 Twenty nine minutes past seven
Algorithm:
STEP 1:Start
STEP 2: Enter the values of hours and minutes in int h and int m respectively.
STEP 3: check whether (h>=1 && h<=12)&& (m>=0&& m<=59)
STEP 4: if m is equal to 1|| m is equal to 59 then plu = “ minute” otherwise plu =
“minutes”.
STEP 4:if value of h ==12 then a = words[1] otherwise a = words[h+1].
68
STEP 5:print the values of h and m.
STEP 6: if (m==0),then print h ,otherwise (m==15) then print quarter past else
(m== 30) then print half past and vice versa.
STEP 6: print these values in sequence .
STEP 7: else print invalid input.
STEP 8: END.
Source Code:
import java.io.*;
public class TimeInWords{
public static void main(String args[])throws IOException{
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Hours : ");
int h=Integer.parseInt(br.readLine());
System.out.print("Enter Minutes : ");
int m=Integer.parseInt(br.readLine());
if((h>=1 && h<=12) && (m>=0 && m<=59)) {String words[]={"", "One", "Two",
"Three", "Four", "Five", "Six","Seven",
"Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen"
,"Seventeen","Eighteen","Nineteen","Twenty","Twenty one", "Twenty
two","Twenty three", "Twenty four", "Twenty five","Twenty
six","Twentyseven","Twenty eight", "Twenty nine")};
String plu, a;
if(m == 1 || m == 59)
plu = "Minute";
else
69
plu = "Minutes";
if(h==12)
a = words[1];
else
a = words[h+1];
System.out.print("Output : "+h+":"+m+" --- ");
if(m==0)
System.out.println(words[h]+" O' clock");
else if(m==15)
System.out.println("Quarter past "+words[h]);
else if(m==30)
System.out.println("Half past "+words[h]);
else if(m==45)
System.out.println("Quarter to "+a);
else if(m<30)
System.out.println(words[m]+" "+plu+" past "+words[h]);
else if
System.out.println(words[60-m]+" "+plu+" to "+a);}
else if
System.out.println("Invalid Input !"); }}
70
Variable Description:
S.No Variable Data Type Description
1. h int Accepts no. of hours
2. m int Accepts no. of minutes
3. words[] String Array to store words.
4. plu String Assists in printing time in words .
5. a String Assists in printing time in words .
Input/Output:
71
Program-19
Write a program to input a string (word). Convert it into lowercase letters. Count and print the
frequency
of each alphabet present in the string. The output should be given as:
Sample Input: Alphabets
Sample Output:
==========================
Alphabet Frequency
==========================
a 2
b 1
e 1
h 1
l 1
p 1
s 1
t 1
Algorithm:
STEP 1: Start
STEP 2: Accept a string s and convert it into lowercase.
STEP 3:Initialize the value of count to be 0
STEP 4:for (char i=’a’ ;i<=’z’;i++)and for(int j=0; j<l; j++) and ch is equal to
s.charAt(j).
STEP 5 : count++ and repeat this step until ch==i.
STEP 6: if value of count is not equal to 0 then print the value of count.
STEP 7: End.
72
Source Code:
import java.util.*;
class AlphabetFreq{
public static void main(){
Scanner br=new Scanner(System.in);
System.out.print("Enter any string: ");
String s = br.nextLine();
s=s.toLowerCase();
int l=s.length();
char ch;
System.out.println("Output:");
System.out.println("==========================");
System.out.println("Alphabet\tFrequency");
System.out.println("==========================");
int count=0;
for(char i='a'; i<='z'; i++){
count = 0;
for(int j=0; j<l; j++){
ch=s.charAt(j);
if(ch==i)
count++; }
if(count!=0){
System.out.println(i+"\t\t"+count);} }}}
73
Variable Description:
S.No. Variable Data Type Description
1. s String Accepts the string.
2. l int Stores the length of string.
3. ch char Stores the character of the string.
4. count int Counter variable to count frequency.
5. i,j int Loop variables
Input/Output:
74
Program-20
Write a Program in Java to input a number in Decimal number system and convert it into its
equivalent
number in the Hexadecimal number system.
Note: Hexadecimal Number system is a number system which can represent a number in any
other number
system in terms of digits ranging from 0 to 9 and then A – F only. This number system consists
of only sixteen
basic digits i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. Here 10 is represented as A, 11 as B
and so on
till 15 which is represented as F.
For Example: 47 in the Decimal number system can be represented as 2F in the Hexadecimal
number system.
Algorithm:
Step 1: Start
Step 2: Accept the number in variable n.
Step 3:Declare an array dig[] which stores the digits of hexadecimal number
system.
Step 4: r=n%16; s=dig[r]+s; n=n/16;
Step 5: Repeat Step 4 till the condition while(n>0) remains true.
Step 6: Print s.
Step 7: End.
75
Source Code:
import java.util.*;
class Dec2Hex{
public static void main(){
Scanner br=new Scanner(System.in);
System.out.print("Enter a decimal number : ");
int n= br.nextInt();;
int r;
String s="";
char dig[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(n>0){
r=n%16;
s=dig[r]+s;
n=n/16;}
System.out.println("Output = "+s);}}
Variable Description:
S.No. Variable Data Type Description
1. n int Accepts the number.
2. Dig[] char array storing the digits (as
characters) in a hexadecimal number
system.
3. s String storing variable for the result
4. r int Finds the remainder.
76
Input/Output:
77
Program-21
Write a program to accept 2 dates in the string format dd/mm/yyyy and find the difference in
days between
the 2 dates.
Example:
INPUT:
Date 1 : 20/12/2012
Date 2 : 11/02/2013
OUTPUT: Difference = 54 days
Algorithm:
Step 1: Start
Step 2: Accepts the first and second date in variables date1 and date2 in the main
function and break them into days,months and yearsby using variables d1,m1,y1
and d2,m2,y2 respectively.
Step 3: Function int isLeap(int y) checks whether year is leap year or not using
conditionif((y%400==0) || ((y%100!=0)&&(y%4==0))) .
Step 4: Function boolean dateValidate(int d, int m, int y) checks whether the date
is valid or not by using condition if(m<0 || m>12 || d<0 || d>month[m] ||
y<0 || y>9999).
Step 5: Function int dayno(int d, int m, int y) finds the day number year = 1 till the
inputted year of both dates and store it in variable a and b.
Step 8: End.
78
Source Code:
import java.io.*;
class Date_Difference
{
static BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int isLeap(int y){
if((y%400==0) || ((y%100!=0)&&(y%4==0)))
return 29;
else
return 28;}
boolean dateValidate(int d, int m, int y){
month[2]=isLeap(y);
if(m<0 || m>12 || d<0 || d>month[m] || y<0 || y>9999)
return false;
else
return true;}
int dayno(int d, int m, int y){
int dn=0;
month[2]=isLeap(y);
for(int i=1;i<m;i++){
dn=dn+month[i];}
79
dn=dn+d;
for(int i=1;i<y;i++){
if(isLeap(i)==29)
dn=dn+366;
else
dn=dn+365;}
return dn;}
public static void main()throws IOException
Date_Difference ob=new Date_Difference();
System.out.print("Enter the 1st date in (dd/mm/yyyy) format: ");
String date1=br.readLine().trim();
int p,q;
p=date1.indexOf("/");
int d1=Integer.parseInt(date1.substring(0,p));
q=date1.lastIndexOf("/");
int m1=Integer.parseInt(date1.substring(p+1,q));
int y1=Integer.parseInt(date1.substring(q+1));
System.out.print("Enter the 2nd date in (dd/mm/yyyy) format: ");
String date2=br.readLine().trim();
p=date2.indexOf("/");
int d2=Integer.parseInt(date2.substring(0,p));
q=date2.lastIndexOf("/");
int m2=Integer.parseInt(date2.substring(p+1,q));
80
int y2=Integer.parseInt(date2.substring(q+1));
if(ob.dateValidate(d1,m1,y1)==true &&ob.dateValidate(d2,m2,y2)==true){
int a=ob.dayno(d1,m1,y1);
int b=ob.dayno(d2,m2,y2);
System.out.print("Output : Difference = "+Math.abs(a-b)+" days.");}
else
System.out.println("Invalid Date");
}
}
Variable Description:
S.No Variable Data Type Description
1. month[] int Stores the maximum days of each
month.
2. date1 int Stores first date.
3. date2 int Stores second date.
4. p,q,d1,m1,y1 int Assists in breaking the first date
into day,month and year .
5. d2,m2,y2 int Assists in breaking the first date
into day,month and year.
6. d,m,y int Accepts the day month and year
7. dn int Helps in calculating the date
difference.
8. i int Loop variable.
81
Input/Output:
82
Program-22
Write a program to print the words of the input in reverse order without any punctuation
marks other than blanks.
INPUT:
Enter number of sentences: 2
Enter the sentences:
This is a sample piece of text to illustrate this question
if you are smart you will solve this right.
OUTPUT: right this solve will you smart are you if question this illustrate to text of piece sample
a is this
NOTE : Individual words (i.e. characters of every word) are not reversed
Test your program for the following data and some random data:
Sample Input 1 :
Enter number of sentences: 1
Enter the text:
Do not judge a book by its cover.
Algorithm:
Step 1:Start
Step 2: Accept the number of sentences in vriable n.
Step 3: Declare String s=” ”
Step 4: Accept the first sentence in String s.
Step 5: Break the string in tokens using StringTokenizer and store the number of
tokens in counter variable c.
Step 6: Store each token in String w.
83
Step 7:Store the reversed String in variable rev.
Step 8: Print the reversed string.
Step 9:End.
Source Code:
import java.util.*;
class Sent_Merge_Rev
{
public static void main(){
Scanner br=new Scanner(System.in);
System.out.print("Enter the number of sentences: ");
int n = br.nextInt();
String s = "";
for(int i=1; i<=n; i++){
System.out.print("Enter Sentence "+i+": ");
s = s + br.nextLine(); }
StringTokenizer str=new StringTokenizer(s," '.,;:!?");
int c=str.countTokens();
String w="", rev="";
for(int i=1; i<=c; i++){
w = str.nextToken();
rev = w+" "+rev;}
System.out.println("Output: "+rev);}}
84
Variable Description:
S.No. Variable Data Type Description
1. n int Accepts the number of sentences.
2. s String Accept the sentence.
3. c int Counts the number of tokens.
4. w String Stores each token.
5. rev String Stores the reversed string.
Input/Output:
85
Program-23
Write a Program in Java to fill a 2-D array with the first ‘m*n’ prime numbers, where ‘m’ is the
number of rows and ‘n’ is the number of columns.
Algorithm:
Algorithm for main method-
Step 1: Start
Step 2: Accept the number of rows in variable m and number of columns in n.
Step 3: Create an array A[][] of size [m][n] and B[] of size[m*n].
Step 4: Declare variable i=0,k=1 and j.
Step 5:if(ob.isPrime(k)==true) then B[i] = k; and i++;
Step 6: k++;
Step 7:Start a loop while(i < m*n) which repeats step 5 and 6 till the condition is
true.
Step 8: Fill the array A[][] with the elements of array B[] using a counter variable
x.
Step 9: Print the filled array A[][].
Step 10 :End.
86
Algorithm for function boolean isPrime(int n)
Step 1: Start.
Step 2:Declare variable c=0.
Step 3: if(n%i == 0) then c++.
Step 4: Repeat step 3 till the loop condition for(int i = 1; i<=n; i++) is true.
Step 5: if(c==2) return true else false.
Step 6:End.
Source Code:
import java.io.*;
class FillPrime
{
boolean isPrime(int n) {
int c = 0;
for(int i = 1; i<=n; i++){
if(n%i == 0)
c++;}
if(c == 2)
return true;
else
return false;}
public static void main()throws IOException{
FillPrime ob = new FillPrime();
87
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of rows: ");
int m=Integer.parseInt(br.readLine());
System.out.print("Enter the number of columns: ");
int n=Integer.parseInt(br.readLine());
int A[][]=new int[m][n];
int B[] = new int [m*n];
int i = 0, j;
int k = 1;
while(i< m*n){
if(ob.isPrime(k)==true){
B[i] = k;
i++;}
k++;}
int x = 0;
for(i=0; i<m; i++){
for(j=0; j<n; j++){
A[i][j] = B[x];
x++;}}
System.out.println("The Filled Array is :");
for(i=0; i<m; i++){
for(j=0; j<n; j++){
System.out.print(A[i][j]+"\t");}
88
System.out.println();}}}
Variable Description:
S.No. Variable Data Type Description
1. m int Accepts number of rows
2. n int Accepts the number of columns
3. A[][] int Array to be filled
4. B[] int Array containing prime numbers
5. i int Counter variable for filling prime
numbers in array b[].
6. k int
7. x int Counter variable for filling array
A[][] with prime numbers
8. c int Counter variable for checking prime
numbers.
Input/Output:
89
Program-24
Write a program in java to print Fibonacci series upto n, where n is the limit entered by
user.,using recursion
Algorithm:
Step 1:Start
Step 2:Accept the limit from the user in variable limit.
Step 3:Declare variable a=0,b=1,c=0.
Step 4:In the functin int fib(int n) check if(n<=1) or else if(n==2) and return a and
b respectively.
Step 5:If both conditions are false return (fib(n-1)+fib(n-2));
Step 6:Print the fibonacci series.
Step 7:End.
Source Code:
import java.io.*;
class Recursion{
static BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int a,b,c,limit;
Recursion() {
a=0;
b=1;
90
c=0;
limit=0;}
void input()throws IOException
{
System.out.print("Enter the limit : ");
limit=Integer.parseInt(br.readLine());}
int fib(int n) {
if(n<=1)
return a;
else if(n==2)
return b;
else
return (fib(n-1)+fib(n-2));}
void generate_fibseries() {
System.out.println("The Fibonacci Series is:");
for(int i=1;i<=limit;i++){
c=fib(i);
System.out.print(c+" ");}}
public static void main(String args[])throws IOException{
Recursion ob=new Recursion();
ob.input();
ob.generate_fibseries();
}
91
}
Variable Description:
S.No. Variable Data Type Description
1. limit int Accepts the limit from user
2. a int Assists in generating fibonacci
series.
3. b int Assists in generating fibonacci
series.
4. c int Assists in generating fibonacci
series.
5. i int Loop variable.
Input/Output:
92
Program-25
Strange is an entity which can hold to the most of 20 integers. The Strange restriction is that an
integer can only be added only from the top or remaining from the top. This is like the pipe of
china plate can add the plate from the top and removing the plate from the pipe.
member()-
void pushdata(int item)-add the integer value to top of stack if possible otherwise
outputs a message “STACK OVERFLOWS”.
void popdata()-removes the integer from top of stack if stack is empty and display
“STACK UNDERFLOW”.
Algorithm:
Step 1: Start
93
Step 6: Create void popdata() function and in it check if(sp==-1) print stack
underflows otherwise take variable t of int type and store t=s[sp],decrease sp by1.
Step 7: In main () method accept max capacity of array in int y and create object
oj of class.
Step 8: Using for(int i=0;i<=y;i++) accept elements from user in int l and call
pushdata() function.
Source Code:
import java.util.*;
class Stack
Stack(int nn)
n=nn;
sp=-1;
s=new int[20];
if(sp==(n-1))
System.out.println(“Stack overflow”);
94
else
sp=sp+1;
s[sp]=item;
}}
void popdata()
if(sp==-1)
System.out.println(“Stack underflow”);
else
int t=s[sp];
sp=sp-1;
}}
int y=ob.nextInt();
for(int i=0;i<y;i++)
95
{
int l=ob.nextInt();
oj.pushdata(l);
for(int i=sp;i>=-1;i--)
{oj.popdata();
}}
Variable Description:
S.No. Variable Data Type Description
1. s int An array to store elements
2. sp int To store index of element
3. n int To store maximum capacity of
array
4. item int To accept argument in pushdata()
function
5. t int To pop out element from array
6. nn int To accept argument in
constructor
7. y int To accept capacity from user
8. i int Loop variable
9. l int To accept elements
96
Input/Output:
97
Program-26
A Goldbach number is positive even integer that can be expressed as the sum of two odd pimes
(All even integer numbers greater than 4 are Goldbach number.
Eg: 6=3+3
10=3+7
10=5+5
Write a program to accept an even integer ‘N’ where N>9 and N<50. Find all the odd prime
pairs whose sum is equal to the number.
Algorithm:
Step 1: Start
Step 3: Accept the number from user in n and check if(n%2!=0||n<9||n>50) print
number is invalid.
Step 9: End.
98
Source Code:
import java.util.*;
class Goldbach
int n=0,p=3,q=0;
System.out.print(“Number=”);
n=sc.nextInt();
if(n%2!=0||n<9||n>50)
{ System.out.println(“Invalid Input.”);
else
while(p<n)
q=n-p;
if(isPrime(p)&&isPrime(q)&&p<=q)
System.out.println(p+”,”+q);
99
p+=2;
}}
isPrime(int n){
int f = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;
}
if(f == 2)
return true;
return false;
}
}
Variable Description:
S.No. Variable Data Type Description
1. n int To accept number from user
2. p int To store first prime number
3. q int To store difference of n and p
4. f int Control variable in isPrime()
function
5. i int Loop variable
100
Input/Output:
101
Program-27
A class date has been defined to handle Date related function.
Finding the future date and days after the current date i.e. Date 32 days after 01-01 will be 02-
02 .
Finding the number of days between the current date and date on which a project .
Eg-If a project started on 01-01 and finished on 02-02,the no. of days would be 32.You may
assume that all the dates are in the year 2013 only and are valid dates.To make calculation
easy,each date can be converted to its equivalent date number.Date no. is the no. of days
between 1st jan (01-01) and the given date (dd-mm).
01-01 1
20-01 20
02-02 33
03-03 62
……. ………
31-12 365
Class name:date
dd:day
mm:month
member function/methods
int datetodatenumber():returns the date number equivalent to the current date object.
date datenumbertodate(int dn):returns the date equivalent to the given date number dn.
102
date futuredate(int n):returns the date that occurs n days after the current date object.You may
assume that the future date will be in the year 2013 only.
Specify the class date giving the details of the constructor and functions date(int nd,int nm),int
datetodatenumber(),date datenumbertodate(int dn),date futuredate(int n).You may assume
that the other function/methods are written for you, do not write the main function.
Algorithm:
Step 1: Start
Step 2: Declare variables dd,mm,sum1,s2,v1 of int type and create an array m[]
containing no. of days in each month.
Step 4: Create a int type function datetodatenumber() and take variable sum=0 of
int type.
Step 8: Using break statement stop execution of for loop and assign (dn-sum) in
t.s2,return t.
103
Step 10: Check if(v>=d) then calculate v and t1.v1 using v=v-m[j] and t1.v1=j-1
respectively,using break stop execution of for loop and assign t1.s2=d-v,return t1.
Step 11: Create void print() function and initialize String s=””,check if((v1+2)<=12)
then go to step 12 otherwise print invalid input.
Step 13: Create main() method and accept dates in e and p of int type,create an
object oj and initialize a with int a=oj.datetodatenumber() and print date number
Step 14: Accept date number in int b and call function using Date
c=oj.datenumbertodate(b) and print date using c.print().
Step 15: Accept days to predict future in int k,call function using Date
l=oj.futuredate(k) and print predicted date using l.print().
Step 16:End.
Source Code:
import java.util.*;
class Date
int dd,mm,sum1,s2,v1;
int m[]={31,28,31,30,31,30,31,31,30,31,30,31};
dd=nd;
104
mm=nm;
sum1=0;
s2=0;
v1=0;
int datetodatenumber()
int sum=0;
for(int i=0;i<m.length();i++)
if(i<=(mm-1))
sum=sum+m[i];
sum1=sum-(m[mm-1]-dd);
return sum1;
int sum=0;
for(int i=0;i<m.length();i++)
{sum=sum+m[i];
105
t.v1=i;
if(sum>=dn)
sum=sum-m[i];
t.v1=i-1;
break;
t.s2=(dn-sum)
return t;
Date futuredate(int n)
int v=0;
int d=datetodatenumber()+n;
for(int j=0;j<m.length();j++)
v=v+m[j];
t1.v1=j;
if(v>=d)
106
{
v=v-m[j];
t1.v1=j-1;
break;
}}
t1.s2=d-v;
return t1;
void print()
String s1=””;
if((v1+2)<=12)
if(s2<10)
s1=s1+”0”+Integer.toString(s2);
else
s1=s1+Integer.toString(s2);
if((v1+2)<10)
s1=s1+”-0”Integer.toString(v1+2);
else
s1=s1+”-”Integer.toString(v1+2);
107
System.out.println(s1);
else{
}}
System.out.println(“Enter date:”);
int e=sc.nextInt();
int p=sc.nextInt();
int a=oj.datetodatenumber();
System.out.println(“Date number:”+a);
int b=sc.nextInt();
Date c=oj.datenumbertodate(b);
System.out.println(Date:”);
c.print();
int k=sc.nextInt();
108
Date l=oj.futuredate(k);
System.out.println(“Future date:”);
l.print();
}}
Variable Description:
S.No. Variable Data Type Description
1. dd int To store date number from user
2. mm int To store month number
3. sum1 int To store sum in
datetodatenumber() function
4. s2,v1 int As an argument during obect
creation
5. m int An array to store no. of days
6. nd,nm int Constructor argument
7. i,j int Loop variable
8. v int As a temporary variable
9. d int To store result of a function.
10. e,p,a,b,k int To accept user input
11. sum int As a temporary variable
109
Input/Output:
110
Program-28
Caesar 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 the other characters remaining unchanged.
Write a program to accept a plain text of length L,Encrypt the plain text if valid as per the
Caesar Cipher .
Example1
Example2
Example3
INPUT:You
OUTPUT:INVALID LENGTH
Algorithm:
Step 1: Start
Step 2: In main() method accept a sentence in variable s.
Step 3: Store length of sentence in variable L.
Step 4: Check the validity of sentence using if(L<4||L>99) and call rot13()
Function.
111
Step 5: In void rot13() declare variables char ch,int a=0,String ans=””.
Step 6: Rotate the letter by13 places using for(int i=0;i<w.length();i++)
Step 7: Inside for loop if letter is greater than 90 or 122 subtract 26 from it.
Step 8: Print the cipher text.
Step 9: End
Source Code:
import java.util.*;
class CaesarCipher
{
void rot13(String w)
{
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;
113
Variable Description:
S.No. Variable Type Description
1. s String Accepts the sentence.
2. L int To store length ofsentence.
3. ch char To store each letter of sentence.
4. a int To increase ASCII value of each
letter by 13.
5. ans String To store cipher text.
6. i int Loop variable
7. w String Accepts string in rot13() function
Input/Output:
114
Program-29
A company manufactures packing cartons in four sizes ,i.e. cartons to accommodate six boxes
,12 boxes ,24 boxes and 48 boxes.Design a program to accept a number of boxes to be packed
(N) by the user (Maximum upto thousand 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 6 should be used .)
Test your program with a sample data and some random data :
EXAMPLE 1
INPUT:N=140
OUTPUT:
EXAMPLE 2
INPUT: N=4296
Algorithm:
Step 1: Start
Step 2: Accept the number of boxes to be packed in variable N .
Step 3: Check if the number of boxes entered are valid or not using
if(N<1||n>1000)
Step 4: Declare an array cart[] of size 4 to store the size of carton.
Step 5: Store the entered number in variable copy.
115
Step 6: Declare variable int totalcart=0, int count=0.
Step 7: Declare variable count to store the size of carton needed.
Step 8: Check if (count!=0) print boxes needed of particular size.
Step 9: Use variable totalcart to store total number of boxes.
Step 10: Store remaining boxes in N using N=N%cart[i] .
Step 11: Print the remaining boxes if(N>0) and increase totalcart by 1.
Step 12: if(N>0) is false print remaining boxes =0.
Step 13: Print total number of boxes and cartons.
Step 14: End.
Source Code:
import java.util.*;
class BoxPacking_ISC2017
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
116
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)
{
System.out.println("\tRemaining Boxes "+N+" x 1 = "+N);
totalCart = totalCart + 1;
}
else
{
System.out.println("\tRemaining Boxes\t\t= 0");
}
System.out.println("\tTotal number of boxes = "+copy);
System.out.println("\tTotal number of cartons = "+totalCart);
}
}
}
117
Variable Description:
S.No. Variable Type Description
1. N int Accepts number of boxes.
2. cart int An array to store carton sizes.
3. copy int To store no of boxes as copy.
4. totalcart int To store total no of cartons
needed.
5. count int To store no of particular sze box
needed.
6. i int Loop variable.
Input/Output:
118
Program-30
The result of a quiz competition is to prepared as follows.
The quize has 5 ques with 4 multiple choices (A,B,C,D) with each ques carrying one mark for the
correct answer . Design a program to accept the no. of participants N such that N must be
greater than 3 and less than 11 . Create a double dimensional array of size (N*5) to store the
answers of each participants row-wise.
Calculate the marks for each participant by matching the correct answer stored in a single
dimensional array of size 5. Display the scores for each participant and also the participant(s)
having the highest score.
Note: array entries are line fed (i.e one entry per line. )
Test your program with the sample data and some random data :
Example 1
INPUT: N=5
Participant 1 D A B C C
Participant 2 A A D C B
Participant 3 B A C D B
Participant 4 D A D C B
Participant 5 B C A D D
Key: B C D A A
OUTPUT:
Scores:
Participant 1=0
Participant 2=1
Participant 3=1
Participant 4=1
119
Participant 5=2
Example 2
INPUT:N=12
Algorithm:
Step 1: Start
Step 2: In main() method create an object and call functions one by one.
Step 3: In void input() the number of participants in variable n.
Step 4: Check for the valid input using if(n<4||n>10).
Step 5: Create an array A of size A[n][5]to store the answer of every participant.
Step 6: Create an array of size s of size [n] to store score of every participant.
Step 7: Accept answers of each participant and store in A.
Step 8: Accept answer key in array K[5].
Step 9: In void calcScore() function calculate the score of every participant.
Step 10: In void printScore() print the score of every participant and print the
highest score as well as highest scorers.
Step 11: End.
120
Source Code:
import java.util.*;
class QuizResult
{
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
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);
}
121
}
void printScore()
{
int max = 0;
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();
122
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\tParticipant "+(i+1));
}
}
}
Variable Description:
S.No. Variable Data Type Description
1. n int To aceept no of participants.
2. A char An array to store answers of every
participants.
3. k char An array to store answer key.
4. i,j int Loop variables.
5. s int An array to store scores of every
participant.
6. max int To store the highest score.
123
Input/Output:
124
Bibliography
From www.javaforschool.com
From www.javaguide.com
From www.guideforschool.com