Computer Project
Computer Project
ANUNAY NARAYAN
TRIVEDI
CLASS:
XII
SUBJECT:
COMPUTER SCIENCE
TOPIC:
JAVA PROGRAMS
UID:
94110003018
ACKNOWLEDGEMENT
I would like to express my sincere gratitude to all those who
contributed to the successful completion of this computer
science project.
First and foremost, I extend my deepest thanks to Mrs. Pooja
Agarwal, my Computer Science instructor, for her invaluable
guidance, encouragement, and constant support. Her expertise
not only helped me gain clarity on challenging concepts but
also inspired me to explore new ideas and push the boundaries
of my learning.
I am also thankful to my classmates and friends for their
constructive feedback and assistance during the development
process. Their valuable suggestions played a key role in
refining the project and improving its overall quality.
I gratefully acknowledge the resources provided by my school
which were instrumental in helping me to complete the
project.
Finally, I owe my heartfelt gratitude to my family for their
unwavering encouragement, patience, and support throughout
this journey. Their motivation has been the foundation of my
academic progress.
This project is the result of collective support and guidance,
and I sincerely thank everyone who made it possible.
PROGRAM-1
ALGORITHM
1. START.
2. Input the sentences having different number of words.
3. Check for the condition that number of sentences are not more
than 10
4. Count the number of words in each sentence.
5. Arrange the sentences in ascending or descending order
according to the no. of sentences present in the sentence.
6. Print the results.
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);
}
}
}
OUTPUT
PROGRAM-2
ALGORITHM
1. START.
2. Input a square matrix of size n where n<=10.
3. Input the three characters.
4. Fill the upper and lower elements formed by the interaction
diagonals by character 1.
5. Fill the left and right elements formed by the interaction of
diagonals by character 2.
6. Fill the diagonals by character 3.
7. Print the original matrix.
8. Print the modified matrix.
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
OUTPUT
PROGRAM-3
Write a Program in Java to input two 2-D arrays and perform Matrix
Multiplication.
ALGORITHM
1. START.
2. Declaration of function for printing a square matrix.
3. Initialization of rows and columns of 1st and 2nd matrix
respectively.
4. Giving condition for multiplication to be possible if(c1 = r2).
5. Print message if condition is false.
6. Initialize 1stand 2nd array and another array to store multiplied
matrix.
7. Matrix multiplication (1st and 2nd) started.
8. Printing all matrix.
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);
}
}
}
ALGORITHM
1. START.
2. Input a sentence.
3. Break the alphabets and rearrange them to form anagrams.
4. Print each anagram and count the no. of anagrams.
5. Print the number of anagrams.
6. END.
SORUCE CODE
import java.util.*;
class Anagrams
{
int c = 0;
void input ()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
String s = sc.next();
}
void display (String s1, String s2)
{
if (s2. length () <=1)
{
c++;
System.out.println(s1+s2);
}
else
{
for (int i=0; i<s2.length(); i++)
{
String x = s2. substring (i, i+1);
String y = s2. substring (0, i);
String z = s2. substring (i+1);
display (s1+x, y+z);
} }
System.out.println("The Anagrams are: ");
System.out.println(z);
System.out.println("Total Number of Anagrams = "+c);
}
public static void main ()
{
Anagrams ob=new Anagrams ();
ob.input();
}
}
VARIABLE DESCRIPTION TABLE
Data Type Variable Description
OUTPUT
PROGRAM-5
SOURCE CODE
import java.util.*;
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
1. START.
2. Input an integer n.
3. Check if n is prime:
o If n < 2, it is not prime.
o Otherwise check divisibility from 2 to √n. If divisible, not
prime.
4. If n is not prime → print "Not a Circular Prime" and stop.
5. Convert n to string s.
6. For each digit rotation (length of s times):
o Convert s to integer.
o Check if it is prime. If not → print "Not a Circular Prime"
and stop.
o Rotate string by moving first digit to the end.
7. If all rotations are prime → print "Circular Prime".
8. END.
SOURCE CODE
import java.util.*;
if (! prime)
{
isCircularPrime = false;
break;
}
// Rotate string
s = s.substring(1) + s.charAt(0);
}
}
}
OUTPUT
PROGRAM-7
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.
SOURCE CODE
import java.util.*;
}
}
VARIABLE DESCRIPTION TABLE
VARIABLE DATATYPE DESCRIPTION
n int To enter a number
OUTPUT
PROGRAM-8
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.
EX: Input: M=100
N=11
Output: The required number is = 119
Total number of digits=3
Input: M=1500
N=25
Output: The required number is= 1699
Total number of digits=4
Input: M=99
N=11
Output: Invalid Input
ALGORITHM
1. START.
2. Input two numbers M and N.
3. Check validity:
o M must be between 100 and 1000 (exclusive).
o N must be less than 100 and greater than 0.
o If invalid → print "Invalid Input!" and stop.
4. Set num = M + 1.
5. Repeat until solution is found:
o Calculate the sum of digits of num.
o If the sum equals N, stop.
o Otherwise increase num by 1 and repeat.
6. Print the required number (num).
7. Count the number of digits in num and print it.
8. END.
SOURCE CODE
import java.util.*;
// Step 1: Input
System.out.print("Enter value of M (100 < M < 1000)");
int M = sc.nextInt();
if (sum == N)
{
// Step 4: Count digits
int digits = 0;
temp = num;
while (temp > 0)
{
digits++;
temp = temp / 10;
}
OUTPUT
PROGRAM-9
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/w X/x Y/y Z/z
Write a program to accept a plain text of length L, where L must be
greater than 3 and less than 100.
Encrypt the text if valid as per the Caesar Cipher.
Test your program with the sample data and some random data.
Example 1
INPUT:
Hello! How are you?
OUTPUT:
The cipher text is:
Uryyb! Ubj ner lbh?
Example 2
INPUT:
Encryption helps to secure data.
OUTPUT:
The cipher text is:
Rapelcgvba urycf gb frpher qngn.
ALGORITHM
1. START.
2. Inputs a plain text input from the user.
3. Checks if the length of the text is less than 4 or greater than or
equal to 100, print "INVALID LENGTH" and stop.
4. Initialize an empty string encryptedText to store the encrypted
result.
5. Loop through each character of the input text.
6. If the character is an uppercase letter (A-Z):
a. Apply the ROT13 transformation: shift the letter by 13
places.
b. Append the transformed letter to encryptedText.
7. If the character is a lowercase letter (a-z):
a. Similarly, apply the ROT13 transformation and append the
result.
8. If the character is neither uppercase nor lowercase (like spaces,
punctuation), keep it unchanged and append it to encryptedText.
9. Prints the encrypted text (cipher text).
10. END.
SOURCE CODE
import java.util.Scanner;
OUTPUT
PROGRAM-10
ALGORITHM
1. START.
2. Ask the user to enter a natural number.
3. Check if the number is less than 1 or greater than or equal to
1000:
4. If yes, print "OUT OF RANGE" and stop.
5. If the number is less than 20, print the corresponding word
directly.
6. If the number is between 20 and 99:
7. Print the tens word (like TWENTY, THIRTY)
8. If the last digit is not zero, print the ones word after it.
9. If the number is 100 or more:
10. Print the hundred's place word + "HUNDRED"
11. If the last two digits are not zero, print "AND" and then
convert the last two digits as in steps 3 and 4.
12. END.
SOURCE CODE
import java.util.Scanner;
String [] ones = {
"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX",
"SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE",
"THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN",
"SEVENTEEN",
"EIGHTEEN", "NINETEEN"
};
String [] tens = {
"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY",
"SIXTY", "SEVENTY", "EIGHTY", "NINETY"
};
if (number < 20) {
System.out.println(ones[number]);
} else if (number < 100) {
int t = number / 10;
int o = number % 10;
if (o == 0) {
System.out.println(tens[t]);
} else {
System.out.println(tens[t] + " " + ones[o]);
}
} else {
int hundredPart = number / 100;
int remainder = number % 100;
if (remainder! = 0) {
System.out.print(" AND ");
OUTPUT
PROGRAM-11
An ISBN is a 10-digit code identifying a book. The first nine are digits
0–9; the 10th can be 0–9 or 'X' (representing 10).
To validate: sum = 10×d1 + 9×d2 + ... + 1×d10
If sum % 11 == 0, it's valid.
Your program should:
• Accept a 10-character input.
• Display "INVALID INPUT" if length ≠ 10.
• Otherwise compute sum, display it, and show:
o "LEAVES NO REMAINDER – VALID ISBN CODE" if sum % 11 ==
0
o else "LEAVES REMAINDER – INVALID ISBN CODE"
EXAMPLES: -
INPUT: 0201530821
OUTPUT: SUM = 99 LEAVES NO REMAINDER - VALID ISBN
CODE
INPUT: 035680324
OUTPUT: INVALID INPUT
ALGORITHM
1. START.
2. Ask the user to enter a 10-character ISBN code.
3. If the length is not 10, show "INVALID INPUT" and stop.
4. Set sum to 0.
5. For each of the 10 characters:
o If it's the 10th character and it's 'X', treat it as 10.
o Otherwise, convert the character to a number.
o Multiply the number by (10 - position number + 1).
o Add to the sum.
6. Show the total sum.
7. If the sum divides evenly by 11, show "LEAVES NO
REMAINDER – VALID ISBN CODE".
8. Else, show "LEAVES REMAINDER – INVALID ISBN
CODE".
9. END.
SOURCE CODE
import java.util.Scanner;
if (code.length() != 10) {
System.out.println("INVALID INPUT");
return;
}
int sum = 0;
for (int i = 0; i < 10; i++) {
char ch = code.charAt(i);
int digit;
if (i == 9 && ch == 'X') {
digit = 10;
} else if (Character.isDigit(ch)) {
digit = ch - '0'; // convert character to number
} else {
System.out.println("INVALID INPUT");
return;
}
int weight = 10 - i;
sum += weight * digit;
}
if (sum % 11 == 0) {
System.out.println("LEAVES NO REMAINDER - VALID ISBN
CODE");
} else {
System.out.println("LEAVES REMAINDER - INVALID ISBN
CODE");
}
}
}
OUTPUT
PROGRAM-12
Accept an uppercase sentence terminated by.,?, or ! with single-space
word separation.
Tasks:
• Count and display all palindromic words in the sentence (words that
read the same forwards and backwards).
• Show the total count of such words.
• If no palindromic words are found, print "NO PALINDROMIC
WORDS".
🔹 Example:
Input: MOM AND DAD ARE COMING AT NOON.
Output: MOM DAD NOON NUMBER OF PALINDROMIC WORDS:
3
ALGORITHM
1. START.
2. Asks the user to enter an uppercase sentence ending with ., ?, or
!.
3. Remove the last punctuation mark.
4. Split the sentence into words by spaces.
5. For each word:
o Check if it is a palindrome (same forwards and
backwards).
o If yes, print the word and increase the palindrome count.
6. If palindrome count is zero, print "NO PALINDROMIC
WORDS".
7. Otherwise, print the number of palindromic words found.
8. END.
SOURCE CODE
import java.util.Scanner;
int palindromeCount = 0;
String palindromicWords = "";
if (palindromeCount == 0) {
System.out.println("NO PALINDROMIC WORDS");
} else {
System.out.println(“PALINDROMIC WORDS ARE:”);
System.out.println(palindromicWords.trim());
System.out.println("NUMBER OF PALINDROMIC WORDS : " +
palindromeCount);
}
}
OUTPUT
PROGRAM-13
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
1. START.
2. Input a number to be checked.
3. Check whether the number is increasing, decreasing or not.
4. If the number is increasing, then print that the number is
increasing.
5. If the number is decreasing, then print that number is
decreasing.
6. If number does not satisfy above conditions, then print that
number is bouncy number.
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");
}
ALGORITHM
1. START.
2. Inputting the elements in the matrix.
3. Printing original matrix.
4. Finding the minimum element of row.
5. Finding the maximum element in the column.
6. Checking condition, the minimum element of row is equal to
maximum element of its corresponding columns.
7. Printing appropriate message according to the given condition.
8. END.
SOURCE CODE
import java.util.*;
class SaddlePoint
{
public static void main ()
{
Scanner sc = new Scanner(System.in);
Some Keith numbers are: 14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537
ALGORITHM
1. START.
2. Input the number.
3. Convert the inputted number into string.
4. Find the numbers in the digit.
5. Initialize the array for storing the terms of the series.
6. Store the digits of the number in the array.
7. Find the sum till the it less than the number.
8. Initialize the loop for generating and adding p.
9. Store the sum in array condition if(sum==n).
10. Print appropriate message according to the given
condition result.
11. 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 DESCRIPTION TABLE
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.
s String Stores the string representation of n to find number of digits.
d int Stores the count of digits in the number.
Array to store digits of n and the terms of the generated
arr int[]
sequence.
i int Index variable for arr, used in sequence generation.
sum int Stores the sum of the previous d terms in the sequence.
j int Loop counter to calculate sum from previous d terms.
OUTPUT
PROGRAM-16
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 an 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
1. START.
2. Input the numbers in n.
3. Convert the decimal number into binary number.
4. Change binary number in string.
5. Count the number of 1’S present in string.
6. If number of 1’s is even, then it is evil number.
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;
}
OUTPUT
PROGRAM-17
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 up to 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:
48*2=96 24*1=24 12*1=12 6*1=6
Remaining boxes 2*1=2
Total no. of boxes =140
Total no. of cartons=6
EXAMPLE 2
INPUT: N=4296
OUTPUT: INVALID LENGTH
ALGORITHM
1. START.
2. Accept the number of boxes n.
3. Check range
4. Create an array cart [] storing sizes of packs.
5. Initialize totalcart and count to 0.
6. repeat until box sizes left.
7. count size wise packs.
8. find remaining packs.
9. Display box wise details.
10. END.
SOURCE CODE
import java.util.*;
class Boxfilling
{
public static void main ()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of boxes to be packed");
int n=sc.nextInt();
if(n<1||n>1000)
{
System.out.println("Invalid Input");
}
else
{
int cart [] = {48,24,12,6};
int copy=n;
int totalCart=0, count=0;
System.out.println("Output:");
for (int i=0; i<4; i++)
{
count=n/cart[i];
if (count! =0)
{
System.out.println("\t"+cart[i]+"\tx\t"+count+"\t="+cart[i]*count);
}
totalCart=totalCart+count;
n=n%cart[i];
}
if(n>0)
{
System.out.println("\tReamining Boxes"+n+"x1="+n);
totalCart=totalCart+1;
}
else
{
System.out.println("\tReamining Boxes\t\t=0");
}
System.out.println("\tTotal number of boxes="+copy);
System.out.println("\tTotal number of cartons="+totalCart);
}
}
}
OUTPUT
PROGRAM-18
.50 .30 .2
Since all conditions are met, this matrix is a Doubly Markov Matrix.
ALGORITHM
1. START.
2. Ask the user for the matrix size (N) and the matrix elements.
3. If N is not between 3 and 8 print "Invalid size" and stop.
4. Assume the matrix is Doubly Markov (set a flag to "true").
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.
6. If the flag is still "true" after all checks, print "The matrix is a
Doubly Markov Matrix."
7. Otherwise (if flag is "false"), print "The matrix is Not a Doubly
Markov Matrix."
8. END.
SOURCE CODE
import java.util.Scanner;
if (n < 3 || n >= 9) {
System.out.println("Invalid size");
sc.close();
}
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;
if (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.");
}
}}
Data
Purpose
Members
word to store a word
to store the rearranged
newword
word
Member Functions Purpose
Rearrange() Default constructor
void readword() To accept the word in uppercase
void To count and display frequency of
freq_vow_con() vowels/consonants
Rearranges the word to place vowels before
void arrange()
consonants
void display() Displays the original and rearranged word
Write the complete class Rearrange along with the main method to
demonstrate its functionality.
ALGORITHM
1. START
2. Ask the user to enter a word in UPPERCASE letters.
3. Count vowels and consonants in the word:
o Go through each letter.
o If it is a vowel (A, E, I, O, U), increase the vowel count.
o Otherwise, increase the consonant count.
4. Rearrange the word:
o Make a new word by first adding all the vowels from the
original word.
o Then add all the consonants after the vowels.
5. Display:
o Show the original word.
o Show the rearranged word.
o Show the number of vowels and consonants.
6. END
SOURCE CODE
import java.util.Scanner;
// Constructor
Rearrange ()
{
w = "";
nw = "";
}
OUTPUT
PROGRAM-20
Since the sum of the digits of the number (18) is equal to the sum of
the digits of its prime factors (18), 666 is a Smith number.
ALGORITHM
1. START
2. Create a function sum that adds up the digits of any number.
3. Create a function prime that checks if a number is prime.
4. Begin the main part of the program.
5. Ask the user to "Enter a number".
6. Create a function smith to check if a number is smith
7. Use the sum function to calculate sum of digits of number
entered by the user, saving the result as s1.
8. Begin trying to divide the user's number by factors, starting
from 2.
9. Keep repeating these actions until the number is fully broken
down:
10. If the current factor divides the number:
11. Check if this factor is prime using the prime function. c. If
it is prime, use the sum function on this factor
and add that result to s2. d. Divide the number by this factor. If
the factor doesn't divide the number, try the next factor
increasing it by 1.
12. Compare s1 and s2.
13. If s1 is the same as s2, tell the user the number "is a Smith
Number." Otherwise, tell the user the number "is NOT a Smith
Number."
14. END
SOURCE CODE
import java.util.Scanner;
class smith
{
Scanner sc = new Scanner(System.in);
int sum (int k) {
int s = 0;
while (k > 0) {
s = s + k % 10;
k = k / 10;
}
return s;
}
int prime (int k)
{
int c = 0, i;
for (i = 1; i <= k; i++) {
if (k % i == 0)
c++;
}
return c;
}
public static void main () {
System.out.println("Enter a number");
smith ob = new smith ();
int s1 = ob.sum(n);
int s2 = 0;
int i = 2, k = n;
while (k > 1) {
if (k % i == 0) {
if (ob.prime(i) == 2) {
s2 = s2 + ob.sum(i);
k = k / i;
} else {
k = k / i;
}
} else {
++i;
}
}
if (s1 == s2) {
System.out.println(n + " is a Smith Number.");
} else {
System.out.println(n + " is not a Smith Number.");
}
}
}
Since 113 itself is prime, and all its rotations (131 and 311) are also
prime, 113 is a twisted prime (or circular prime).
ALGORITHM
1. START.
2. Enter a number.
3. Read the integer input from the user and store it in N.
4. Convert the integer N to string and store it in s.
5. Calculate the length of the string s and store it .
6. Initialize flag to 0.
7. Create an object obj of the twisted class.
8. A for loop, with loop control variable i from 1 to length (to
generate each rotation):
9. Convert the current string s back to an integer and store it in k.
10. Call the prime function using obj.prime(k).
11. If the value returned by obj.prime(k) is NOT equal to 2
(implying k is not prime): Set flag to 1. Exit the loop
immediately (there is no need to check further rotations).
12. Rotate the string s by moving its first character to the end
(e.g., if s is "123", it becomes "231").
13. If flag is equal to 0: Display "Twisted". else (if flag is 1):
Display "Not twisted".
14. END.
SOURCE CODE
import java.util.Scanner;
class twisted
int c=0;
if(n%i==0)
c++;
return c;
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
String a=""+n;
int l=a.length();
int flag=0;
for(int i=1;i<=l;i++)
int k=Integer.parseInt(a);
if(obj.prime(k)!=2)
flag=1;
a=a.substring(1)+a.charAt(0);
if(flag==0)
System.out.println("Twisted");
else
System.out.println("Not twisted");
}
VARIABLE DESCRIPTION TABLE
VARIABLE DATA TYPE DECSRIPTION
n int The number being checked
OUTPUT
PROGRAM-22
SOURCE CODE
import java.util.*;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int rem1 = 0;
int rem2 = 0;
int rem3 = 0;
int rem4 = 0;
int remainingBoxes = n;
int totalCartons = 0;
if (remainingBoxes > 0) {
System.out.println("Remaining boxes:\t" + remainingBoxes + " * 1 \t= "
+ remainingBoxes);
totalCartons++;
} else {
System.out.println("Remaining boxes:\t= 0");
}
System.out.println("Total number of boxes:\t= " + n);
System.out.println("Total number of cartons:\t= " + totalCartons);
}
}
Ex: 10=3 + 7
10= 5 + 5
ALGORITHM
1. START.
2. Declare a global variable n.
3. Create a returning boolean function isprime to check if the
number is prime or not.
4. Take a counter variable.
5. Run a loop from 1 till the number inputted.
6. Check the number of factors of the inputted number using the
counter variable.
7. If the count is two, return true, else return false.
8. Create a void function input.
9. Create an object of the Scanner class to input the number.
10. Create a void function isgoldbatch.
11. Check if the number is odd, greater than 50, or less than 9.
If true, print Invalid Input.
12. Run a loop from i = 3 to n/2.
13. Check if i is prime and also check if n - i is prime.
14. If both are prime, print the prime pair. Otherwise, continue
the loop.
15. Create the main () function.
16. Create an object of the class.
17. Call the functions using the object.
18. END.
SOURCE CODE
import java.util.*;
class goldbatch
int n;
boolean isprime(int x) {
int c = 0;
if (x % i == 0)
c++;
if (c == 2)
return true;
else
return false;
}
void input () {
n = sc.nextInt();
void isgoldbatch() {
if (n % 2 == 1 || n > 50 || n < 9) {
System.out.println("Invalid input");
return;
// Main function
ob.input();
ob.isgoldbatch();
OUTPUT
PROGRAM-24
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
1. START
2. Create a parameterized returning function String date (int d, int
y).
3. Create an array containing the days of all the months.
4. If the entered year is a leap year, set February to 29 days.
5. If d > 365 and it is not a leap year, subtract 365 and increase the
year by 1. Otherwise, subtract 366 and increase the year by 1.
6. Create a String month [] array containing the names of all
months.
7. Run a loop to subtract month days from d until d becomes less
than or equal to the days in the current month.
8. When the condition is met, store the month index and break the
loop.
9. Add the correct suffix (st, nd, rd, th) to the date according to the
value of d.
10. Return the final formatted date string.
11. Create the main () function.
12. Create a Scanner object to input: day number, year, and
number of days after.
13. If day > 366 or day < 1 or year > 9999 or N (days after)
not between 1 and 100, print Invalid Input.
14. Otherwise, print the given date and the date after N days
using the function.
15. END.
SOURCE CODE
import java.util.Scanner;
class prac6 {
int m [] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
m [1] += 1;
int mn = 0;
if (d > 365) {
if (m [1] == 28)
d -= 365;
else
d -= 366;
y++;
if (d <= m[i]) {
mn = i;
break;
d -= m[i];
// Adding suffix
return date;
// Main function
System.out.println("Enter Year");
int N = sc.nextInt();
if (day > 366 || day < 1 || year > 9999 || N > 100 || N < 1) {
System.out.println("Invalid Input");
else
}
VARIABLE DESCRIPTION TABLE
Variable Use
d Formal parameter to accept day number
y Formal parameter to accept year
m[] Stores number of days in every month
mn Stores month index (month number)
date Stores the final formatted date
month[] Stores names of months
day Day number entered by user
year Year entered by user
N Number of days after d to be calculated
OUTPUT
PROGRAM-25
ALGORITHM
1. START.
2. Create the main function.
3. Create an object of the Scanner class.
4. Enter the size m of the matrix.
5. If the size is less than 3 or greater than 10, print Invalid Size.
6. Create a two-dimensional array of size m × m.
7. Create a one-dimensional array of size (m-2) × (m-2).
8. Create a variable c to help with input in the one-dimensional
array.
9. Run nested loops to input numbers into the two-dimensional
array.
10. Store all non-boundary elements in the one-dimensional
array.
11. Print the original matrix.
12. Sort the one-dimensional array using the bubble sort
technique.
13. Run nested loops (outer loop i = 1 to m-2, inner loop j = 1
to m-2) and place sorted non-boundary elements back into the
two-dimensional array.
14. Print the arranged matrix.
15. Calculate the sum of diagonal elements using a variable s.
16. Print the diagonal elements and their sum.
17. END.
SOURCE CODE
import java.util.*;
class ascending {
int m = sc.nextInt();
System.out.println("Invalid size");
return;
int c = 0;
a[i][j] = sc.nextInt();
b[c++] = a[i][j];
System.out.println("Original matrix");
System.out.print(a[i][j] + "\t");
System.out.println();
b [j] = b [j + 1];
b [j + 1] = temp;
}
}
c = 0;
a[i][j] = b[c++];
System.out.println("Arranged matrix");
System.out.print(a[i][j] + "\t");
System.out.println();
int s = 0;
if (i == j || i + j == m - 1) {
s += a[i][j];
System.out.print(a[i][j] + "\t");
} else {
System.out.print("\t");
System.out.println();
System.out.println(s);
Variable Use
Size of the matrix
m
entered by user
Two-dimensional
a[][] array to store matrix
elements
One-dimensional
b[] array to store non-
boundary elements
c Index counter for b[]
Stores the sum of
s
diagonal elements
OUTPUT
PROGRAM-26
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.
ALGORITHM
1. START.
2. Create the main function.
3. Create an object of the Scanner class to take input.
4. Input a string from the user.
5. If the string does not end with ".", "!", or "?", then print Invalid
Input and exit.
6. Convert the string to uppercase.
7. Create an array of strings using the split () function.
8. Arrange the words of the string according to their length using
the bubble sort technique.
9. If two words have the same length, arrange them according to
the alphabetical order of their first letter only.
10. Print the converted string.
11. END.
SOURCE CODE
import java.util.*;
class lowtohigh {
String ss = sc.nextLine();
System.out.println("Invalid input");
return;
// Convert to uppercase
ss = ss.toUpperCase();
s[j] = s [j + 1];
s [j + 1] = temp;
s[j] = s [j + 1];
s [j + 1] = temp;
System.out.println("Converted String:");
OUTPUT
PROGRAM-27
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
1. START.
2. Define a class banner.
3. In the main method, prompt the user to enter the number of
teams n.
o Validate input: if n is less than 3 or greater than 8, print
Invalid number of teams and exit.
4. Create a two-dimensional character array ch[n][100] to store
team names.
5. Use a loop to take input of each team name. For every team
name, store each character into the 2D array.
6. Display the banner:
o Use nested loops to print characters’ column by column.
o If a team’s name is shorter than the current column, print a
blank space.
o Stop when all team names have been fully printed.
7. END.
SOURCE CODE
import java.util.*;
class banner {
int n = sc.nextInt();
if (n < 3 || n > 8) {
return;
String s = sc.nextLine();
ch[i][j] = s.charAt(j);
}
// Display banner
if (ch[j][i]! = '\u0000') {
System.out.print(ch[j][i] + "\t");
allEmpty = false;
} else {
System.out.print(" \t");
System.out.println();
if (allEmpty) break;
ALGORITHM
1. START.
2. Create a returning parameterized function reverse.
3. Extract the digits of the number and reverse the original number.
4. Create a static void main () function.
5. Create an object of the class to call the functions.
6. Create an object of the Scanner class and input the range.
7. Find the minimum and maximum of the two numbers entered by
the user.
8. Declare a counter variable, a frequency variable, and a flag
variable.
9. Run a loop from the minimum number to the maximum number.
10. Inside the loop, check if the current number is prime by
counting factors.
11. Check if:
• The square of the reverse of the number = reverse of the
square of the number.
• Both the original number and its reverse are prime.
12. If the above condition is true, print the number and
increase frequency.
13. If no Adam prime numbers are found, print a suitable
message.
14. END.
SOURCE CODE
import java.util.*;
class primeadam {
// Function to reverse a number
int reverse (int a) {
int rev = 0;
while (a! = 0) {
int d = a % 10;
rev = rev * 10 + d;
a = a / 10;
}
return rev;
}
// Main function
static void main () {
primeadam ob = new primeadam();
Scanner sc = new Scanner(System.in);
if (f == 0)
System.out.println("No Adam prime number could be found.");
}
}
a Formal parameter for reverse function / also user input lower range
1258
1251
1212
1125
ALGORITHM
1. START.
2. Create the void main function.
3. Create an object of the Scanner class to input the array.
4. Enter the size of the array.
5. If the size is less than 2 or greater than 10, print "Invalid size"
and exit.
6. Declare a single-dimensional array and a two-dimensional array.
7. Enter the values of the single-dimensional array.
8. Sort the single-dimensional array using the bubble sort
technique.
9. Print the sorted array.
10. Run a loop from i = n-1 till 0.
11. Declare the nested loop’s variable j outside the loop.
12. Run the loop from 0 to i.
13. Transfer the elements from the single-dimensional array to
the two-dimensional array according to the required pattern.
14. Print the two-dimensional array (matrix form).
15. END.
SOURCE CODE
import java.util.*;
class squaremat {
int n = sc.nextInt();
System.out.println("Invalid size");
System.exit(0);
a[i] = sc.nextInt();
// Bubble sort
a[j] = a [j + 1];
a [j + 1] = temp;
System.out.print(a[i] + "\t");
System.out.println();
System.out.println("Matrix:");
int x = 0;
int j;
b[x][j] = a[j];
int m = 0;
b[i][k] = a[m++];
x++;
// Print 2D array
System.out.print(b[i][j] + "\t");
System.out.println();
j, k, i Loop counters
OUTPUT