0% found this document useful (0 votes)
16 views128 pages

Computer Project

This document contains a computer science project by Anunay Narayan Trivedi, focusing on Java programs. It includes multiple programs with algorithms and source code for tasks such as sorting sentences by word count, filling a matrix with characters, performing matrix multiplication, generating anagrams, and packing boxes into cartons. The document also acknowledges contributions from instructors, classmates, and family.

Uploaded by

itzkushagra1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views128 pages

Computer Project

This document contains a computer science project by Anunay Narayan Trivedi, focusing on Java programs. It includes multiple programs with algorithms and source code for tasks such as sorting sentences by word count, filling a matrix with characters, performing matrix multiplication, generating anagrams, and packing boxes into cartons. The document also acknowledges contributions from instructors, classmates, and family.

Uploaded by

itzkushagra1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NAME:

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

Accept a paragraph of text consisting of sentences that are terminated


by either ‘.’ (Full Stop), ‘!’ (exclamation mark) or a ‘?’ (question mark).
Assume that there can be a maximum of 10 sentences in a paragraph.
Write a program to arrange the sentences in increasing order of their
number of words.
Example:
INPUT : Please come and attend the party.
Hello!
How are you?
OUTPUT:
Hello = 1
How are you = 3
Please come and attend the party = 6

ALGORITHM
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);
}
}
}

VARIABLE DESCRIPTION TABLE


Data Type Variable Description

int c,n,count To store the number of words in every sentence


int p[] Array to store number of words in a part of paragraph
String pg To store the paragraph entered by user
int i,j As looping variables
String sent[] Array to store sentences
String w Formal parameter

OUTPUT
PROGRAM-2

Given a square matrix M [ ] [ ] of order ‘n’. The maximum value


possible for ‘n’ is 10. Accept three different characters from the
keyboard and fill the array according to the instruction given below.
Fill the upper and lower elements formed by the intersection of the
diagonals by character 1.
Fill the left and right elements formed by the intersection of the
diagonals by character 2.
Fill both the diagonals by character 3.
Output the result in format given below:
Example 1
ENTER SIZE: 4
INPUT: FIRST CHARACTER: ‘*’
SECOND CHARACTER: ‘?’
THIRD CHARACTER: ‘#’

ALGORITHM

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

int N To store the size of the matrix


char A[][] To store the characters in the
matrix entered by the user
char c1,c2,c3 To store the user entered first
second and third character
respectively
int i,j As looping variables

OUTPUT
PROGRAM-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);
}
}
}

VARIABLE DESCRIPTION TABLE


Data Type Variable Description

int r,c,r1,c1,r2,c2 To store number of rows and


columns respectively
int A[][] Integer arrays
int sum To store elements of resultant
array
int i,j,k As looping variables
OUTPUT
PROGRAM-4

Write a Program in Java to input a word and print its anagrams.


Note: Anagrams are words made up of all the characters present in the
original word by re-arranging the characters.
Example: Anagrams of the word TOP are: TOP, TPO, OPT, OTP,
PTO and POT.

ALGORITHM
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

int c To store total number of anagrams


String s To store the word entered by user
String x,y,z To store the anagrams of the entered word
int i As looping variable

OUTPUT
PROGRAM-5

A company manufactures packing cartons in four sizes i.e. cartons in


accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes. Design a
program to accept the number of boxes to be packed (N) by user
(maximum up to 1000 boxes) and display the break-up of the cartons
used in descending order of the capacity (i.e. preference should be
given to highest capacity available,
Ex1: INPUT: N=726
OUTPUT: 48 * 15 =720
6*1=6
Remaining boxes: = 0
Total number of boxes: =726
Total number of cartons: =16
Ex 2: INPUT: N=140
OUTPUT: 48 * 2= 96
24 *1 = 24
12*1 = 12
6*1=6
Remaining boxes 2 * 1 = 2
Total number of boxes =140
Total number of cartons =6
ALGORITHM
1. START.
2. Input number of boxes N (maximum 1000).
3. Initialize carton sizes as 48, 24, 12, 6.
4. For each carton size (starting from 48):
o Find number of cartons = N ÷ size.
o Update remaining boxes = N % size.
5. Repeat until all carton sizes are checked.
6. Display the break-up (only sizes where carton count > 0).
7. If some boxes remain (not divisible by 6), display them as
“unpacked boxes”.
8. END.

SOURCE CODE

import java.util.*;

public class PackingCartons


{
public static void main ()
{
Scanner sc = new Scanner(System.in);

// Step 1: Input number of boxes


System.out.print(“Enter number of boxes (max 1000): “);
int N = sc.nextInt();

// Step 2: Validate input


if (N < 1 || N > 1000)
{
System.out.println(“Invalid input! Enter between 1 and 1000.”);
}

// Step 3: Carton sizes (descending order)


int [] sizes = {48, 24, 12, 6};
int [] count = new int[sizes.length];

// Step 4: Calculate carton break-up


for (int I = 0; I < sizes.length; i++)
{
count[i] = N / sizes[i]; // number of cartons of this size
N = N % sizes[i]; // remaining boxes
}

// Step 5: Display result


System.out.println(“nCarton break-up:”);
for (int I = 0; I < sizes.length; i++)
{
if (count[i] > 0)
{
System.out.println(sizes[i] + “-box carton(s): “+ count[i]);
}
}

// Step 6: If leftover boxes remain


if (N > 0)
{
System.out.println(“Unpacked boxes (cannot fit into cartons): “ + N);
}
}
}

VARIABLE DESCRIPTION TABLE


VARIABLE DATATYPE DESCRIPTION

N int To enter number of


boxes

Sizes[] int Array to enter the


carton size

Count[] int To count the size of


array
OUTPUT
PROGRAM-6

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.*;

public class CircularPrime


{
public static void main ()
{
Scanner sc = new Scanner(System.in);

// Step 1: Input number


System.out.print("Enter a number: ");
int n = sc.nextInt();

// Step 2: Convert number to string for rotations


String s = String.valueOf(n);
int len = s.length();
boolean isCircularPrime = true;

// Step 3: Check each rotation


for (int i = 0; i < len; i++)
{
int rotated = Integer.parseInt(s);

// Prime check (inside main, no method)


boolean prime = true;
if (rotated < 2)
{
prime = false;
} else
{
for (int j = 2; j <= Math.sqrt(rotated); j++) {
if (rotated % j == 0) {
prime = false;
break;
}
}
}

if (! prime)
{
isCircularPrime = false;
break;
}

// Rotate string
s = s.substring(1) + s.charAt(0);
}

// Step 4: Display result


if (isCircularPrime)
System.out.println(n + " is a Circular Prime.");
else
System.out.println(n + " is NOT a Circular Prime.");

}
}

VARIABLE DESCRIPTION TABLE


VARIABLE DATATYPE DESCRIPTION

n int To store a number input


by user

s String To convert the number


into string

len int To find the length of the


string

isCircularPrime boolean To store Boolean value,


true

i int Variable to control loop


rotated int To check for rotation

prime boolean To check for prime

j int Control variable

OUTPUT
PROGRAM-7

Write a program to input a number and check whether it is a Buzz


number or not.
 Buzz number- Checking if a number ends with 7 or is divisible
by 7.

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.*;

public class BuzzNumber


{
public static void main ()
{
Scanner sc = new Scanner(System.in);

// Step 1: Input number


System.out.print("Enter a number: ");
int n = sc.nextInt();

// Step 2: Check Buzz Number


if (n % 7 == 0 || n % 10 == 7)
{
System.out.println(n + " is a Buzz Number.");
}
else
{
System.out.println(n + " is NOT a Buzz Number.");
}

}
}
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.*;

public class SmallestNumberDigitSum


{
public static void main ()
{
Scanner sc = new Scanner(System.in);

// Step 1: Input
System.out.print("Enter value of M (100 < M < 1000)");
int M = sc.nextInt();

System.out.print("Enter value of N (0 < N < 100)");


int N = sc.nextInt();

// Step 2: Validate input


if (M <= 100 || M >= 1000 || N <= 0 || N >= 100)
{
System.out.println("Invalid Input!");
}

// Step 3: Find required number


int num = M + 1;
while (true)
{
int temp = num;
int sum = 0;

// Calculate digit sum


while (temp > 0)
{
sum += temp % 10;
temp = temp / 10;
}

if (sum == N)
{
// Step 4: Count digits
int digits = 0;
temp = num;
while (temp > 0)
{
digits++;
temp = temp / 10;
}

// Step 5: Print results


System.out.println("The required number is: " + num);
System.out.println("Total number of digits: " + digits);
break;
}
num++;
}
}
}

VARIABLE DESCRIPTION TABLE


VARIABLE DATATYPE DESCRIPTION

M int Variable to store value


between 100 and 1000

N int Variable to store value


between 0 and 100

num int To store M+1

temp int Temperory vaiable to


store value of num and
prevent it from altering
sum int To store the sumof
digits
digits int To count the number of
digits of the number

OUTPUT
PROGRAM-9

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.
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;

public class CaesarCipher {


public static void main () {
Scanner sc = new Scanner(System.in);

// Step 1: Accept the input


System.out.print("Enter the plain text: ");
String text = sc.nextLine();

// Step 2: Validate the length of the input


if (text.length() < 4 || text.length() >= 100) {
System.out.println("INVALID LENGTH");
return;
}

// Step 3: Encrypt the text using ROT13


String encryptedText = ""; // Initialize an empty string to hold the
encrypted result

// Loop through each character in the input text


for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);

// Check if the character is uppercase


if (c >= 'A' && c <= 'Z') {
// Apply ROT13 to uppercase letters
c = (char) ('A' + (c - 'A' + 13) % 26);
}
// Check if the character is lowercase
else if (c >= 'a' && c <= 'z') {
// Apply ROT13 to lowercase letters
c = (char) ('a' + (c - 'a' + 13) % 26);
}
// Non-alphabet characters remain unchanged
encryptedText += c; // Concatenate the character to the result string
}
// Step 4: Print the encrypted text
System.out.println("The cipher text is:");
System.out.println(encryptedText);
}
}

