Isc Class 12 Comp Project

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

ACKNOWLEDGEMENT

I would like to express my sincere gratitude to all people who helped me in


completing project.
I am indeed grateful to our principal for providing a platform to learn and grow
in a conducive learning environment. I am obliged to my family member for
providing me all support and guidance throughout the project.
Last but not least I am indebted to our subject teacher Mr. Adil Usmani sir, a
computer science teacher for extending all possible support whenever and
wherever required in making of project.

Tamanna Yadav
XII-Commerce

1
CERTIFICATE
This is to certify that Tamanna Yadav, a student of class 12th of TMPS International
School has successfully completed the project on topic.

"Project Report on Computer Science with Java" under the guidance of


Mr.Adil Usmani sir during the academic year 2023-24.

Signature of teacher Signature of student

2
CONTENT

S.No Topic Page no.


1. Program 1 4
2. Program 2 6
3. Program 3 8
4. Program 4 11
5. Program 5 14
6. Program 6 16
7. Program 7 19
8. Program 8 21
9. Program 9 23
10. Program 10 25
11. Program 11 29
12. Program 12 32
13. Program 13 34
14. Program 14 36
15. Program 15 38
16. Program 16 40
17. Program 17 43
18. Program 18 45
19. Program 19 49
20. Program 20 51
21. Program 21 54
22. Program 22 56
23. Program 23 58
24. Program 24 60
25. Program 25 62
26. Conclusion 64
27. Bibliography 65

3
PROGRAM 1
Write a program to input a number and check and print whether it is a Pronic
number or not.
Algorithm
STEP 1: Import the Scanner class.
STEP 2: Create a Scanner object for user input.
STEP 3: Ask the user to enter a number.
STEP 4: Read the integer input and store it in the num variable.
STEP 5: Initialize variables’ i’ and ‘c ‘to 0.
STEP 6: Enter a ‘while’ loop that iterates from 0 to half of the input number.
STEP 7: Calculate the product of ‘i’ and ‘i + 1’.
STEP 8: Check if the product is equal to the input number.
STEP 9: If a pronic number is found, increment the count c, print the equation, and
break out of the loop.
STEP 10: After the loop, check if ‘c’ is equal to 1, and based on this condition, print
whether the number is a pronic number or not.
Solution:
import java.util.Scanner;
class PRONICNUMBER{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int num=sc.nextInt(); //accept the num
//check for the pronic number
int i=0;int c=0;
while(i<=(num/2){
int prod=i*(i+1);
if(prod==num) {
c++;
System.out.println(i+"*"+(i+1)+"="+num);
break;
}
i++;
}
if(c==1)
System.out.println(num+"is a pronic number");
else

4
System.out.println(num+"is not a pronic number");
}
} //end
Output
Enter a number
2
1*2=2
2 is a pronic number

Variable Description
Variable name Datatype purpose
Num Int An integer variable to store the
user-input number.
Int An integer variable used as an
i iterator in the while loop.
Int An integer variable used as an
c iterator in the while loop

