Computer Science Project
NAME: Anshit Kumar Srivastava
TOPIC: JAVA programs
UID:
ACKNOWLEDGEMENT
I would like to express my sincere gratitude to my Computer Science
teacher, Ms. Pooja Agarwal, for her valuable guidance, support, and
encouragement throughout the completion of this project. Her insightful
suggestions and constant motivation helped me in understanding and
implementing the concepts effectively.
I am also thankful to City Montessori School for providing me with the
facilities and opportunities to carry out this project successfully.
Finally, I extend my heartfelt thanks to my parents and friends for their
cooperation, encouragement, and continuous support.
PROGRAMS
PROGRAM 1- A company manufactures packing cartons in four sizes
i.e. cartons in accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes.
Design a program to accept the number of boxes to be packed (N) by user
(maximum up to 1000 boxes) and display the break-up of the cartons used
in descending order of the capacity(i.e. Preference should be given to the
highest capacity available).
ALGORITHM
Step one: start
Step two: create the void main function
Step three: create the object of the scanner class to input the number of
cartons by user Step four: declare an array with the specific storage of
cartons to evaluate the number of cartons required to match the input by
user
Step five: declare a sum variable to add all the number of cartons required
Step six: run a loop till the input by user is not less than 6
Step seven: run a nested loop from the starting of the array till the end
Step eight: evaluate the number of cartons of sizes required and add them
in the sum variable
Step nine: print according to the format given in the question
Step ten: calculate the remaining carton of the input for it to be again
calculated in the loop
Step eleven: print the total number of cartons and the remaining cartons
Step twelve: end
PROGRAMMING
import java.util.*; class cartons
{ public static void main()
Scanner sc=new Scanner(System.in); System.out.println("Enter the no. of
cartons"); int n=sc.nextInt();
System.out.println("Total no. of boxes:"+n); int r=0; int s=0;
int a[]={48,24,12,6,2};
while(n>6)
for(int i=0;i<5;i++)
r=n/a[i]; s=s+r;
System.out.println(a[i]+"*"+r+"="+(a[i]*r)); n=n%a[i];
System.out.println("Total no. of cartons:"+s);
System.out.println("Remaining Boxes:"+n);
}
VD TABLE
VARIABLE USE
n No. of boxes input from user
a[] The sizes of boxes available
r No. of cartons required of each size
s Total cartons required
OUTPUT:-
PROGRAM 2-Give two positive numbers M and N, such that M is between
100 and 1000 and N is less than 100. Find the smallest integer that is
greater than M and whose digits add up to N. For example if M=10 and N=
11, then the smallest integer greater than 100 whose digits add up to 11 is
119.
Write a program to accept the numbers M and N from the user and print
the smallest required number whose sum of all its digits is equal to N. Also
print the total number of digits present in the required number. The
program should check for validity of the inputs and display an appropriate
message for an invalid input.
ALGORITHM
Step one: start
Step two: create a int returning parameterised sum function. Step three:
declare a sum variable
Step four: find the sum of the number and return
Step five: create a int returning parameterised count function. Step six:
declare a count variable
Step seven: count the digits of the number and return it Step eight: create
the void main function
Step nine: create the object of the class
Step ten: create the object of the scanner class to input the range from
user Step eleven: return invalid input if range is greater than 10000 or less
than 100 and the number entered by user is greater than equal to 100
Step twelve: run a loop from m and check if the sum of any of the number
from the range is equal to the number inputted and break the loop
Step thirteen: print the required number along with the count Step
fourteen: end
PROGRAM
import java.util.*; class smallestinteger
{ int sum(int x){
int s=0; while(x!=0)
{ int d=x%10; s=s+d; x=x/10;
return s;
int count(int x)
int c=0; while(x!=0)
int d=x%10; c++;
x=x/10;
}return c;
public static void main()
{ smallestinteger ob=new smallestinteger(); Scanner sc=new Scanner
(System.in); System.out.println("Enter m and n");
int m=sc.nextInt(); int n=sc.nextInt();
if(m>10000||m<100||n>=100)
{System.out.println("Invalid input"); return;
for(int i=m;;i++)
if(ob.sum(i)==n)
{System.out.println("The required no. is:"+i); System.out.println("Total no.
of digits are:"+ob.count(i)); break;
VD TABLE
VARIABLE USE
x Formal parameter to accept values from actual parameter
d Digit extraction
s Sum of digits
c Count of digits
m Lower range from user
n Upper range from user
OUTPUT:-
Program-3
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 input a no. to be checked
STEP-3 check whether the no. is increasing, decreasing or not
STEP-4 if the no. is increasing then print that the no. is increasing
STEP-5 if the no. is decreasing then print that no. is decreasing
STEP-6 if no. does not satisfies above conditions then print that no. is
bouncy no.
STEP-7 END
SOURCE CODE
import java.util.*;
class BouncyNumber
{
boolean isIncreasing(int n) //Function to check whether a number
Is increasing or not
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)) // If any digit is more than next
digit
f = 1;
break;
if(f==1)
return false;
else
return true;
}
boolean isDecreasing(int n) // to check whether a number is
decreasing or not
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)) // If any digit is less than next digit
f = 1;
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”);
else if(isDecreasing(n)==true)
System.out.println("The number " + n + " is Decreasing”);
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);
}}
Variable Data
Description
Name Type
Number entered by the user to check for bouncy
n int
property.
Variable Data
Description
Name Type
s String String representation of the number n.
Stores a digit (character) of the number during
ch char
comparison.
Flag variable to indicate if the number breaks the
f int
condition.
Loop control variable used for traversing the
i int
digits.
OUTPUT
Program- 4
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.
For example, 197 is a Keith number since it generates the sequence
1, 7, 9, 17, 33, 57, 107, 197, ………..
Some Keith numbers are: 14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537 ……
Algorithm
STEP-1 start
STEP-2 input the number
STEP-3 convert the inputted number into string
STEP-4 find the numbers in the digit
STEP-5 initialize the array for storing the terms of the series
STEP-6 store the digits of the number in the array
STEP-7 find the sum till the it less than the number
STEP-8 initialize the loop for generating and adding p
STEP-9 store the sum in array
STEP-10 condition if(sum==n)
STEP-11 print appropriate message according to the given condition
result
STEP-12 end
Source code
import java.util.*;
class Keith
public static void main()
Scanner sc = new Scanner(System.in);
System.out.print("\n Enter a number : ");
int n = sc.nextInt();
int copy=n;
String s=Integer.toString(n);
int d=s.length();
int arr[]=new int[n];
for(int i=d-1; i>=0; i--)
arr[i]=copy%10;
copy=copy/10;
}
int i=d,sum=0;
while(sum<n)
sum = 0;
for(int j=1; j<=d; j++)
sum=sum+arr[i-j];
arr[i]=sum;
i++;
if(sum==n)
System.out.println("The number is a Keith Number");
else
System.out.println("The number is a not a Keith Number");
Variable Data
Description
Name Type
n int Stores the number entered by the user.
copy int Stores a copy of n used to extract digits.
Variable Data
Description
Name Type
Stores the string representation of n to find number
s String
of digits.
d int Stores the count of digits in the number.
Array to store digits of n and the terms of the
arr int[]
generated sequence.
i int Index variable for arr, used in sequence generation.
Stores the sum of the previous d terms in the
sum int
sequence.
Loop counter to calculate sum from previous d
j int
terms.
OUTPUT:
Program-5
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:
(i)Output the original matrix.
(ii) Find the SADDLE POINT for the matrix. If the matrix has no saddle point,
output the message “NO SADDLE POINT”.
[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.]
Example: In the Matrix
456
789
513
Saddle point = 7 because it is the minimum element of row 2 and
maximum element of column 1
Algorithm
STEP-1 start
STEP-2 inputting the elements in the matrix
STEP-3 printing original matrix
STEP-4 finding the minimum element of row
STEP-5 finding the maximum element in the column
STEP-6 checking condition, the minimum element of row is equal to
maximum element of its corresponding columns
STEP-6 printing appropriate message according to the given condition
STEP-7 end
Source code
import java.util.*;
class SaddlePoint
public static void main()
Scanner sc = new Scanner(System.in);
System.out.print("Enter the order of the matrix : ");
int n = sc.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]= sc.nextInt();
}
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]<min)
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("********************");
}}}
VD
TABLE:-
Data
Variable Name Description
Type
N int Stores the order of the square matrix.
A int[][] 2D array to store matrix elements.
I int Loop counter variable for rows.
J int Loop counter variable for columns.
min int Stores the minimum element of a row.
Stores the column index of the row’s minimum
X int
element.
Stores the maximum element of the column
max int
corresponding to the row minimum.
Loop counter variable for scanning column
K int
elements.
Flag variable to indicate if saddle point is found (1
F int
= found, 0 = not).
Output:
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
of 1’s in its binary equivalent.
Example: Binary equivalent of 9 is 1001, which contains even number of
1’s. A few evil numbers are 3, 5, 6, 9….
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
INPUT:15
BINARYEQUIVALENT: 1111
NO. OF 1’s: 4
OUTPUT: EVIL NUMBER
ALGORITHM
STEP -1 start
STEP -2 Input the numbers in n
STEP-3 convert the decimal number Into binary number
STEP-4 change binary number in string.
STEP -4 Count the number of 1’S present in string.
STEP-6 if number of 1’s are even then it is evil number.
STEP-7 end
SOURCE CODE
import java.util.*;
class EvilNumber
String toBinary(int n) // Function to convert dec to bin
int r;
String s=""; //variable for binary digits
char dig[]={'0','1'}; //array of binary digits
while(n>0)
r=n%2; //finding remainder
s=dig[r]+s; //concatenating 0 or 1
n=n/2;
return s;
}
int countOne(String s) // Function to count number of 1’s
int c = 0, l = s.length();
char ch;
for(int i=0; i<l; i++)
ch=s.charAt(i);
if(ch=='1')
c++; //counting 1’s
return c;
public static void main()
EvilNumber ob = new EvilNumber();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number");
int n = sc.nextInt();
String bin = ob.toBinary(n);
System.out.println("Binary Equivalent"+bin);
int x = ob.countOne(bin);
System.out.println("Number of 1’s"+x);
if(x%2==0)
System.out.println(n+" Evil number");
else
System.out.println(n+" Not a evil number");
Variable Data
Description
Name Type
N int Stores the number entered by the user.
Stores remainder when n is divided by 2 (for binary
R int
conversion).
S String Stores the binary equivalent of the number.
dig char[] Array storing binary digits '0' and '1'.
C int Counter to store number of 1’s in the binary string.
L int Stores the length of the binary string.
Temporarily stores each character of the binary
Ch char
string while counting.
Stores the binary equivalent of n returned by
bin String
toBinary().
X int Stores the count of 1’s returned by countOne(bin).
Output:
PROGRAM 7- Write a program to declare a square matrix A[][] of order
(M×M) where M must be greater than 3 and less than 10. Allow the user to
input positive intergers into this matrix. Perform following tasks on the
matrix. [2016] (a) Sort the non boundry elements in ascending order using
any standard sorting technique and rearrange them in matrix. (b)
Calculate the sum of both the diagonals. (c) Display the original matrix,
rearranged matrix and only the diagonal elements of the rearranged
matrix with their sum.
ALGORITHM
Step one: start
Step two: create the void main function
Step three: create the object of the scanner class Step four: enter the
size(m) of the matrix
Step five: if the size is less than 3 or greater than 10 print invalid input Step
six: create a double dimensional array of size m*m
Step seven: create a single dimensional array of size (m-2)(m-2)
Step eight: create a variable to help in the input of the single dimensional
array Step nine: run a nested loop to input the numbers in the double
dimensional array Step ten: store all the non boundary elements in the
single dimensional array Step eleven: print the original Matrix
Step twelve: sort the single dimensional array using the bubble sort
technique
Step thirteen: run a nested loop where the outer loop goes from 1 to m-1
and inner loop goes from 1 to m-1 and store the sorted non boundary
elements of the single dimensional array in the double dimensional array
Step fourteen: print the arranged matrix
Step fifteen: calculate the sum of the diagonal elements by creating a sum
variable and storing the sum of diagonal elements of the matrix
Step sixteen: print the sum Step seventeen: end
PROGRAM
import java.util.*; class ascending
public static void main()
Scanner sc=new Scanner(System.in); System.out.println("Enter the size of
the matrix"); int m=sc.nextInt();
if(m<3||m>10)
System.out.println("Invalid size"); return;
int a[][]=new int[m][m];
int b[]=new int[(m-2)*(m-2)]; int c=0;
for(int i=0;i<m;i++)
for(int j=0;j<m;j++)
a[i][j]=sc.nextInt();
if(i!=0&&i!=m-1&&j!=0&&j!=m-1) b[c++]=a[i][j];
}System.out.println("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();
for(int i=0;i<b.length;i++)
for(int j=0;j<b.length-1;j++)
if(b[j]>b[j+1])
int temp=b[j]; b[j]=b[j+1]; b[j+1]=temp;
}
c=0;
for(int i=1;i<m-1;i++)
for(int j=1;j<m-1;j++)
a[i][j]=b[c++];
System.out.println("Arranged 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();
System.out.println("Sum of diagonal elements"); int s=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
if(i==j||i+j==m-1)
s=s+a[i][j]; System.out.print(a[i][j]+"\t");
else System.out.print("\t");
System.out.println();
System.out.println(s);
}}
VD TABLE
VARIABLE USE
M Size of array from user
a[] Double dimensional array
b[] Single dimensional array
C Index number
S Sum of corner elements
OUTPUT:-
PROGRAM 8- 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 a vertical order, side
by side with a horizontal tab (i.e. eight spaces).
ALGORITHM
Step one: Start.
Step two: Define a class banner:
In the main method, prompt the user to enter the number of teams (N) and
then validate the input: Check if n is between 3 and 8 inclusive. If not, print
"INVALID INPUT" and exit the program.
Step three: Take input for team names and create a double dimensional
character array and with dimensions N x 100 to store team names. Use a
loop to take input for each team name and store it in the array.
Step four: Display the banner: Use nested loops to iterate through each
character position (column) in the array and for each column, print the
characters of all teams in the same row. If a team's name is shorter than
the current column, print a space. Break the loop when all teams have
been printed, and no characters are left.
Step five: End.
PROGRAM
import java.util.*; class banner
public static void main()
{
Scanner sc=new Scanner(System.in); System.out.println("Enter the no. of
teams"); int n=sc.nextInt();
if(n<3||n>8)
System.out.println("Invalid no. of teams"); return;
char ch[][]=new char[n][100]; System.out.println("Enter the names of the
team");
for(int i=0;i<n;i++)
String s=sc.nextLine(); for(int j=0;j<s.length();j++) ch[i][j]=s.charAt(j);
int f=1;
for(int i=0;i<100;i++)
f=1;
for(int j=0;j<n;j++)
System.out.print(ch[j][i]+"\t");
if(ch[j][i]!='\u0000') f=f*0;
}
System.out.println(); if(f==1)
break;
VD TABLE
VARIABLE USE
N No. of teams from user
ch[][] Stores the characters of the team
name’s
S Name of team from user
OUTPUT:-
PROGRAM 9- A circular prime is a prime number with the property that the
number generated at each intermediate step when cyclically permuting its
digits will be prime. For example, 1193 is a circular prime, since 1931, 9311
and 3119 all are also prime.
ALGORITHM
Step one: start
Step two: create a returning parameterised function function prime to
check if the number is prime or not
Step three: create a count variable
Step four : run a loop from 1 till that number and check the number of
factors of tht number by increasing the count
Step five: if count= 2 then it is prime otherwise no Step six: create the void
main function
Step seven: create the object of the scanner class to input the number from
user Step eight: convert the number to string
Step nine: calculate the length of string Step ten: create a flag variable
Step eleven: run a loop from 0 to length of number of number Step twelve:
convert the string back to int
Step thirteen: check if the number is prime or not, if not then change the
value of flag
Step fourteen: change the order of the number and shift it's first number to
last . Step fifteen: check if flag value has changed, if not then all numbers
were circulate prime otherwise no.
Step sixteen: end
PROGRAM
import java.util.*; class circularprime
int prime(int n)
int i,c=0;
for(i=1;i<=n;i++)
if(n%i==0) c++;
return c;
public void main()
Scanner sc=new Scanner(System.in); System.out.println("Enter the no.");
int k=sc.nextInt(); String s=""+k;
int l=s.length(); int f=1;
for(int i=0;i<l;i++)
{
int m=Integer.parseInt(s); if(prime(m)!=2)
f=0;
System.out.print(s+"\t"); s=s.substring(1)+s.charAt(0);
if(f==1)
System.out.println("Circular Prime"); else
System.out.println("Not circular prime");
}}
VD TABLE
VARIABLE USE
N Formal parameter to accept
number from actual parameter
C Counter of factors
K Number input from user
OUTPUT:-
PROGRAM 10-Write a program to accept a sentence which may be
terminated by either '.', '?' or '!' only. The words are to be separated by a
single blank space and are in UPPER CASE. Perform the following tasks:
1. Check for the validity of the accepted sentence only for the terminating
character.
2. Arrange the words in ascending order of their length. If two or more words
have the same length, then sort them alphabetically.
3. Display the original sentence along with the converted sentence.
ALGORITHM
Step one: start
Step two: create the main function
Step three: create the object of the scanner class to input the string by user
Step four: input the string
Step five: if the string does not end with ".", "!" Or "?" Then print invalid
input and exit Step six: convert the string to uppercase
Step seven: create an array of string by using the split function
Step eight: arrange the words of the string according to their length using
the bubble sort technique of the length of the two words are equal then
arrange them according to the alphabetical order of their first letter only.
Step nine: print the converted strong Step ten: end
PROGRAM
import java.util.*; class lowtohigh
public static void main()
Scanner sc=new Scanner(System.in);
System.out.println("Enter the sentence"); String ss=sc.nextLine();
if(ss.charAt(ss.length()-1)!='.'&&ss.charAt(ss.length()-1)!
='?'&&ss.charAt(ss.length()-1)!='!')
System.out.println("Invalid input"); return;
ss=ss.toUpperCase(); System.out.println("Original String:"+ss);
ss=ss.substring(0,ss.length()-1);
String s[]=ss.split(" "); for(int i=0;i<s.length;i++)
for(int j=0;j<s.length-i-1;j++)
if(s[j].length()>s[j+1].length())
String temp=s[j]; s[j]=s[j+1]; s[j+1]=temp;
}
if(s[j].length()==s[j+1].length())
if(s[j].compareTo(s[j+1])>0)
String temp=s[j]; s[j]=s[j+1]; s[j+1]=temp;
System.out.println("Converted String:"); for(int i=0;i<s.length;i++)
System.out.print(s[i]+" ");
VD TABLE
VARIABLE USE
Ss String input from user
s[] String broken into words
temp Temporary variable used to store
the array element
OUTPUT:-
PROGRAM 11. A prime- Adam integer is a positive integer (without leading
zeros) which is a prime as well as an Adam-number. [2020] Adam number:
The Square of a number and the square of its reverse are reverse to each
other. Ex: if n=13 and reverse of n=31, then (13) 2 =169 (31) 2=961 which is
reverse of 169 Thus, 13, is an Adam number. Accept two positive integers
m and n, where m is less than n as user input. Display all prime-Adam
integers that are in range between m and n (both inclusive) and output
them along with the frequency.
ALGORITHM
Step one: start
Step two: create a returning parameterised function reverse
Step three: extract the digits of the number and reverse the original
number Step four: create a static void main function
Step five: create the object of the class to call the functions
Step six: create the object of the scanner class and input the range
Step seven: find the minimum and maximum of the two number range
inputted by user
Step eight: declare a counter variable and frequency variable and flag
variable Step nine: run a loop from the minimum number to the maximum
number
Step ten: run a loop to check if the number in the range is prime or not by
increasing the count of the factors from one till that number
Step eleven: check if the square of reverse of original number is reverse of
square of the original number and the reversed original number and
original number is prime or not.
Step twelve: if the condition of step eleven evaluates to true then print the
particular number and increase the frequency.
Step thirteen: if no Adam prime numbers could be found within the range
specified print the suitable statement.
Step fourteen: end
PROGRAM
import java.util.*; class primeadam
int reverse(int a)
{ int rev=0; while(a!=0)
int d=a%10; rev=rev*10+d; a=a/10;
return rev;
static void main()
primeadam ob=new primeadam(); Scanner sc=new Scanner(System.in);
System.out.println("Enter the range:"); int a=sc.nextInt();
int b=sc.nextInt();
int m=Math.min(a,b); int n=Math.max(a,b); int f=0,f1=0;
for(int i=m;i<=n;i++)
int c=0;
for(int j=1;j<=i;j++)
{ if(i%j==0) c++;
if(ob.reverse(i*i)==(ob.reverse(i)*ob.reverse(i))&&c==2)
if(f==0)
f=1;
System.out.println("THE PRIME-ADAM INTEGERS ARE:");
System.out.print(i+"\t"); f1++;
System.out.println("\n FREQUENCY IS:"+f1); if(f==0)
System.out.println("No adam prime number could be found.");
}}
VD TABLE
VARIABLE USE
rev Store and return the reverse of the
no.
A Formal parameter
D Digit extraction
A Input from user
B Input from user
F Used as a flag
f1 Frequency
C Counter
OUTPUT:-
PROGRAM 12.Write a program to input a number and check whether it is
a Buzz number or not.
Buzz number- Checking if a number ends with 7 or is divisible by 7.
import java.util.*;
public class BuzzNumber
public static void main()
Scanner sc = new Scanner(System.in);
// Step 1: Input number
System.out.print("Enter a number: ");
int n = sc.nextInt();
// Step 2: Check Buzz Number
if (n % 7 == 0 || n % 10 == 7)
System.out.println(n + " is a Buzz Number.");
else
{
System.out.println(n + " is NOT a Buzz Number.");
ALGORITHM
1. Start
2. Input a number n from the user.
3. Check if n % 7 == 0 OR last digit of n is 7 (n % 10 == 7).
4. If either condition is true → print "Buzz Number".
5. Otherwise → print "Not a Buzz Number".
6. End
VARIABLE DESCRIPTION TABLE
VARIABLE DATATYPE DESCRIPTION
N int To enter a number
OUTPUT:-
Program-12
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 a maximum of 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 input the sentences having different no. of words
STEP-3 check for the condition that no. of sentences are not more
than 10
STEP- 4 count the no. of words in each sentence
STEP-5 arrange the sentences in ascending or descending order
according to the no. of sentences present in the sentence
STEP-6 print the results
STEP-7 END
SOURCE CODE
import java.util.*;
class sortParagraph
// Function to count no. of words in every sentence
int countWords(String s)
StringTokenizer str = new StringTokenizer(s," .,?!");
int c = str.countTokens();
return c;
} // Function to sort the sentences in ascending order of their no. of
words
void sort(String w[], int p[])
int n = w.length, t1 = 0;
String t2 = "";
for(int i=0; i<n-1; i++)
for(int j=i+1; j<n; j++)
{
if(p[i]>p[j]) // for descending use p[i]<p[j]
t1 = p[i];
p[i] = p[j];
p[j] = t1;
t2 = w[i];
w[i] = w[j];
w[j] = t2;
printResult(w,p); // Calling function for printing the result
void printResult(String w[], int p[]) // Function to print the result
int n = w.length;
for(int i=0; i<n; i++)
System.out.println(w[i]+"\t=\t"+p[i]);
public static void main(String args[])
{
sortParagraph ob = new sortParagraph();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a paragraph : "); //Inputting a paragraph
String pg = sc.nextLine();
StringTokenizer str = new StringTokenizer(pg,".?!");
int count = str.countTokens(); //Counting no. of sentences in it
if(count > 10)
System.out.println("A maximum of 10 sentences are allowed i
else
String sent[] = new String[count]; //Array to store the sentence
int p[] = new int[count]; //Array to store no. of words
for(int i=0; i<count; i++)
sent[i] = str.nextToken().trim(); // Saving sentences
p[i] = ob.countWords(sent[i]); // Saving no. of words
ob.sort(sent,p);
}
Variable Description Table
Data Type Variable Description
Int c,n,count To store the number of words in every
sentence
Int p[] Array to store number of words in a part
of paragraph
String pg To store the paragraph entered by user
Int i,j As looping variables
String sent[] Array to store sentences
String w Formal parameter
OUTPUT
Program-13
Write a program to print the words of the input in reverse order without
any punctuation marks other than blanks.
For example, Consider the following input text:
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.
Sample Output: Cover its by book a judge not do
Algorithm:
Step 1 Start
Step 2 Enter the number of sentences.
Step 3 Initialize for loop and for inputting multiple sentences and
joining them.
Step 4 Convert the sentence into String Tokenizer using
StringTokenizer function.
Step 5. Using nextToken() extract one word at a time
Step 6 Then join the extracted words in reverse order.
Step 7 Print the reversed string.
Step 8 end
Source Code
import java.io.*;
import java.util.*;
class Sent_Merge_Rev
public static void main(String args[])throws IOException
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the number of sentences: ");
int n = Integer.parseInt(br.readLine());
String s = "";
for(int i=1; i<=n; i++)
System.out.print("Enter Sentence "+i+": ");
s = s + br.readLine();
}
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);
Variable Description Table
Data Type Variable Description
Int n,c To store the number of sentences and
words respectively.
String S, w To store the input sentence and next word
respectively
String rev To store the reversed string
Int i,j As looping variables
Output:-
Program-14
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 input a square matrix of size n where n<=10
Step-3 input the three characters
Step-4 fill the upper and lower elements formed by the interaction
diagonals by character 1
Step-5 fill the left and right elements formed by the interaction of
diagonals character 2
Step-6 fill the diagonals by character 3
Step-7 print the original matrix
Step-8 print the modified matrix
Step-9 end
SOURCE CODE
import java.util.*;
class MatrixFill
public static void main()
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))
A[i][j] = c3; // Filling the diagonals with 3rd
else
A[i][j] = c2; // Filling all other positions wi
for(int i=0; i<n/2; i++)
for(int j=i+1; j<n-1-i; j++)
A[i][j] = c1; // Filling the upper positions formed
A[n-1-i][j] = c1; // Filling the lower positions fo
// Printing the Matrix
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 Table
Data Type Variable Description
Int N To store the size of the matrix
char A[][] To store the characters in the matrix
entered by the user
char c1,c2,c3 To store the user entered first second and
third character respectively
Int i,j As looping variables
OUTPUT:-
Program-15
Write a Program in Java to input two 2-D arrays and perform Matrix
Multiplication:.
Algorithm
STEP-1 start
STEP-2 declaration of function for printing a square matrix
STEP-3 initialization of rows and columns of 1st and 2nd matrix
respectively
STEP-4 giving condition for multiplication to be possible
if(c1 = r2)
STEP-5 print message if condition is false
STEP-6 initialize 1stand 2nd array and another array to store
multiplied matrix
STEP-7 matrix multiplication (1st and 2nd) started
STEP-8 printing all matrix
STEP-9 end
Source code
import java.util.*;
class MatrixMultiplication
void printMatrix(int P[][], int r, int c)
for(int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
System.out.print(P[i][j]+"\t");
System.out.println();
public static void main(String args[])throws Exception
MatrixMultiplication ob = new MatrixMultiplication();
Scanner sc = new Scanner(System.in);
System.out.print("Enter no. of rows of 1st Matrix : ");
int r1=sc.nextInt();
System.out.print("Enter no. of columns of 1st Matrix : ");
int c1=sc.nextInt();
System.out.print("Enter no. of rows of 2nd Matrix : ");
int r2=sc.nextInt();
System.out.print("Enter no. of columns of 2nd Matrix : ");
int c2=sc.nextInt();
if(c1 != r2) // Checking Condition for Multiplication to be possible
{
System.out.println("Matrix Multiplication of the given order is not
possible");
else
int A[][]=new int[r1][c1]; // Array to store 1st Matrix
int B[][]=new int[r2][c2]; // Array to store 2nd Matrix
int C[][]=new int[r1][c2]; // Array to store Result of
Multiplied matrix
System.out.println("*************************");
System.out.println("Inputting the 1st Matrix");
System.out.println("*************************");
for(int i=0; i<r1; i++)
for(int j=0; j<c1; j++)
System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
System.out.println("*************************");
System.out.println("Inputting the 2nd Matrix");
System.out.println("*************************");
for(int i=0; i<r2; i++)
for(int j=0; j<c2; j++)
System.out.print("Enter an element : ");
B[i][j]=sc.nextInt();
int sum = 0;
for(int i=0; i<r1; i++)
for(int j=0; j<c2; j++)
for(int k=0; k<c1; k++)
sum = sum + A[i][k]*B[k][j];
C[i][j]=sum;
sum=0;
}
System.out.println("n*************************");
System.out.println(" Output ");
System.out.println("*************************");
System.out.println("The 1st Matrix is");
ob.printMatrix(A,r1,c1);
System.out.println("*************************");
System.out.println("The 2nd Matrix is");
ob.printMatrix(B,r2,c2);
System.out.println("************************************");
System.out.println("The Result of Multiplication is");
ob.printMatrix(C,r1,c2);
Variable Description Table
Data Type Variable Description
Int r,c,r1,c1,r To store number of rows and columns
2,c2 respectively
Int A[][] Integer arrays
Int sum To store elements of resultant array
Int i,j,k As looping variables
OUTPUT:-
PROGRAM 16-A special two-digit number is such that when the sum of
its digits is added to the product of its digits, the result is equal to the
original two-digit number.
Example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits
to the product of its digits. If the value is equal to the number input, then
display the message "Special two—digit number" otherwise, display the
message "Not a special two-digit number".
SOURCE CODE:-
import java.util.Scanner;
public classSpecialNumber
public static void main()
Scanner in = new Scanner(System.in);
System.out.print("Enter a 2 digit number: ");
int orgNum = in.nextInt();
int num = orgNum;
int count = 0, digitSum = 0, digitProduct = 1;
while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
digitProduct *= digit;
count++;
if (count != 2)
System.out.println("Invalid input, please enter a 2-digit number");
else if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");
Algorithm
Start.
Step 2: Input a 2-digit number orgNum.
Step 3: Copy orgNum into variable num and initialize count = 0, digitSum =
0, digitProduct=1.
Step 4: Extract last digit and add digit to digitSum
Step 5:Multiply digit with digitProduct.
Increment count by 1.
Step 6: If count 2, then print "Invalid input, please enter a 2-digit number".
Step 7: Else check if (digitSum + digitProduct) == orgNum.
Step 8: If true, print "Special 2-digit number".
Otherwise, print "Not a special 2-digit number"
Stop.
VD TABLE:-
OUTPUT:-
PROGRAM 17:Write a program to declare a square matrix A[][] of order
M × M 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:
(a) Display the original matrix.
(b) Check if the given matrix is said to be symmetric or not. A square
matrix is said to be symmetric, if the element of the ith row and jth
column is equal to the element of the jth row and ith column.
(c) Find the sum of the elements of left diagonal and the sum of the
elements of right diagonal of the matrix and display them.
Example 1
INPUT:
M=3
Enter elements of the matrix:
123
245
356
OUTPUT:
ORIGINAL MATRIX
123
245
356
THE GIVEN MATRIX IS SYMMETRIC.
THE SUM OF THE LEFT DIAGONAL = 11
THE SUM OF THE RIGHT DIAGONAL = 10
Example 3
INPUT: M = 12
OUTPUT: SIZE IS OUT OF RANGE.
import java.util.Scanner;
class Symmetric
int A[][]:
int M;
Symmetric(int size)
{M=size:
A = new int[M][M];
void accept()
{ if(M>2&& M < 10 )
{Scanner sc=new Scanner(System.in);
System.out.println("Enter elements of the Matrix");
for(int i = 0; i < M ;i++)
{ for( int j = 0; j < M; j++)
{
A[i][j]=sc.nextInt;}}
else
{ System.out.println("THE MATRIX SIZE IS OUT OF RANGE");
System.exit(0); }
public void display_Original()
{ System.out.println("ORIGINAL MATRIX");
for(int i = 0; i < M ;i++)
{ for(int j = 0;j < M;j++)
System.out.print[i][j]+" ");
System.out.printin():}
public void checkSymmetric()
{ int flag=1;
for(int i = 0; i < M; i++)
{ for( j = 0; j < M; j++)
if(A[i][j]!=[j][i])
{flag=0; break; }}}
if(flag==1)
System.out.println("THE GIVEN MATRIX IS SYMMETRIC");
else
System.out.println("THE GIVEN MATRIX IS NOT SYMMETRIC");
public void compute()
int sumLD=0,sumRD=0;
for(int i=0;i<M;i++) {
for(int j=0;j<M:j++) {
if(i==j)
sumLD+=A[i][j];
if((i+j)==M)
sumRD+=A[i][j]; }}
System.out.println("The sum of the left diagonal= "+sumLD);
System.out.println("The sum of the right diagonal="+sumRD);
public static void main(String args[])
Scanner sc=new Scanner(System.in);
System.out.print("Enter size of Matrix: ");
int size=sc.nextInt();
Symmetric obj=new Symmetric(size);
obj.accept(); obj.display Original();
obj.checkSymmetric();
obj.compute();
}}
Algorithm
Start.
Step 1:Accepts user input for matrix size M.
Step 2:invalid sizes.
Step 3:Check if M is greater than 2 and less than 10.If not, display "SIZE IS
OUT OF RANGE." and Stop.
Step 4:Input the elements of the matrix and display the original matrix.
Step 5: To Check for Symmetry Initialize a flag variable.
Step 6:If A[i][j] != A[j][i], set flag = 0 and break.
If flag = 1, print symmetric with appropriate message
Step 7:Find diagonal sum.
Step 8:Display the sum of left and right diagonal with an apt message.
Stop.
VD TABLE:-
OUTPUT:-
PROGRAM 18:Give two positive numbers M and N, such that M is between
100 and 1000 and N is less than 100. Find the smallest integer that is
greater than M and whose digits add up to N. For example if M=10 and N=
11, then the smallest integer greater than 100 whose digits add up to 11 is
119.
Write a program to accept the numbers M and N from the user and print
the smallest required number whose sum of all its digits is equal to N. Also
print the total number of digits present in the required number. The
program should check for validity of the inputs and display an appropriate
message for an invalid input.
ALGORITHM
Step one: start
Step two: create a int returning parameterised sum function. Step three:
declare a sum variable
Step four: find the sum of the number and return
Step five: create a int returning parameterised count function. Step six:
declare a count variable
Step seven: count the digits of the number and return it Step eight: create
the void main function
Step nine: create the object of the class
Step ten: create the object of the scanner class to input the range from
user Step eleven: return invalid input if range is greater than 10000 or less
than 100 and the number entered by user is greater than equal to 100
Step twelve: run a loop from m and check if the sum of any of the number
from the range is equal to the number inputted and break the loop
Step thirteen: print the required number along with the count Step
fourteen: end
PROGRAM
import java.util.*;
class smallestinteger
{ int sum(int x)
int s=0; while(x!=0)
{ int d=x%10; s=s+d; x=x/10;
}return s;
int count(int x)
int c=0; while(x!=0)
int d=x%10; c++;
x=x/10;
}return c;
public static void main()
{ smallestinteger ob=new smallestinteger(); Scanner sc=new Scanner
(System.in); System.out.println("Enter m and n");
int m=sc.nextInt(); int n=sc.nextInt();
if(m>10000||m<100||n>=100)
{System.out.println("Invalid input"); return;
for(int i=m;;i++)
if(ob.sum(i)==n)
{System.out.println("The required no. is:"+i); System.out.println("Total no.
of digits are:"+ob.count(i)); break;
}}}}
VD TABLE
VARIABLE USE
X Formal parameter to accept values
from actual parameter
D Digit extraction
S Sum of digits
C Count of digits
M Lower range from user
N Upper range from user
OUTPUT:-
PROGRAM 19-Design a program to accept a day number (between
1 and 366), year (in 4 digits) from the user to generate and display
the corresponding date. Also accept ‘N’ (1<=N<=100) from the
user to compute and display the future date corresponding to ‘N’
days after the generated date. Display an error message if the
value of the day number, year and N are within the limit or not
according to the condition specified.
ALGORITHM
Step one: start
Step two: create a parameterised returning function string date
Step three: create an array containg the days of all the months
Step four: if the year entered is a leap year then convert the days
of February to 29 Step five: if the days are greater than 365 and if
it is not a leap year then subtract 365 and a year to the year
entered otherwise subtract 366
Step six: create a string month contacting the names of all the
months
Step seven: run a loop to find the number of days till the days get
less than month days Step eight: when the days get less than the
month days store the position of the month and break the loop
Step nine: add "st", "rd", "nd" and "th" according to the date
acquired Step ten: return the date
Step eleven: create the main function
Step twelve: create the object of the scanner class to input the
days, and year and the number of days after
Step thirteen: if days entered are greater than 366 or less than 1
or year is greater than 9999 or the days entered after the current
days is not between 1 and 100 print invalid input
Step fourteen: print the date months and year by calling the
different function Step fifteen: end
PROGRAM
import java.util.Scanner; class prac6
{
String date(int d, int y)
{
int m[]={31,28,31,30,31,30,31,31,30,31,30,31}; if(y%4==0 && y
%100!=0 || y%400==0) m[1]+=1;
int mn=0; if(d>365)
{ if(m[1]==28) d-=365;
else
d-=366; y++;
}
String date=""; String month[] =
{"January","February","March","April","May","June","July","Augu
st","September","October", "November","December"};
for(int i=0;i<12;i++)
{
if(d<=m[i])
{
mn=i; break;
}
d-=m[i];
}
if(d%10==1 && d!=11) date+=d+"st ";
else if(d%10==2 && d!=12) date+=d+"nd ";
else if(d%10==3 && d!=13) date+=d+"rd ";
else date+=d+"th ";
date+=month[mn]+" "; date+=y;
return date;
}
public static void main()
{
Scanner sc = new Scanner(System.in); prac6 ob = new prac6();
System.out.println("Enter Day Number"); int day=sc.nextInt();
System.out.println("Enter Year"); int year=sc.nextInt();
System.out.println("Enter a number between 1 and 100"); int
N=sc.nextInt(); if(day>366||day<1||year>9999||N>100||N<1)
System.out.println("Invalid Input");
else
{
System.out.println("Day Number :"+day); System.out.println("Date
: "+ob.date(day,year));
System.out.println("Date after "+N+" days:
"+ob.date(day+N,year));
}}}
VD TABLE
VARIABLE USE
D Formal parameter to accept
value
Y Formal parameter to accept
value
m[] Store no. of days of every
month
Mn Store month no.
Date Stores the date which has to be
printed
month[] Stores the names of months
Day Day no. as input
Year Year as input
N Days after d of which days has
to be calculated
OUTPUT:-
PROGRAM 20- Write a program to check if a double dimensional array
is doubly markov or not an example of a Doubly Markov Matrix that
0.20 .30 .50
.30 .40 .30
.50 .30 .2
All elements are ≥0:.
Each row sums to 1:
Row 1: 0.2+0.3+0.5=1.0
Row 2: 0.3+0.4+0.3=1.0
Row 3: 0.5+0.3+0.2=1.0
Each column sums to 1:
Column 1: 0.2+0.3+0.5=1.0
Column 2: 0.3+0.4+0.3=1.0
Column 3: 0.5+0.3+0.2=1.0
Since all conditions are met, this matrix is a Doubly Markov Matrix.
PROGRAM
import java.util.Scanner;
public class markovdouble { public static void main()
Scanner sc = new Scanner(System.in); System.out.println("Enter value of
n"); int n = sc.nextInt();
double a[][] = new double[n][n];
if (n < 3 || n >= 9) { System.out.println("Invalid size"); sc.close();
System.out.println("Enter array elements"); for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) { a[i][j] = sc.nextDouble();
System.out.println("Entered 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();
int flag = 1;
for (int i = 0; i < n; i++) { double sumrows = 0.0; double sumcolumns = 0.0;
for (int j = 0; j < n; j++) { if (a[i][j] < 0.0) {
flag = 0; break;
sumrows += a[i][j];
for (int j = 0; j < n; j++) { sumcolumns += a[j][i];
if (flag == 0) { break;
}
if (sumrows != 1.0 || sumcolumns != 1.0) { flag = 0;
break;
if (flag == 1) {
System.out.println("The matrix is a Doubly Markov Matrix.");
} else {
System.out.println("The matrix is Not a Doubly Markov Matrix.");
ALGORITHM
Step 1: Start.
Step 2: Ask the user for the matrix size (N) and the matrix elements. Step
3: If N is not between 3 and 8 print "Invalid size" and stop.
Step 4: Assume the matrix is Doubly Markov (set a flag to "true").
Step 5: For each row (from first to last): a. Calculate the sum of numbers
in that row. b. Calculate the sum of numbers in the corresponding
column. c. Check if any number in the matrix is negative. If yes, set flag
to "false" and stop all checks. d. Check if the row sum is exactly 1.0. If
not, set flag to "false" and stop all checks. e. Check if the column sum is
exactly
1.0. If not, set flag to "false" and stop all checks.
Step 6: If the flag is still "true" after all checks, print "The matrix is a
Doubly Markov Matrix."
Step 7: Otherwise (if flag is "false"), print "The matrix is Not a Doubly
Markov Matrix."
Step 8: End.