VARIABLE DESCRIPTION TABLE


Variable Data Type Description

text String The input plain text entered by the user.


encryptedText String Holds the encrypted (cipher) text result.
c char A character in the input text being processed in the loop.
i int The index of the current character being processed in the
loop.

OUTPUT
PROGRAM-10

Write a program to accept a natural number less than 1000 and


display it in words.
Test cases include:
• Input: 29 → Output: TWENTY NINE
• Input: 119 → Output: ONE HUNDRED AND NINETEEN
• Input: 500 → Output: FIVE HUNDRED
• Input: 17001 → Output: OUT OF RANGE

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;

public class NumberToWords {


public static void main () {
Scanner sc = new Scanner(System.in);

System.out.print("INPUT NUMBER: ");


int number = sc.nextInt();

if (number < 1 || number >= 1000) {


System.out.println("OUT OF RANGE");
return;
}

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;

System.out.print(ones[hundredPart] + " HUNDRED");

if (remainder! = 0) {
System.out.print(" AND ");

if (remainder < 20) {


System.out.println(ones[remainder]);
} else {
int t = remainder / 10;
int o = remainder % 10;
if (o == 0) {
System.out.println(tens[t]);
} else {
System.out.println(tens[t] + " " + ones[o]);
}
}
} else {
System.out.println();
}
}
}
}

VARIABLE DESCRIPTION TABLE


Variable Data Type Description

number int The natural number input by the user


ones String[] Array holding words for digits 0 to 19
tens String[] Array holding words for tens multiples (20, 30, etc.)
hundredPart int The hundred digit of the number
remainder int The last two digits of the number

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;

public class ISBNValidator {


public static void main () {
Scanner sc = new Scanner(System.in);

System.out.print("INPUT CODE: ");


String code = sc.nextLine();

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;
}

System.out.println("SUM = " + sum);

if (sum % 11 == 0) {
System.out.println("LEAVES NO REMAINDER - VALID ISBN
CODE");
} else {
System.out.println("LEAVES REMAINDER - INVALID ISBN
CODE");
}
}
}

VARIABLE DESCRIPTION TABLE


Variable Data Type Description

code String The 10-character ISBN code entered by user


sum int The total calculated using ISBN formula
i int Loop counter from 0 to 9
digit int Holds the numeric value of each character
weight int The number used to multiply each digit (starts at 10)

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;

public class PalindromicWordsCounter {


public static void main () {
Scanner sc = new Scanner(System.in);

System.out.print("INPUT SENTENCE: ");


String sentence = sc.nextLine();

// Check if last character is.,? or !


char lastChar = sentence.charAt(sentence.length() - 1);
if (lastChar! = '.' && lastChar != '?' && lastChar != '!') {
System.out.println("INVALID INPUT: Sentence must end with.,? or !");
return;
}

// Remove the last punctuation mark


sentence = sentence.substring(0, sentence.length() - 1);

// Split sentence into words


String [] words = sentence.split(" ");

int palindromeCount = 0;
String palindromicWords = "";

for (int i = 0; i < words.length; i++) {


String word = words[i];
if (isPalindrome(word)) {
palindromicWords += word + " ";
palindromeCount++;
}
}

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);
}
}

// Method to check if a word is palindrome


public static boolean isPalindrome(String word) {
int left = 0;
int right = word.length() - 1;
while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}

VARIABLE DESCRIPTION TABLE


Variable Data Type Description

sentence String The input sentence from the user


words String[] Array of words in the sentence
i int Loop counter
word String Current word being checked
palindromeCount int Number of palindromic words found
palindromeWords String Stores all palindrome words found (for output)

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");
}

public static void main ()


{
Scanner sc = new Scanner(System.in);
BouncyNumber ob = new BouncyNumber();
System.out.print("Enter a number: ");
int n = sc.nextInt();
ob.isBouncy(n);
}
}

VARIABLE DESCRIPTION TABLE

Variable Name Data Type Description