5
PROGRAM 2
Write a program to accept a number and check whether it is a Jupiter number or
not?
Algorithm
Step1. Create a Java program called `JupiterNumber`.
Step2. Define a method `countDig`.
Step3. Initialize a count `c` to 0.
Step4.While the number is not 0, divide it by 10 and increment `c`.
Step5.Return `c - 1`.
Step6. Define a method `checkNum` to check if a number is a Jupiter Number.
Step7. Calculate the first and last digits of the number.
Step8. Find the sum of these two digits.
Step9.Check if the number is divisible by the sum.
Print whether it's a Jupiter Number or not.
Step10.Create a`main` method.
Step11.Create a `Scanner` object for user input.
Step12.Prompt the user to enter a number.
Step13.Read the input number.
Step14.Call the `countDig` method to count digits (result not used).
Step15.Call the `checkNum` method to check if the number is a Jupiter Number and
print the result.
Solution:
import java .util.Scanner;
public class JupiterNumber {
public static int countDig(int num){
int c=0;
while(num!=0) {
num=num/10;
c++;
}
return c-1;
}
//check if a number is a jupiter
public static void checkNum(int num){
int p=countDig(num);
int div=(int)(Math.pow(10,p));
int first_dig=num/div;
System .out.println("First digit = "+ first_dig );
int last_dig=num%10;

6
System .out.println("Last digit = "+ last_dig );
int sum= first_dig +last_dig;
System .out.println("Sum of the two digits = "+ sum );
if ((num%sum)==0) {
System .out.println(num+ " is divisible by "+ sum);
System .out.println(num+" is a Jupiter Number" );
}
else
{
System .out.println(num+ " is not divisible by "+ sum);
System .out.println(num+" is not a Jupiter Number" );
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt(); //accept the number
countDig(n);
checkNum(n);
}
} //end
Output
Enter a number
2
First digit = 2
Last digit = 2
Sum of the two digits = 4
2 is not divisible by 4
2 is not a Jupiter Number
Variable Description Table
Variable name Datatype Purpose
num int to store input number
c int to store input number
p int to store count of digit
div int to store the divisor for extracting the first
digit
first_dig int to store the first digit of the number
last_dig int to store the last digit of the number

7
PROGRAM 3
Write a program to accept a number and check whether it is a circular prime or
not?
Algorithm
Step1. Define a function isPrime to check if a number is prime by counting its
divisors.
Step2. Define a function getDigitCount to count the number of digits in a given
number.
Step3. Define a function computeCheck to check if a number is a circular prime by
rotating its digits and checking if all rotations are prime.
Step4. In the main function:
a. Take an input number from the user.
b. Check if the input number is prime.
c. If it's prime, count its digits and perform circular prime check.
d. Output whether the number is a circular prime or not.
Solution:
import java.util.*;
class Circular_Prime {
// check if a number is prime
public static boolean isPrime(int num) {
int c=0;
for(int i=1;i<=num;i++){
if(num%i==0){
c++;
}
}
return c==2;
}
public static int getDigitCount(int num){
int c=0;
while(num!=0){
c++;
num=num/10;
}
return c;
}
public static void computeCheck(int num){
int c=0;

8
int temp;
int n1=num;
System.out.println(n1);
int p=getDigitCount(num);
int div=(int)Math.pow(10,p-1);
for( int i=1;i<=p-1;i++){
int r= num%div;
int d=num/div; int rev=(r*10)+d;
System .out .println (rev);
num=rev;
if(isPrime (rev))
c++;
}
if(c==p-1)
System .out.println( n1+" is a circular prime number");
else
System .out.println( n1+" is a not circular prime number");
}
public static void main(String args[]) {
Scanner sc=new Scanner (System .in);
System .out. println (" Enter a number");
int n =sc.nextInt(); //to accept a number
// check the number
if(isPrime(n)){
getDigitCount (n);
computeCheck(n);
}
else
System.out.println("is a not prime number so it can not to be a circular
prime number"+n);
}

}
Output
Enter a number
29
29
92
29 is a not circular prime number

9
Variable Description Table
Variable name Datatype Purpose
num int to store the input number
c int to count divisors or primes
i int to initialize loop
n1 int to store the original number
p int to store the digit count of num
div int to calculate a divisor
r int to store the remainder
d int to store the digit
rev int to store the reversed number

10
PROGRAM 4
Write a program in java to accept a number. Check and display whether it is a
Bouncy number or not.
Algorithm:
Step1. Take an integer input from the user.
Step2. If the input is less than 100, output "Not a bouncy number" and terminate.
Step3. Split the input number into its digits.
Step4. Check if the digits form an increasing or decreasing sequence.
Step5. If it's an increasing sequence, output "Not a bouncy number" if all digits are
in increasing order; otherwise, output "Bouncy number."
Step6. If it's a decreasing sequence, output "Not a bouncy number" if all digits are
in decreasing order; otherwise, output "Bouncy number."
Solution:
import java.util.Scanner;
class BouncyNumber {
// to count the number
public static int countDig(int n) {
int c=0;
while(n!=0) {
n=n/10;
c++;
}
return c-1;
}
public static void main(String[] args) {
Scanner sc=new Scanner (System .in);
System .out .println ("Enter a number");
int num= sc.nextInt();
//check if the number is less than 100
if(num<100){
System .out.println ("Not a bouncy number");
return ;
}
System .out .println (num);
int count= countDig (num);
int div=(int)(Math.pow(10,count));
int A[]= new int[count+1];
for(int i=0;i<=count;i++){

11
int dig=num/div;
A[i]=dig;
num=num%div;
div=div/10;
}
int c=0; if(A[0]<A[1]) {
for(int i=1 ;i<count; i++) {
if(A[i]<A[i+1]) c++;
}
if (c==count)
System .out. println("Not a bouncy number as it is an increasing
number");
else
System .out. println("Bouncy number");
}
else {
for(int i=1 ;i<=count; i++) {
if(A[i]>A[i+1])
c++;
}
if(c==count)
System .out. println("Not a bouncy number as it is a decreasing
number");
else
System .out. println("Bouncy number");
}
}
} //end

12
Output
Enter a number
24546
24546
Bouncy number

Variable description

Variable datatype purpose


num int To store user-input number
count int To count the digits
div int to separate digits
A[] int to store the individual digits
of the input number.
c int to count whether the number
is bouncy or not
i Int to initialize the loop
dig Int to representing individual
digits during digit
separation

13
PROGRAM 5
Write a program to count a total number of word in sentence.
Algorithm:
Step1. Initialize a string ab with a sentence.
Step2. Convert the sentence to uppercase.
Step3. Initialize variables count and len.
Step4. Loop through each character in the sentence:
a. Check if the character is a space (' ').
b. If a space is found, increment the count to count words.
Step5. Output the total number of words in the sentence, which is count + 1.
SOLUTION:
public class inserword {
public static void main(String args[]) {
String ab="technology is when it brings people together";
String upper=ab.toUpperCase();
int count=0; int len=ab.length();
for(int i=0;i<len;i++) {
char ch=ab.charAt(i);
//check if the character is a space
if(ch==' ') {
count++;
}
}
//output
System.out.println("total words in sentence is: "+(count+1));
}
}

14
Output
total words in sentence is: 7

Variable Description

Variable name Datatype Purpose


ab int To store a string
Upper int To store upper case string
count int To count the number of space
len int To store length
i int To initialize loop
ch int To store character

15
PROGRAM 6
Write a program in Java to enter natural numbers in a double dimensional array m
x n (where m is the number of rows and n is the number of columns). Display the new
matrix in such a way that the new matrix is the mirror image of the original matrix.
Algorithm:
Step1. Prompt the user to enter the number of rows (m) and columns (n).
Step2. Create two 2D arrays, arr and newArr, to store the input array and its
mirror image, respectively.
Step3. Read and store the elements of the input array.
Step4. Display the input array.
Step5. Perform the mirror image transformation by copying elements from arr to
newArr with column reversal.
Step6. Display the mirror image array
Solution:
import java.util.Scanner;
public class MirrorImage {
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("Enter number of rows (m): ");
int m = in.nextInt(); //enter number of row
System.out.print("Enter number of columns (n): ");
int n = in.nextInt(); //enter number of columns
int arr[][] = new int[m][n];
int newArr[][] = new int[m][n];
System.out.println("Enter array elements");
for (int i = 0; i < m; i++) {
System.out.println("Enter Row "+ (i+1) + " :");
for (int j = 0; j < n; j++) {
arr[i][j] = in.nextInt();
}
}
System.out.println("Input Array:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
for (int j = 0; j < n; j++) {

16
for (int i = 0; i < m; i++) {
newArr[i][n - 1 - j] = arr[i][j];
}
}

System.out.println("Mirror Image Array:");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(newArr[i][j] + "\t");
}
System.out.println();
}
}
} //end

17
Output
Enter array elements
Enter Row 1 :
1
6
8
Enter Row 2 :
5
7
8
Enter Row 3 :
3
5
6
Input Array:
1 6 8
5 7 8
3 5 6
Mirror Image Array:
8 6 1
8 7 5
6 5 3

Variable Description Table:

Variable name Datatype Purpose


m int To store number of row
n int To store number of column
arr int To store intput array
newArr int To store the mirror image of
the inout array
i,j int To initialize the loop

18
PROGRAM 7
Write a program to input a number and check whether it is 'Magic Number' or not.
Algorithm:
Step1. Prompt the user to enter a number.
Step2. Initialize a variable n to the input number.
Step3. Repeat the following until n becomes a single-digit number (less than or
equal to 9):
- Initialize a variable sum to 0.
- While n is not equal to 0:
- Extract the last digit d of n.
- Update n by removing the last digit.
- Add d to sum.
- Update n with the value of sum.
Step4. If n is equal to 1, output that the input number is a "Magic Number."
Otherwise, it's not a "Magic Number."
Solution:
import java.util.Scanner;
public class MagicNum {
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("Enter number to check: ");
int num = in.nextInt(); //enter a number
int n = num;
while (n > 9) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}
if (n == 1)
System.out.println(num + " is Magic Number");
else
System.out.println(num + " is not Magic Number");
}
} //end

19
Output
Enter number to check: 289
289 is Magic Number

Variable Description Table


Variable Datatype Purpose
num int To input a number
N int To perform the digit sum calculation
and Magic Number check.
sum int to calculate the sum of digits
D int To represent a digit

20
PROGRAM 8
Write a program to print it out in spiral order.
Algorithm:
Step1. Initialize a 2D array a of size N x N with sequential values.
Step2. Define a method printNormal to print the array in normal order.
Step3. Define a method printSpiral to print the array in a spiral order.
Step4. In printSpiral:
- Iterate through the array in a spiral pattern, printing elements in four directions.
- Print the central element if N is an odd number.
Step5. In the main method:
- Prompt the user to enter N for creating an N x N array.
- Create an instance of the Spiral class with the given N.
- Print the normal and spiral order representations of the array.
Solution:
import java.util.Scanner;
class Spiral{
int[][]a;
int N;
Spiral(int n) {
a=new int[n][n];
N=n;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
a[i][j]=1+N*i+j;
}
void printNormal(){
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
void printSpiral() {
for(int i=N-1,j=0;i>0;i--,j++){
for (int k=j;k<i;k++) System.out.print(a[j][k]+"");
for (int k=j;k<i;k++) System.out.print(a[k][i]+"");
for (int k=i;k>j;k--) System.out.print(a[i][k]+"");
for (int k=i;k>j;k--) System.out.print(a[k][j]+"");
}
if(N%2==1) System.out.println(a[(N-1)/2][(N-1)/2]);

21
}
public static void main(String[]args) {
Scanner in=new Scanner(System.in); // initialize scanner for user input
Systemout.println("Enter N to create an N*N array:");
int N=in.nextInt(); //enter a number
Spiral sp=new Spiral(N);
System.out.println("The given array is:");
sp.printNormal();.
System.out.println("When printed in spiral order:");
sp.printSpiral();
}
} end
Output
Enter N to create an N*N array:
3
The given array is:
1 2 3 4 5 6 7 8 9
When printed in spiral order:
123698745

Variable description
Variable name Datatype Purpose
A int To store the elements
N int To store the size
i,j,k int To initialize a loop
n int for initializing elements in
the array in a pattern.
sp int To store spiral array

22
PROGRAM 9
Decimal To Binary Conversion Using Recursion
Alogrithm
main()
STEP 1: Accept number
task(int n)
STEP 1: Proceed of n>2
STEP 2: store reminder in variable d when n is divided by 2
STEP 3:task(n%2)
STEP 4: Display d backward in horizontal line
Solution
import java.util.*;
class recur{
void main(){
System.out . println(" enter number to find binary value");
int a= new Scanner (System.in). next Int(); //enter a number
task(a);
}
Void task( int n){
if (n>0)
{
int d=n%2;
task (n/2);
System.out.println(d);
}
}
public static void main(String args[])
recur obj=new recur();
obj.main
}
} //end

23
Output
enter number to find binary value
0101
1
1
0
0
1
0
1
Variable Description

Variable name Datatype Purpose


a int to get number
d int binary calculation
n int user input

24
PROGRAM 10
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 integers into this
matrix. Perform the following tasks on the matrix:
1. Sort the non-boundary elements in ascending order using any standard
sorting technique and rearrange them in the matrix.
2. Calculate the sum of both the diagonals.
3. Display the original matrix, rearranged matrix and only the diagonal
elements of the rearranged matrix with their sum.
Solution:
import java.util.Scanner;
public class MatrixSort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("ENTER MATRIX SIZE (M): ");
int m = in.nextInt(); // enter size of matrix

if (m <= 3 || m >= 10) {


System.out.println("THE MATRIX SIZE IS OUT OF RANGE.");
return;
}

int a[][] = new int[m][m];

System.out.println("ENTER ELEMENTS OF MATRIX");


for (int i = 0; i < m; i++) {
System.out.println("ENTER ROW " + (i+1) + ":");
for (int j = 0; j < m; j++) {
a[i][j] = in.nextInt();
if (a[i][j] < 0) {
System.out.println("INVALID INPUT");
return;
}
}
}

System.out.println("ORIGINAL MATRIX");
printMatrix(a, m);

25
sortNonBoundaryMatrix(a, m);
System.out.println("REARRANGED MATRIX");
printMatrix(a, m);

computePrintDiagonalSum(a, m);
}

public static void sortNonBoundaryMatrix(int a[][], int m) {


int b[] = new int[(m - 2) * (m - 2)];
int k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
b[k++] = a[i][j];
}
}

for (int i = 0; i < k - 1; i++) {


for (int j = 0; j < k - i - 1; j++) {
if (b[j] > b[j + 1]) {
int t = b[j];
b[j] = b[j+1];
b[j+1] = t;
}
}
}

k = 0;
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
a[i][j] = b[k++];
}
}
}

public static void computePrintDiagonalSum(int a[][], int m) {


int sum = 0;
System.out.println("DIAGONAL ELEMENTS");
for (int i = 0; i < m; i++) {

26
for (int j = 0; j < m; j++) {
if (i == j || i + j == m - 1) {
sum += a[i][j];
System.out.print(a[i][j] + "\t");
}
else {
System.out.print("\t");
}
}
System.out.println();
}
System.out.println("SUM OF THE DIAGONAL ELEMENTS = " + sum);
}