n int Number entered by the user to check for bouncy property.
s String String representation of the number n.
ch char Stores a digit (character) of the number during comparison.
f int Flag variable to indicate if the number breaks the condition.
i int Loop control variable used for traversing the digits.
OUTPUT
PROGRAM-14
Write a program to declare a square matrix A [] [] of order ‘n’.
Allow the user to input positive integers into this matrix. Perform the
following tasks on the matrix:
(i)Output the original matrix.
(ii) Find the SADDLE POINT for the matrix. If the matrix has no
saddle point, output the message “NO SADDLE POINT”.
[Note: A saddle point is an element of the matrix such that it is
the minimum element for the row to which it belongs and
the maximum element for the column to which it belongs. Saddle
point for a given matrix is always unique.]
Example: In the Matrix
456
789
513
Saddle point = 7 because it is the minimum element of row 2 and
maximum element of column 1.

ALGORITHM
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);

System.out.print("Enter the order of the matrix: ");


int n = sc.nextInt();
int A [] [] =new int[n][n];
System.out.println("Inputting the elements in the matrix");
System.out.println("******************************");
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
System.out.print("Enter Element at ["+i+”] ["+j+"]: ");
A[i][j] = sc.nextInt();
}
}
System.out.println("******************************");
System.out.println("The Original Matrix is");
for (int i=0; i<n;i++)
{
for (int j=0; j<n; j++)
{
System.out.print(A[i][j] +"\t");
}
System.out.println();
}
int max, min, x, f=0;
for (int i=0; i<n;i++)
{
min = A[i][0];
x = 0;
for (int j=0; j<n; j++)
{
if(A[i][j] <min)
{
min = A[i][j];
x = j;
}
}
max = A[0][x];
for (int k=0; k<n;k++)
{
if(A[k][x]>max)
{
max = A[k][x];
} }
if(max==min)
{
System.out.println("********************");
System.out.println("Saddle point = "+max);
System.out.println("********************");
f=1;
} }
if(f==0)
{
System.out.println("********************");
System.out.println("No saddle point");
System.out.println("********************");
}
}
}

VARIABLE DESCRIPTION TABLE


Variable Data
Description
Name Type
n int Stores the order of the square matrix.
A int[][] 2D array to store matrix elements.
i int Loop counter variable for rows.
j int Loop counter variable for columns.
min int Stores the minimum element of a row.
x int Stores the column index of the row’s minimum element.
Stores the maximum element of the column corresponding to the
max int
row minimum.
k int Loop counter variable for scanning column elements.
Flag variable to indicate if saddle point is found (1 = found, 0 =
f int
not).
OUTPUT
PROGRAM-15
Write a Program in Java to input a number and check whether it is
a Keith Number or not.
Note: A Keith Number is an integer N with‘d’ digits with the
following property:

If a Fibonacci-like sequence (in which each term in the sequence is


the sum of the ‘d’ previous terms) is formed, with the first ‘d’ terms
being the decimal digits of the number N, then N itself occurs as a
term in the sequence.

For example, 197 is a Keith number since it generates the sequence


1, 7, 9, 17, 33, 57, 107, 197, ………..

Some Keith numbers are: 14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537

ALGORITHM
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;
}

int countOne(String s) // Function to count number of 1’s


{
int c = 0, l = s.length();
char ch;
for (int i=0; i<l; i++)
{
ch=s.charAt(i);
if(ch=='1')
c++; //counting 1’s
}
return c;
}
public static void main ()
{
EvilNumber ob = new EvilNumber();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number");
int n = sc.nextInt();
String bin = ob.toBinary(n);
System.out.println("Binary Equivalent"+bin);
int x = ob.countOne(bin);
System.out.println("Number of 1’s"+x);
if(x%2==0)
System.out.println(n+" Evil number");
else
System.out.println(n+" Not a evil number");
}
}

VARIABLE DESCRIPTION TABLE


Variable Data
Description
Name Type
n int Stores the number entered by the user.
Stores remainder when n is divided by 2 (for binary
r int
conversion).
s String Stores the binary equivalent of the number.
dig char[] Array storing binary digits '0' and '1'.
c int Counter to store number of 1’s in the binary string.
l int Stores the length of the binary string.
Temporarily stores each character of the binary string
ch char
while counting.
Stores the binary equivalent of n returned by
bin String
toBinary().
x int Stores the count of 1’s returned by countOne(bin).

OUTPUT
PROGRAM-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);
}
}
}

VARIABLE DESCRIPTION TABLE


Variable Name Data Type Description
n int Number of boxes to be packed (user input).
cart[] int[] Array storing carton sizes {48, 24, 12, 6}.
copy int Copy of n, used to display the total boxes.
totalCart int Stores the total number of cartons used.
Number of cartons of the current size in the
count int
loop.
i int Loop control variable for traversing cart[].

OUTPUT
PROGRAM-18

Write a program to check if a double dimensional array is doubly


markov or not

an example of a Doubly Markov Matrix that

0.20 .30 .50

.30 .40 .30

.50 .30 .2

 All elements are ≥0.


 Each row sums to 1:
o Row 1: 0.2+0.3+0.5=1.0
o Row 2: 0.3+0.4+0.3=1.0
o Row 3: 0.5+0.3+0.2=1.0
 Each column sums to 1:
o Column 1: 0.2+0.3+0.5=1.0
o Column 2: 0.3+0.4+0.3=1.0
o Column 3: 0.5+0.3+0.2=1.0

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;

public class markovdouble {


public static void main ()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n");
int n = sc.nextInt();
double a [][] = new double[n][n];

if (n < 3 || n >= 9) {
System.out.println("Invalid size");
sc.close();
}

System.out.println("Enter array elements");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextDouble();
}
}

System.out.println("Entered Matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
int flag = 1;

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


double sumrows = 0.0;
double sumcolumns = 0.0;

for (int j = 0; j < n; j++) {


if (a[i][j] < 0.0) {
flag = 0;
break;
}
sumrows += a[i][j];
}

for (int j = 0; j < n; j++) {


sumcolumns += a[j][i];
}

if (flag == 0) {
break;
}

if (sumrows != 1.0 || sumcolumns != 1.0) {


flag = 0;
break;
}
}

if (flag == 1) {
System.out.println("The matrix is a Doubly Markov Matrix.");
} else {
System.out.println("The matrix is Not a Doubly Markov Matrix.");
}

}}

VARIABLE DESCRIPTION TABLE


VARIABLE DATA TYPE DECSRIPTION
n int The size (number of
rows/columns) of the matrix.

a double[][] Elements of array


are stored
flag Int 1 if it is doubly markov else 0
if not
i int Loop counter, typically for
rows or main iteration.

j int Loop counter, typically for


columns or inner iteration.
sumrows double Sum of elements of rows

sumcolumns Double Sum of elements of columns


OUTPUT
PROGRAM-19

A class Rearrange has been defined to modify a word by bringing all


the vowels in the word at the beginning followed by the consonants.

Example: ORIGINAL becomes OIAIRGNL

Some of the members of the class are given below:

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;

public class Rearrange


{
// Data members
String w; // to store a word
String nw; // to store the rearranged word

// Constructor
Rearrange ()
{
w = "";
nw = "";
}

// Method to accept the word in UPPERCASE


void rw()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word in UPPERCASE: ");
w = sc.next().toUpperCase();
}

// Method to find the frequency of vowels and consonants


void fvc()
{
int v = 0, c = 0;
for (int i = 0; i < w.length(); i++)
{
char ch = w.charAt(i);
if ("AEIOU”. indexOf(ch)! = -1)
v++;
else if (Character.isLetter(ch))
c++;
}
System.out.println("Number of vowels: " + v);
System.out.println("Number of consonants: " + c);
}

// Method to rearrange the word with vowels followed by consonants


void arr ()
{
String vs = "";
String cs = "";
for (int i = 0; i < w.length(); i++)
{
char ch = w.charAt(i);
if ("AEIOU”. indexOf(ch)! = -1)
vs += ch;
else
cs += ch;
}
nw = vs + cs;
}

// Method to display the original and rearranged word


void dsp()
{
System.out.println("Original word: " + w);
System.out.println("Rearranged word: " + nw);
}
// Main function
public static void main ()
{
Rearrange obj = new Rearrange ();
obj.rw ();
obj.fvc ();
obj.arr ();
obj.dsp ();
}
}

VARIABLE DESCRIPTION TABLE


Name Type Description

w String Stores the original input word

nw String Stores the rearranged word

v int Counter to store number of vowels

c int Counter to store number of consonants

ch char Current character being checked

vs String Temporary string to collect vowels

OUTPUT
PROGRAM-20

Write a program in Java to check if a number is Smith number or not.

One classic example of a Smith number is 666.

1. Sum of digits of 666: 6+6+6=18


2. Prime factorization of 666: 666=2×3×3×37
3. Sum of digits of its prime factors:
o Digit sum of 2: 2
o Digit sum of 3: 3
o Digit sum of 3: 3
o Digit sum of 37: 3+7=10

Total sum of digits of prime factors: 2+3+3+10=18

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 ();

Scanner Sca = new Scanner(System.in);


int n = Sca.nextInt();

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.");
}
}
}

VARIABLE DESCRIPTION TABLE


VARIABLE DATA TYPE DESCRIPTION
s int Finding sum of digits of a
number
c int Counter to find factors
s2 int To find sum of all prime
numbers that are factors of a
number
s1 int Finding sum of digits of
prime number
k int Value of original number
OUTPUT
PROGRAM-21

Write a program to check if a number is circular/twisted prime or not

1. Original Number: 113, 113 is prime


2. First Rotation: 131 (moving the first digit '1' to the end)
o 131 is prime
3. Second Rotation: 311 (moving the first digit '1' to the end of
131)
o 311 is prime

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 prime (int n)