public static void printMatrix(int a[][], int m) {


for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}// end

27
Output:

Variable description:
Variable name Datatype Purpose
m int to store the size of array
a int to store the original matrix
b int to store sorted non-boundary
matrix
k int to store temporary variable
index
i int to store row index
j int to store column matrix
t int to store temporary variable
for swapping elements
sum int to store the sum of diagonal
matrix

28
PROGRAM 11
Write a program to accept a sentence which may be terminated by either '.', '?' or
'!' only. The words may be separated by more than one blank space and are in
UPPER CASE.
Perform the following tasks:
1. Find the number of words beginning and ending with a vowel.
2. Place the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.
Algorithm
Step1. Initialize a Scanner object to read input from the user.
Step2. Prompt the user to enter a sentence and store it in a string variable (ipStr).
Step3. Check if the last character of the input string is not '.', '?', or '!' - if not, print
"INVALID INPUT" and exit.
Step4. Remove the last punctuation character from the input string.
Step5. Tokenize the modified input string into words using StringTokenizer.
Step6. Initialize counters for words beginning and ending with vowels and two
StringBuffers to store words.
Step7. Iterate through each word:
a. Check if the word starts and ends with a vowel - if yes, increment the vowel
word count and append the word to the vowel words StringBuffer.
b. If the word does not start and end with a vowel, append it to the other
StringBuffer.
Step8. Combine the two StringBuffers to form a new string.
Step9. Print the count of words beginning and ending with a vowel and the new
string.
Solution:
import java.util.*;
public class VowelWord
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.println("ENTER THE SENTENCE:");
String ipStr = in.nextLine().trim().toUpperCase();
int len = ipStr.length();
char lastChar = ipStr.charAt(len - 1);
if (lastChar != '.'
&& lastChar != '?'
&& lastChar != '!') {
System.out.println("INVALID INPUT");

29
return;
}
String str = ipStr.substring(0, len - 1);
StringTokenizer st = new StringTokenizer(str);
StringBuffer sbVowel = new StringBuffer();
StringBuffer sb = new StringBuffer();
int c = 0;
while (st.hasMoreTokens()) {
String word = st.nextToken();
int wordLen = word.length();
if (isVowel(word.charAt(0))
&& isVowel(word.charAt(wordLen - 1))) {
c++;
sbVowel.append(word);
sbVowel.append(" ");
}
else {
sb.append(word);
sb.append(" ");
}
}
String newStr = sbVowel.toString() + sb.toString();
System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A
VOWEL = " + c);
System.out.println(newStr);
}
public static boolean isVowel(char ch) {
ch = Character.toUpperCase(ch);
boolean ret = false;
if (ch == 'A' || ch == 'E'|| ch == 'I || ch == 'O' || ch == 'U')
ret = true;
return ret;
}
}// end

30
Output:
ENTER THE SENTENCE:
The area between the eyebrows is called glabella
INVALID INPUT

Variable description:

Variable name Datatype Purpose


ipStr int Stores the input sentence in uppercase and
trimmed form.
len int to store the length
lastchar int to stores the last character
str int Contains the input sentence without its ending
punctuation
st int to split the input sentence into words.
sbVowel int to store words beginning and ending with
vowels.
sb int to store other words
c int to counts the number of words beginning and
ending with vowels
word int to store temporary variable to hold each word
during processing
wordLen int to stores the length of each word
newStr int to contains modified sentence with separated
words

31
PROGRAM 12
A company manufactures packing cartons in four sizes, i.e. cartons to accommodate
6 boxes, 12 boxes, 24 boxes and 48 boxes. Design a program to accept the
number of boxes to be packed (N) by the user (maximum up to 1000 boxes) and
display the break-up of the cartons used in descending order of capacity (i.e.
preference should be given to the highest capacity available, and if boxes left are
less than 6, an extra carton of capacity 6 should be used.)
Test your program with the following data and some random data:
Algorithm
Step1. enter the number of boxes (N)
Step2.If N is less than 1 or greater than 1000, print "INVALID INPUT" and exit.
Step3.Define an array of carton sizes: {48, 24, 12, 6}.
Step4.Initialize a total variable to 0.
Step5.Initialize a temporary variable (t) with the input value (N).
Step6.Calculate the number of cartons of that size .
Step7.Print the total number of input boxes and the total number of cartons.
Solution
import java.util.Scanner;

public class CartonBoxes


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("Enter number of boxes (N): ");
int n = in.nextInt();
if (n < 1 || n > 1000) {
System.out.println("INVALID INPUT");
return;
}
int cartonSizes[] = {48, 24, 12, 6};
int total = 0;
int t = n;
for (int i = 0; i < cartonSizes.length; i++) {
int cartonCount = t / cartonSizes[i];
t = t % cartonSizes[i];
total += cartonCount;
if (cartonCount != 0) {
System.out.println(cartonSizes[i] + " * " + cartonCount +
" = " + (cartonSizes[i] * cartonCount));

32
}
}
if (t != 0) {
System.out.println("Remaining boxes = " + t
+ " * 1 = " + t);
total++;
}
else {
System.out.println("Remaining boxes = 0");
}
System.out.println("Total number of boxes = " + n);
System.out.println("Total number of cartons = " + total);
}
}// end
Output
Enter number of boxes (N): 6
6*1=6
Remaining boxes = 0
Total number of boxes = 6
Total number of cartons = 1
Variable Description
Variable Datatype Purpose
n int to stores the number of boxes
cartonSizes int to store size
total int to store the total number of cartons used
t int A temporary variable used for calculations
during the loop.
i int to initialize loop
cartonCount int to stores the number of cartons of a specific
size needed

33
PROGRAM 13
The result of a quiz competition is to be prepared as follows:
The quiz has five questions with four multiple choices (A, B, C, D), with each question
carrying 1 mark for the correct answer. Design a program to accept the number of
participants N such that N must be greater than 3 and less than 11. Create a
double-dimensional array of size (Nx5) to store the answers of each participant
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.
Algorithm:
Step 1. Get the number of participants (N) from the user, ensuring it's between 4
and 10.
Step 2. Create a 2D array to store participant answers and a 1D array for the
answer key.
Step 3. Prompt the user to input answers for each participant and the answer key.
Step 4. Calculate scores for each participant by comparing their answers with the
key.
Step 5. Find and display the highest score and the corresponding participant(s).
Solution:
import java.util.Scanner;
public class QuizCompetition{
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("Enter the Number of Participants (N): ");
int n = in.nextInt();
if (n <= 3 || n >= 11) {
System.out.println("INPUT SIZE OUT OF RANGE.");
return;
}
char answers[][] = new char[n][5];
char key[] = new char[5];
System.out.println("Enter answers of participants");
for (int i = 0; i < n; i++) {
System.out.println("Participant " + (i+1));
for (int j = 0; j < 5; j++) {
answers[i][j] = in.next().charAt(0);
}
}
System.out.println("Enter Answer Key:");

34
for (int i = 0; i < 5; i++) {
key[i] = in.next().charAt(0);
}
int hScore = 0;
int score[] = new int[n];
System.out.println("Scores:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < 5; j++) {
if (answers[i][j] == key[j]) {
score[i]++;
}
}
if (score[i] > hScore) {
hScore = score[i];
}
System.out.println("Participant " + (i+1) + " = " + score[i]);
}
System.out.println("Highest Score:");
for (int i = 0; i < n; i++) {
if (score[i] == hScore) {
System.out.println("Participant " + (i+1));
}
}
}
}// end

Output:
Enter the Number of Participants (N): 4
Enter answers of participants
Participant 1
Variable Description:
Variable Datatype Purpose
n int to stores the number of participants
answers int 2D array to store the answers of
participants
key int Array to store the answer key
hScore int Keeps track of the highest score achieved
score int Array to store the scores of participants.
i,j int to initialize loop

35
PROGRAM 14
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.
ROT13
A/a B/b C/c D/d E/e F/f G/g H/h I/i J/j K/k L/l M/m
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/w X/x Y/y Z/z
Write a program to accept a plain text of length L, where L must be greater than 3
and less than 100.
Encrypt the text if valid as per the Caesar Cipher.
Algorithm:
Step 1 . Enter plain text.
Step2. Check if the length of the input text is within a valid range (3 < len < 100),
otherwise print an error message and exit.
Step 3. Create a StringBuffer to store the cipher text.
Step4 .Iterate through each character in the input text.
Step5 .If the character is in the range 'A' to 'M' or 'a' to 'm', shift it forward by 13
positions.
Step 6 . If the character is in the range 'N' to 'Z' or 'n' to 'z', shift it backward by 13
positions.
Step7 .Append the transformed character to the StringBuffer.
Step8.Convert the StringBuffer to a String to obtain the cipher text.
Step9. Print the cipher text.
Solution:
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter plain text:");
String str = in.nextLine();
int len = str.length();
if (len <= 3 || len >= 100) {
System.out.println("INVALID LENGTH");
return;
}
StringBuffer sb = new StringBuffer();
36
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
sb.append((char)(ch + 13));
}
else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
sb.append((char)(ch - 13));
}
else {
sb.append(ch);
}
}

String cipher = sb.toString();


System.out.println("The cipher text is:");
System.out.println(cipher);
}
}

Output:
Enter plain text: Hello! How are you?
The cipher text is: Uryyb! Ubj ner lbh?

Variable description
Variable Datatype Purpose
str int to store input
len int to store length
sb int to build the cipher text
i int to initialize loop
ch int to store chararcter
cipher int to store the result of cipher text

37
PROGRAM 15
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 'N'.
Algorithm:
Step1.Prompt the user to enter the value of N.
Step2. Check if N is within the valid range (9 < N < 50), and if it is even. If not,
print an error message and exit.
Step3.Determine if a given number is prime by checking its divisors.
Step4.Initialize variables (a, b).
Step5. Iterate through possible values of 'a' (starting from 3 up to N/2).
Step6.For each 'a', calculate 'b = N - a'.
Step7.Check if both 'a' and 'b' are prime using the isPrime function.
Step8.Print prime pairs.
Solution:
import java.util.Scanner;
public class GoldbachNumber{
//check if number is prime
public static boolean isPrime(int num) {
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
return c == 2;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (n <= 9 || n >= 50) {
System.out.println("INVALID INPUT. NUMBER OUT OF RANGE.");
return;
}
if (n % 2 != 0) {
System.out.println("INVALID INPUT. NUMBER IS ODD.");
return;
}
System.out.println("PRIME PAIRS ARE:");

38
int a = 3;
int b = 0;
while (a <= n / 2) {
b = n - a; //calcluate
if (isPrime(a) && isPrime(b)) {
System.out.println(a + ", " + b);
}
a += 2;
}
}
}// end
Output:
ENTER THE VALUE OF N: 20
PRIME PAIRS ARE:
3, 17
7, 13

Variable Description:

Variable Datatype Purpose


n int to store the value
a int to store number
b int to store 2 number
i int to check prime number
c int to count the divisor

39
PROGRAM 16
Write a program to declare a matrix a[][] of order (m × n) where 'm' is the number
of rows and 'n' is the number of columns such that the values of both 'm' and 'n' must
be greater than 2 and less than 10. Allow the user to input integers into this matrix.
Perform the following tasks on the matrix:
1. Display the original matrix.
2. Sort each row of the matrix in ascending order using any standard sorting
technique.
3.Display the changed matrix after sorting each row.
Algorithm:
Step1. Enter the values of M and N.
Step2. Check if both M and N are within the valid range (2 < M, N < 10). If not,
print an error message and exit.
Step3. Create a 2D array 'a' with dimensions M x N.
Step4.Prompt the user to input elements for each row of the matrix.
Step5. Print the original matrix.
Step6.Implement a bubble sort to sort each row of the matrix in ascending order.
Step7.Print the matrix after sorting each row.
Solution:
import java.util.Scanner;
public class ArraySort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
// accept the size of matrix
System.out.print("ENTER THE VALUE OF M: ");
int m = in.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
// range for the matrix size
if (m <= 2 || m >= 10|| n <= 2 || n >= 10) {
System.out.println("MATRIX SIZE OUT OF RANGE.");
return;
}
int a[][] = new int[m][n];
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++) {
System.out.println("ENTER ELEMENTS OF ROW " + (i+1) + ":");

40
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n - 1; j++) {
for (int k = 0; k < n - j - 1; k++) {
if (a[i][k] > a[i][k + 1]) {
int t = a[i][k];
a[i][k] = a[i][k+1];
a[i][k+1] = t;
}
}
}
}
System.out.println("MATRIX AFTER SORTING ROWS");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}//end