int c=0;

for (int i=1; i<=n;i++)

if(n%i==0)

c++;

return c;

public static void main ()

{
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;

twisted obj = new twisted ();

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

c int Counter for the number of


factors.
a string Stores the string form of the
number during rotation
checks.
l Int number of digits in the input
number.
flag int becomes 1 if any rotation is
found to be not prime.

k int The integer value of the


number's current rotation

OUTPUT
PROGRAM-22

A company manufactures packing cartons in four sizes i.e. cartons in


accommodate 6 boxes, 12 boxes, 24 boxes and 48 boxes. Design a
program to accept the number of boxes to be packed (N) by user
(maximum up to 1000 boxes) and display the break-up of the cartons
used in descending order of the capacity (i.e. preference should be
given to highest capacity available,
Ex1:
INPUT: N=726
OUTPUT: 48 * 15 =720
6*1 =6
Remaining boxes: =0
Total number of boxes: =726
Total number of cartons: =16
Ex 2:
INPUT: N=140
OUTPUT: 48 * 2 = 96
24 *1 = 24
12*1 = 12
6*1=6
Remaining boxes 2*1=2
Total number of boxes =140
Total number of cartons =6
ALGORITHM
1. START.
2. Get the total number of boxes
3. Set boxesLeft = N and totalCartons = 0.
4. For 48-box cartons: Calculate how many fit, print details, update
boxesLeft, add to totalCartons.
5. For 24-box cartons: Repeat Step 4's logic using the updated
boxesLeft.
6. For 12-box cartons: Repeat Step 4's logic using the updated
boxesLeft.
7. For 6-box cartons: Repeat Step 4's logic using the updated
boxesLeft.
8. Handle any remaining boxes: If boxesLeft is more than zero,
print them and add 1 to totalCartons. Otherwise, print 0
remaining.
9. Display the original N (total boxes).
10. Display the final totalCartons.
11. END.

SOURCE CODE
import java.util.*;

public class boxescartons {


public static void main () {
Scanner sc = new Scanner(System.in);
System.out.println("Enter total number of boxes");
int n = sc.nextInt();

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;

// Calculate for 48-box cartons


if (remainingBoxes >= 48) {
a = remainingBoxes / 48;
System.out.println("48 * " + a + "\t= " + (48 * a));
remainingBoxes %= 48;
totalCartons += a;
}

// Calculate for 24-box cartons from the *current* remainingBoxes


if (remainingBoxes >= 24) {
b = remainingBoxes / 24;
System.out.println("24 * " + b + "\t= " + (24 * b));
remainingBoxes %= 24;
totalCartons += b;
}

// Calculate for 12-box cartons


if (remainingBoxes >= 12) {
c = remainingBoxes / 12;
System.out.println("12 * " + c + "\t= " + (12 * c));
remainingBoxes %= 12;
totalCartons += c;
}

// Calculate for 6-box cartons


if (remainingBoxes >= 6) {
d = remainingBoxes / 6;
System.out.println("6 * " + d + "\t= " + (6 * d));
remainingBoxes %= 6;
totalCartons += d;
}

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);

}
}

VARIABLE DESCRIPTION TABLE


VARIABLE DATA TYPE DESCRIPTION
n int The total number of boxes to
pack.

a int Count of 48-box cartons used.

b Int Count of 24-box cartons used.

c Int Count of12-box cartons used.

d int Count of 6-box cartons used.

rem1 int Remainder from 48-box


calculation.
rem2 Int Remainder from 24-box
calculation.
rem3 Int Remainder from 12-box
calculation.
rem4 int Remainder from 6-box
calculation.
remainingBoxes int Boxes left to pack

totalCartons int Total


number
of
cartons
OUTPUT
PROGRAM-23

A Goldbach number is a positive even integer that can be


expressed as the sum of two odd primes. (All even integers greater
than 4 are Goldbach numbers.) [2018]

Ex: 10=3 + 7
10= 5 + 5

Write a program to accept an even integer ‘N’ where N>9 and


N<50. Find all the odd prime pairs whose sum is equal to the
number ‘N’.

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;

// Function to check if a number is prime

boolean isprime(int x) {

int c = 0;

for (int i = 1; i <= x; i++) {

if (x % i == 0)

c++;

if (c == 2)

return true;

else

return false;
}

// Function to take input

void input () {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number:");

n = sc.nextInt();

// Function to check Goldbach number

void isgoldbatch() {

if (n % 2 == 1 || n > 50 || n < 9) {

System.out.println("Invalid input");

return;

System.out.println("Number = " + n);

for (int i = 3; i <= n / 2; i++) {

if (isprime(i) && isprime(n - i)) {

System.out.println(i + " + " + (n - i));

// Main function

public static void main (String args[]) {


goldbatch ob = new goldbatch();

ob.input();

ob.isgoldbatch();

VARIABLE DESCRIPTION TABLE


Variable Use
n Global variable to accept number from user
x Formal parameter for checking prime numbers
c Counter to count number of factors

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 {

// Function to convert day number to date

String date (int d, int y) {

int m [] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// Leap year adjustment

if (y % 4 == 0 && y % 100! = 0 || y % 400 == 0)

m [1] += 1;

int mn = 0;

if (d > 365) {

if (m [1] == 28)

d -= 365;

else

d -= 366;

y++;

String date = "";


String month [] = {"January", "February", "March", "April", "May",
"June", "July",

"August", "September", "October", "November", "December"};

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

if (d <= m[i]) {

mn = i;

break;

d -= m[i];

// Adding suffix

if (d % 10 == 1 && d! = 11) date += d + "st ";

else if (d % 10 == 2 && d! = 12) date += d + "nd ";

else if (d % 10 == 3 && d! = 13) date += d + "rd ";

else date += d + "th ";

date += month[mn] + " " + y;

return date;

// Main function

public static void main () {

Scanner sc = new Scanner(System.in);

prac6 ob = new prac6();

System.out.println("Enter Day Number");


int day = sc.nextInt();

System.out.println("Enter Year");

int year = sc.nextInt();

System.out.println("Enter a number between 1 and 100");

int N = sc.nextInt();

if (day > 366 || day < 1 || year > 9999 || N > 100 || N < 1) {

System.out.println("Invalid Input");

else

System.out.println("Day Number: " + day);

System.out.println("Date: " + ob.date(day, year));

System.out.println("Date after " + N + " days: " + ob.date(day + N,


year));

}
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

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
following tasks on the matrix. [2016] (a) Sort the non-boundary
elements in ascending order using any standard sorting technique
and rearrange them in matrix. (b) Calculate the sum of both the
diagonals. (c) Display the original matrix, rearranged matrix and
only the diagonal elements of the rearranged matrix with their
sum.

ALGORITHM
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 {

public static void main () {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of the matrix");

int m = sc.nextInt();

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

System.out.println("Invalid size");

return;

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

int b [] = new int [(m - 2) * (m - 2)];

int c = 0;

// Input matrix and store non-boundary elements

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


for (int j = 0; j < m; j++) {

a[i][j] = sc.nextInt();

if (i != 0 && i != m - 1 && j != 0 && j != m - 1) {

b[c++] = a[i][j];

// Print original matrix

System.out.println("Original matrix");

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

for (int j = 0; j < m; j++) {

System.out.print(a[i][j] + "\t");

System.out.println();

// Bubble sort for non-boundary elements

for (int i = 0; i < b.length; i++) {

for (int j = 0; j < b.length - 1; j++) {

if (b[j] > b [j + 1]) {

int temp = b[j];

b [j] = b [j + 1];

b [j + 1] = temp;

}
}

// Place sorted elements back in matrix

c = 0;

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

for (int j = 1; j < m - 1; j++) {

a[i][j] = b[c++];

// Print arranged matrix

System.out.println("Arranged matrix");

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

for (int j = 0; j < m; j++) {

System.out.print(a[i][j] + "\t");

System.out.println();

// Sum of diagonal elements

System.out.println("Sum of diagonal elements");

int s = 0;

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

for (int j = 0; j < m; j++) {

if (i == j || i + j == m - 1) {
s += a[i][j];

System.out.print(a[i][j] + "\t");

} else {

System.out.print("\t");

System.out.println();

System.out.println(s);

VARIABLE DESCRIPTION TABLE

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.

2. Arrange the words in ascending order of their length. If two or


more words have the same length, then sort them alphabetically.

3. Display the original sentence along with the


converted sentence.

ALGORITHM
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 {

public static void main () {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the sentence");

String ss = sc.nextLine();

// Check for valid ending

if (ss.charAt(ss.length() - 1) != '.' && ss.charAt(ss.length() -


1) != '?' && ss.charAt(ss.length() - 1) != '!') {

System.out.println("Invalid input");

return;

// Convert to uppercase

ss = ss.toUpperCase();

System.out.println("Original String: " + ss);

// Remove last punctuation

ss = ss.substring(0, ss.length() - 1);

// Split into words

String s [] = ss.split(" ");


// Bubble sort based on length and alphabetical order

for (int i = 0; i < s.length; i++) {

for (int j = 0; j < s.length - i - 1; j++) {

if (s[j]. length () > s [j + 1]. length ()) {

String temp = s[j];

s[j] = s [j + 1];

s [j + 1] = temp;

else if (s[j]. length () == s [j + 1]. length ()) {

if (s[j]. compareTo (s [j + 1]) > 0) {

String temp = s[j];

s[j] = s [j + 1];

s [j + 1] = temp;

// Print converted string

System.out.println("Converted String:");

for (int i = 0; i < s.length; i++) {


System.out.print(s[i] + " ");

VARIABLE DESCRIPTION TABLE


Variable Use
ss String input from user
s[] String array after splitting words
Temporary variable used to swap elements during
temp
sorting

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 {

public static void main () {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the no. of teams");

int n = sc.nextInt();

sc.nextLine(); // consume newline

if (n < 3 || n > 8) {

System.out.println("Invalid no. of teams");

return;

char ch[][] = new char[n][100];

System.out.println("Enter the names of the teams:");

// Input team names

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

String s = sc.nextLine();

for (int j = 0; j < s.length(); j++) {

ch[i][j] = s.charAt(j);

}
// Display banner

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

boolean allEmpty = true;

for (int j = 0; j < n; j++) {

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;

VARIABLE DESCRIPTION TABLE


Variable Use
n Number of teams entered by the user
ch[][] Stores the characters of all team names
s Temporary string to hold each team name
OUTPUT
PROGRAM-29
A prime- Adam integer is a positive integer (without leading
zeros) which is a prime as well as an Adam-number. [2020] Adam
number: The Square of a number and the square of its reverse are
reverse to each other. Ex: if n=13 and reverse of n=31, then (13)
2 =169 (31) 2=961 which is reverse of 169 Thus, 13, is an Adam
number. Accept two positive integers m and n, where m is less
than n as user input. Display all Prime-Adam integers that are in
range between m and n (both inclusive) and output them along
with the frequency.

ALGORITHM
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);

System.out.println("Enter the range:");


int a = sc.nextInt();
int b = sc.nextInt();

int m = Math.min(a, b);


int n = Math.max(a, b);
int f = 0, f1 = 0;

for (int i = m; i <= n; i++) {


int c = 0;
// Prime check
for (int j = 1; j <= i; j++) {
if (i % j == 0)
c++;
}
// Check Adam Prime property
if (ob.reverse(i * i) == (ob.reverse(i) * ob.reverse(i)) && c == 2) {
if (f == 0) {
f = 1;
System.out.println("THE PRIME-ADAM INTEGERS ARE:");
}
System.out.print(i + "\t");
f1++;
}
}

System.out.println("\nFREQUENCY IS: " + f1);

if (f == 0)
System.out.println("No Adam prime number could be found.");
}
}

VARIABLE DESCRIPTION TABLE


VARIABLE USE

rev Stores and returns the reverse of a number

a Formal parameter for reverse function / also user input lower range

b User input upper range

d Stores digit while extracting in reverse function

m Minimum of the two numbers entered

n Maximum of the two numbers entered

f Flag variable (checks if at least one Adam Prime exists)

f1 Frequency (counts how many Adam primes are found)

c Counter to check if a number is prime


OUTPUT
PROGRAM-30
Write a program to declare a 1 D array a[] and a square matrix
b[][] of size N, where N >2 and N< 10. Allow the user to input
positive integers into the single dimensional array. Perform the
following tasks on the matrix: [2019] a) Sort the elements of the
single dimensional array in ascending order using any standard
sorting technique and display the sorted elements.
b) Fill the square matrix b[][] in the following format. If the
array a[]= {5,2,1,8} the after sorting a[] ={1,2,5,8} Then the
matrix b[][] would fill as below:

1258
1251
1212
1125

c) Display the filled matrix in the above format.

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 {

public static void main () {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of the array");

int n = sc.nextInt();

if (n < 2 || n > 10) {// corrected condition

System.out.println("Invalid size");

System.exit(0);

int a [] = new int[n];

int b [] [] = new int[n][n];


// Input array elements

for (int i = 0; i < n; i++)

a[i] = sc.nextInt();

// Bubble sort

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

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

if (a[j] > a [j + 1]) {

int temp = a[j];

a[j] = a [j + 1];

a [j + 1] = temp;

// Print sorted array

for (int i = 0; i < n; i++)

System.out.print(a[i] + "\t");

System.out.println();

System.out.println("Matrix:");

int x = 0;

for (int i = n - 1; i >= 0; i--) {

int j;

for (j = 0; j <= i; j++)

b[x][j] = a[j];
int m = 0;

for (int k = n - j + 1; k < n; k++)

b[i][k] = a[m++];

x++;

// Print 2D array

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

for (int j = 0; j < n; j++)

System.out.print(b[i][j] + "\t");

System.out.println();

VARIABLE DESCRIPTION TABLE


VARIABLE USE

n Array size input from user

a[] Single-dimensional array (stores user input and sorted values)

b[][] Double-dimensional array to store elements of a[] in matrix form

x Tracks the row index of the 2D array while filling

m Index variable for reusing elements of a[] while filling matrix

temp Temporary variable used for swapping during bubble sort

j, k, i Loop counters
OUTPUT

You might also like