41
Output:
ENTER THE VALUE OF M: 3
ENTER THE VALUE OF N: 4
ENTER ELEMENTS OF MATRIX:
ENTER ELEMENTS OF ROW 1:
3715
ENTER ELEMENTS OF ROW 2:
2846
ENTER ELEMENTS OF ROW 3:
9321
ORIGINAL MATRIX
3715
2846
9321
MATRIX AFTER SORTING ROWS
1357
2468
1239
Variable Description:
Variable Datatype Purpose
m int to store number of row
n int to store number of column
a int to store elements
i,j,k int to initialize loop
t int to store variable for swapping
elements during sorting

42
PROGRAM 17
The names of the teams participating in a competition should be displayed on a
banner vertically, to accommodate as many teams as possible in a single banner.
Design a program to accept the names of N teams, where 2 < N < 9 and display
them in vertical order, side by side with a horizontal tab (i.e. eight spaces).
Algorithm:
Step1. Prompt user for the value of N.
Step2. Check if N is within the valid range (2 < N < 9). If not, print an error and
exit.
Step3. Create an array 'teams' to store N team names.
Step4. Iterate over teams, inputting names and finding the maximum length
(highLen).
Step5. a. Iterate for each character position (i) up to highLen.
b. If the team name is shorter than i, print a space, else print the character at
position i.
c. Move to the next line.
Solution:
import java.util.Scanner;
public class Banner
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();// enter the number
in.nextLine();
if (n <= 2 || n >= 9) {
System.out.println("INVALID INPUT");
return;
}
String teams[] = new String[n];
int highLen = 0;
for (int i = 0; i < n; i++) {
System.out.print("Team " + (i+1) + ": ");
teams[i] = in.nextLine();
if (teams[i].length() > highLen) {
highLen = teams[i].length();
}
}
for (int i = 0; i < highLen; i++) {

43
for (int j = 0; j < n; j++) {
int len = teams[j].length();
if (i >= len) {
System.out.print(" \t");
}
else {
System.out.print(teams[j].charAt(i) + "\t");
}
}
System.out.println();
}
}
} //end

Output:
ENTER THE VALUE OF N: 4
Team 1: Alpha
Team 2: Beta
Team 3: Gamma
Team 4: Delta

A B G D
l e a e
p t m l
h a m t
a a a

Variable Description:
Variable Datatype Purpose
n int to store value
team string to store the names of team
highLen int to store length of the longest name
i,j int to initialize loop
len int to store length of each name

44
PROGRAM 18
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 not within the limit or not according to the condition
specified.
Algorithm:
Step1. Prompt the user for the day number, year, and the number of days to
calculate.
Step2. Check if the day number is within the valid range (1 to 366) and the number
of days is within the valid range (1 to 100). If not, print an error message and exit.
Step3. Determine if the given year is a leap year.
Step4.Calculate the date corresponding to the provided day number and year
using monthDays and monthNames arrays.
Step5.Calculate the future date after adding the specified number of days.
Step6.Adjust the year if the added days exceed the total days in a year (leap or
non-leap).
Step7.Print the initial date and the calculated future date.
Solution:
import java.util.Scanner;
public class DateCalculator{
public static boolean isLeapYear(int y) {
boolean ret = false;
if (y % 400 == 0) {
ret = true;
}
else if (y % 100 == 0) {
ret = false;
}
else if (y % 4 == 0) {
ret = true;
}
else {
ret = false;
}
return ret;
}
public static String computeDate(int day, int year) {

45
int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String monthNames[] = {"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY",
"JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER",
"DECEMBER"};
boolean leap = isLeapYear(year);
if (leap) {
monthDays[1] = 29;
}
int i = 0;
int daySum = 0;
for (i = 0; i < monthDays.length; i++) {
daySum += monthDays[i];
if (daySum >= day) {
break;
}
}
int date = day + monthDays[i] - daySum;
StringBuffer sb = new StringBuffer();
sb.append(date);
sb.append("TH ");
sb.append(monthNames[i]);
sb.append(", ");
sb.append(year);
return sb.toString();
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in); // initialize scanner for user input
//input by user
System.out.print("DAY NUMBER: ");
int dayNum = in.nextInt();
System.out.print("YEAR: ");
int year = in.nextInt();
System.out.print("DATE AFTER (N DAYS): ");
int n = in.nextInt();
//input ranges
if (dayNum < 1 || dayNum > 366) {
System.out.println("DAY NUMBER OUT OF RANGE");
return;
}

46
if (n < 1 || n > 100) {
System.out.println("DATE AFTER (N DAYS) OUT OF RANGE");
return;
}
// calculate the initial date
String dateStr = computeDate(dayNum, year);
// calculate the future date after adding specified number of days
int nDays = dayNum + n;
int nYear = year;
boolean leap = isLeapYear(year);
if (leap && nDays > 366) {
nYear = nYear + 1;
nDays = nDays - 366;
}
else if (nDays > 365) {
nYear = nYear + 1;
nDays = nDays - 365;
}
// calculate the final future date
String nDateStr = computeDate(nDays, nYear);
// display the inital date
System.out.println();
System.out.println("DATE: " + dateStr);
System.out.println("DATE AFTER " + n
+ " DAYS: " + nDateStr);
}
}//end

47
Output:
DAY NUMBER: 150
YEAR: 2023
DATE AFTER (N DAYS): 30

DATE: 30TH MAY, 2023


DATE AFTER 30 DAYS: 29TH JUNE, 2023

Variable Description:
Variable Datatype Purpose
dayNum int to store the day number
year int to store the year
n int to sore the number of days
leap boolean to indicating whether the input year is a leap
year.
monthDays int for storing the number of days in each month.
monthName int for storing the names of the months.
daySum int to calculate the total number of days in months
during computation.
i int to initialize loop
date int to store the calculated date
sb int to construct the date string
dateStr int to store the initial date string
nDays int to store the calculated future day number.
nYears int to store the year for the future date.
nDateStr int to store the final future date string

48
PROGRAM 19
A class Capital has been defined to check whether a sentence has words beginning
with a capital letter or not.
Some of the members of the class are given below:
Class name: Capital
Data member/instance variable:
sent: to store a sentence
freq: stores the frequency of words beginning with a capital letter
Member functions/methods:
Capital () : default constructor
void input (): to accept the sentence
boolean isCap(String w): checks and returns true if the word begins with a capital
letter, otherwise returns false
void display(): displays the sentence along with the frequency of the words
beginning with a capital letter
Specify the class Capital, giving the details of the constructor( ), void input( ),
boolean isCap(String) and void display( ). Define the main( ) function to create an
object and call the functions accordingly to enable the task.
Algorithm:
Step1. Initialize the frequency of capital words to 0.
Step2. Use a Scanner to input a sentence.
Step3. Define a method (isCap) to check if a word starts with a capital letter.
Step4. Split the sentence into words.
Step5. Iterate through words and increment the frequency for each word starting
with a capital letter.
Step6. Print the original sentence and the frequency of capital words.
Step7. Create an instance of the Capital class.
Step8.Input a sentence.
Step9.Display the results.
Solution:
import java.util.Scanner;
class Capital
{
private int freq;
private String sent;

public Capital() {
this.freq=0;
}

49
public void input()
{
Scanner s=new Scanner(System.in); // initialize scanner for user input
this.sent=s.nextLine();
}
private boolean isCap(String w){
return(w.charAt(0)>=65 && w.charAt(0)<=90);
}
public void display() {
String[] words=this.sent.split("");
System.out.println(this.sent);

for(String word : words)


{
if(isCap(word))
this.freq +=1;
}
System.out.println("Frequency of capital words:"+this.freq);//print result
}
public static void main(String args[]) {
Capital c=new Capital();
c.input();
c.display();
}
}//end
Output:
Enter a sentence: Hello World! This is a Test.
Hello World! This is a Test.
Frequency of capital words: 4

Variable Description:
Variable Datatype Purpose
freq int to store frequency
sent int to store input sentence
w int to represent each word
words int to store words after splitting the
input sentence

50
PROGRAM 20
A superclass Worker has been defined to store the details of a worker. Define a
subclass Wages to compute the monthly wages for the worker. The
details/specifications of both the classes are given below:
Class name: Worker
Data Members/instance variables:
Name: to store the name of the worker
Basic: to store the basic pay in decimals
Member functions:
Worker (…): Parameterised constructor to assign values to the instance variables
void display (): display the worker’s details
Class name: Wages
Data Members/instance variables:
hrs: stores the hours worked
rate: stores rate per hour
wage: stores the overall wage of the worker
Member functions:
Wages (…): Parameterised constructor to assign values to the instance variables of
both the classes
double overtime (): Calculates and returns the overtime amount as (hours*rate)
void display (): Calculates the wage using the formula wage = overtime amount +
Basic pay and displays it along with the other details
Specify the class Worker giving details of the constructor () and void display ( ).
Using the concept of inheritance, specify the class Wages giving details of
constructor ( ), double-overtime () and void display (). The main () function need not
be written.

51
Algorithm:
Step1. Define a worker class with attributes Name and Basic.
Step2.Create a constructor to initialize these attributes.
Step3.Include a display method to print the name and basic salary.
Step4. Define a wages class that extends the worker class.
Step5.Add attributes hrs, rate, and wage to represent hours worked, hourly rate,
and total wage.
Step6.Create a constructor to initialize these attributes, calling the superclass
constructor using super.
Step7.Implement an overtime method to calculate overtime pay.
Step8.Override the display method to include the total wage calculation and print
the result.
Step9.Create an instance of the wages class.
Step10.Input worker details and hours worked.
Step11.Display the worker's details and total wage.
Solution:
importjava.io.*;
class worker{
String Name;
double Basic;
public worker (String n, double b){
Name = n;
Basic = b;
}
public void display ( ){
System.out.println (Name);
System.out.println (Basic);
}
}
class wages extends worker{
int hrs, rate;
double wage
public wage (string n, double b, int h, int r, double w){
super (n, b);
hrs = h;
rate = r;
wage = w;
}
public double overtime (){

52
return (hours*rate);
}
public void display ( ){
super.display ();
wage = overtime () + Basic;
System.out.prinln(wages);
}
}//end
Output:
Name: John Doe
Basic: 2000.0
Wage: 2900.0
Variable Description:
Variable Datatype Purpose
Name String to store worker name
Basic double to store salary
hrs int to store number of hours
rate int to store the hourly wage rate
wage double to store the total wage

53
PROGRAM 21
Replace all vowels of a sentence with succeeding letter
Algorithm
STEP 1: START
STEP 2: Find length of the entered word and store in variable 1
STEP 3: for i=0 to 1-1, repeat STEP 4,5,6
STEP 4: Extract characters of the word and store in variable ch
STEP 5: if ch is a vowel, ch-ch+1
STEP 6: str str+ch
STEP 7: Display the original word and the new word
STEP 8: END
Solution
import java.util.Scanner;
public class CharacterManipulation {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // initialize scanner for user input
System.out.println("Enter a sentence:");
String s = sc.nextLine();
int l = s.length();
String str = "";

for (int i = 0; i < l; i++) {


char ch = s.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
str += ch;
}
}

System.out.println("Original - " + s + "\nNew Word - " + str); //print the result


}
}//end

54
Output
Enter a sentence:
Computer Application
Original - Computer Application
New Word – oueAiaio

Variable Description
Variable Datatype Purpose
s string to store input sentence
l int to store length
ch char extract character
str string to store new sentence
i int to store number of character in s

55
PROGRAM 22
Write a recursive function for printing Fibonacci series up to 100 terms.
Algorithm:
Step1. Create a class named fib to calculate Fibonacci numbers.
Step2. Implement a method fibo that calculates Fibonacci numbers recursively.
- If n is 1, return 0.
- If n is 2, return 1.
- If n is greater than 2, return the sum of the previous two Fibonacci numbers.
- Otherwise, return -1.
Step3. Create an instance of the fib class (obj1).
- Iterate from 1 to 10.
- Calculate the Fibonacci term using the fibo method.
- Print the term.
Solution:
class fib{
int fibo(int n) {
if(n == 1)
return 0;
else if(n==2)
return 1;
else if(n>2)
return fibo(n-1)+fibo(n-2);
else
return -1;
}
public static void main(String args[]) {
int i,term;
fib obj1=new fib();
//print fibonacci terms up to 10
for(i=1;i<=10;++i) {
term =obj1.fibo(i);
System.out.println(term);
}
}
}

56
Output:
0
1
1
2
3
5
8
13
21
34
Variable Description:
Variable Datatype Purpose
n int to store fibonacci term
i int to initialize the loop
term int to calculate fibonacci term
obj1 int to call fibo

57
PROGRAM 23
Finding HCF Using Recursion
Alogrithm
Main()
STEP 1: Accept first number
STEP 2: Accept second number
STEP 3: Calculate HCF
STEP 4: Display HFC
STEP 5:hcf(int a,int b)
STEP 6:If (a>b) is true then return (hef(a-b,b))
STEP 7: Otherwise if (b>a)is true return (hef(a,b-a))
STEP 8: Otherwise return a
Solution
import java.util.Scanner;
class HCF{
void main(){
Scanner sc=new Scanner(System.in); // initialize scanner for user input
System.out.println("enter number to find their HCF");
// enter a number from user
int a=new Scanner (System.in).nextInt();
int b= new Scanner (System.in).nextInt();
int c=HCF(a,b);
System.out.println("HCF="+c);
}
int HCF(int a,int b)
{
// to calculate
if (a>b)
return (HCF(a-b,b));
else if (b>a)
return (HCF(a,b-a));
else
return a;
}
}

58
Output
enter number to find their HCF
46
34
HCF=2

Variable Description:
Variable Datatype Purpose
a int to get number
b int to get number
c int to store hcf

59
PROGRAM 24
Write a program in java to convert number into word .
Algorithm:
Step1. enter a number.
Step2.If the input number is 0, print "Number in words: Zero" and exit.
Step3.Define arrays for units, teens, and tens.
Step4.Create a function convertNumberToWords that takes a long number as input.
Step5.If the number is negative, return "Negative " plus the conversion of the absolute
value.
Step6.Handle cases for numbers less than 10, numbers between 10 and 19, numbers
between 20 and 99, numbers between 100 and 999, thousands, millions, and billions.
Step7.Get user input for a number.
Step8.Print "Number in words: " plus the result of calling convertNumberToWords with the
input number.
Solution:
import java.util.Scanner;

public class NumberToWords {


private static final String[] units = {"", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine"};
private static final String[] teens = {"", "Eleven", "Twelve", "Thirteen", "Fourteen",
"Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private static final String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety"};

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in); // initialize scanner for user input
System.out.print("Enter a number: ");
long number = scanner.nextLong();

if (number == 0) {
System.out.println("Number in words: Zero");
} else {
System.out.println("Number in words: " + convertNumberToWords(number));
}
}

private static String convertNumberToWords(long number) {

60
if (number < 0) {
return "Negative " + convertNumberToWords(-number);
}

if (number < 10) {


return units[(int) number];
} else if (number < 20) {
return teens[(int) (number % 10)];
} else if (number < 100) {
return tens[(int) (number / 10)] + " " + convertNumberToWords(number %
10);
} else if (number < 1000) {
return units[(int) (number / 100)] + " Hundred " +
convertNumberToWords(number % 100);
} else if (number < 1000000) {
return convertNumberToWords(number / 1000) + " Thousand " +
convertNumberToWords(number % 1000);
} else if (number < 1000000000) {
return convertNumberToWords(number / 1000000) + " Million " +
convertNumberToWords(number % 1000000);
} else {
return convertNumberToWords(number / 1000000000) + " Billion " +
convertNumberToWords(number % 1000000000);
}
}
} //end

Output:
Enter a number: 256
Number in words: Two Hundred Fifty Six

Variable Description:
Variable Datatype Purpose
units string to store words for numbers from 1 to 9.
teens string to store words for numbers from 11 to 19.
tens string to store words for tens from 10 to 90
number long to store input number
absNumber long to handle negative number
result String to store final word

61
PROGRAM 25
Write a program to check niven number.
Algorithm:
Step 1.enter a number.
Step2.Initialize variables n, num, r, and sum to 0.
Step3.Copy the original number n to the variable num.
Step4.calculate
Step5.Check if true, print "Niven Number."
If false, print "Not Niven Number."
Solution:
import java.util.Scanner;
public class NivenNumber{
public static void main(String[] args){
int n, num, r,
sum = 0;
Scanner sc = new Scanner(System.in); //create a scanner object for user
System.out.print("Enter number=");
n = sc.nextInt(); //accepting value
num = n;
while (num > 0) {
r = num % 10;
sum = sum + r;
num = num / 10;
}
//check the number
if (n % sum == 0) {
System.out.println("Niven Number");
}
else {
System.out.println("Not Niven Number");
}
}
} //end

62
Output:
Enter number=234
Niven Number

Variable Description:
Variable Datatype Purpose
n int to store number
num int to store copy of n
r int to hold the reminder
sum int to sum of individual digit

63
CONCLUSION

Java is an object oriented programming language. It is a general purpose


programming language mainly designed to run developed Java code on all
platforms that support Java without recompilation.

As we all know, that Java is one of the most popular and in demand programming
languages to learn and it was one of the first languages to standardise high-level
threading utilities. Java project is a must for aspiring developers. This project has
the developers develop real -world projects to hone their skills and materialise their
theoretical knowledge into practical experience .Java has significant advantage
both as a commercial language and also as a teaching language. Java project
provides rigorous compile time error checking typically associated with Pascal
,allowing instructors to introduce students to GUI programming networking threads
and other important concepts used in modern day software. Overall the Java
project gives complete design for the extended language.

64
BIBLIOGRAPHY
1.https://www.knowledgeboat.com
2. https://www.keepkoding.com
3. Text book of sumita Arora ISC 12

65

You might also like