Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Computer Project

Uploaded by

heheno42069
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Computer Project

Uploaded by

heheno42069
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Program 6:

Write a program in java that takes user input for a 4x4 matrix,
prints the original matrix, and then outputs the transpose of
the matrix.
Examples:
Enter the elements in the 4 x 4 matrix :
1234
5678
9 10 11 12
13 14 15 16
The Transpose of the matrix:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

33
Algorithm:
1. Start
2. Import the necessary Java I/O libraries.
3. Declare the Transpose class.
4. Define the main method with the throws IOException clause.
5. Declare and initialize integer variables i and j.
6. Create a 4x4 integer array num to store the original matrix.
7. Create another 4x4 integer array num1 to store the transpose of the
matrix.
8. Create an InputStreamReader object (read) to read input from the
console.
9. Create a BufferedReader object (in) to read input using the read object.
10. Prompt the user to enter elements for the 4x4 matrix.
11. Use nested loops to read user input and populate the num array.
12. Display a message indicating the entered matrix elements.
13. Use nested loops to print the original 4x4 matrix.
14. Display a message indicating the transpose operation.
15. Use nested loops to calculate and populate the num1 array with the
transpose of the num array.
16. Use nested loops to print the transpose matrix, completing the program.
17. End

34
Code:
import java.io.*;
public class Transpose {
public static void main(String args[]) throws IOException {
int i, j;
// Declare 2D arrays to store the original and transposed matrices
int num[][] = new int[4][4];
int num1[][] = new int[4][4];
// Set up input stream readers
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
// Prompt user to enter elements for the 4x4 matrix
System.out.println("Enter the elements in the 4 x 4 matrix :");
// Input loop to fill the original matrix
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
num[i][j] = Integer.parseInt(in.readLine());
}
}
// Display the elements of the original matrix
System.out.println("The elements of 4 x 4 matrix are:");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
System.out.print(num[i][j] + " ");
}
System.out.println();
}
// Display the message for the transposed matrix
System.out.println("The Transpose of the matrix:");
// Transpose the matrix and store it in num1

35
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
num1[j][i] = num[i][j];
}
}
// Display the elements of the transposed matrix
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
System.out.print(num1[i][j] + " ");
}
System.out.println();
}
}
}

Variable Description:
Variable Data Type Function
i int Loop control variable for rows in
matrices
j int Loop control variable for columns in
matrices
num int[][] Original 4x4 matrix to store user input
num1 int[][] Transposed 4x4 matrix

36
Output:

37
Program 7:
Write a program in Java that takes user input for the
dimension of a square matrix, finds the largest element in
each row, and finally displays the original matrix along with
the identified largest elements in each row.
Example:
Enter the dimension for a square matrix:
3
Enter the elements of the array:
123
456
789
Largest element in row 1: 3
Largest element in row 2: 6
Largest element in row 3: 9
1 2 3
4 5 6
7 8 9

38
Algorithm:
1. Start.
2. Declare a class named "ArrayMax."
3. Create a Scanner object "in" to take input from the user.
4. Declare integer variable "m" and a 2D array "arr."
5. Create a constructor "ArrayMax" with a parameter "mm" to initialize "m"
and allocate memory for the array.
6. Declare a method "readarray()" to read elements into the 2D array from
the user.
7. Print "Enter the elements of the array."
8. Use nested loops to iterate over each element of the array and take user
input.
9. Declare a method "large()" to find and print the largest element in each
row.
10. Use a loop to iterate over each row.
11. Initialize a variable "k" with the first element of the row.
12. Use another loop to compare each element in the row with "k" and update
"k" if a larger element is found.
13. Print the largest element in the current row.
14. Declare a method "display()" to print the elements of the array.
15. Use nested loops to iterate over each element and print it.
16. Declare the main method.
17. Prompt the user to enter the dimension for a square matrix and store it in
variable "l."
18. Create an object "ob" of the "ArrayMax" class with dimension "l," call
"readarray()," "large()," and "display()" methods on "ob," and end the
program.
19. End.

39
Code:
import java.util.*;
// Class definition for finding the maximum element in each row of a square matrix
public class ArrayMax {
// Scanner object for user input
Scanner in = new Scanner(System.in);
// Variable to store the dimension of the square matrix
int m = 0;
// 2D array to store the elements of the matrix
int arr[][];
// Constructor to initialize the matrix with the specified dimension
ArrayMax(int mm) {
m = mm;
arr = new int[mm][mm];
}
// Method to read elements into the array from user input
void readarray() {
System.out.println("Enter the elements of the array");
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = in.nextInt();
}
}
}
// Method to find and print the largest element in each row
void large() {
for (int i = 0; i < m; i++) {
int k = arr[i][0];
for (int j = 1; j < m; j++) {
if (arr[i][j] > k)

40
k = arr[i][j];
}
System.out.println("Largest element in row " + (i + 1) + ": " + k);
}
}
// Method to display the elements of the array
void display() {
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
// Main method for executing the program
public static void main(String Args[]) {
Scanner in = new Scanner(System.in);
// Prompt user to enter the dimension for a square matrix
System.out.println("Enter the dimension for a square matrix");
// Read user input for matrix dimension
int l = in.nextInt();
// Create an object of the ArrayMax class with the specified dimension
ArrayMax ob = new ArrayMax(l);
// Call methods to read array, find largest elements, and display the array
ob.readarray();
ob.large();
ob.display();
}
}

41
Variable Description:
Variable Data Type Function
m int Stores the dimension of the square matrix
arr int[][] 2D array to store the elements of the matrix
i, j int Loop control variables for rows and columns.
k int Temporary variable for finding the largest
element in each row.
l int Reads input for the dimension of the square
matrix.

Output:

42
Program 8:
Write a program in Java that takes a string as input, removes
duplicate letters from the string, and outputs the modified
string.
Examples:
Enter a String
programming
The new String after removing duplicate letters: progamin

Algorithm:
1. Start.
2. Initialize a Scanner object for user input.
3. Declare variables s1 and s2 as strings to store input and the result,
respectively.
4. Declare integer variables i, p, j, and t.
5. Display a prompt to the user: "Enter a String."
6. Read the input string from the user and store it in the variable s1.
7. Declare char variables ch1 and ch2.
8. Get the length of the input string and store it in the variable p.
9. Start a loop from i = 0 to i < p. 10. Inside the loop, set ch1 as the i-th
character of s1.
10. Initialize t to 0.
11. Start another loop from j = 0 to j < s2.length(). 13. Inside the inner loop,
set ch2 as the j-th character of s2.
12. Check if ch1 is equal to ch2. If true, set t to 1.
13. After the inner loop, check if t is equal to 0. 16. If true, concatenate ch1
to s2.

43
14. Display the result: "The new String after removing duplicate letters: "
followed by s2.
15. End.

44
Code:
import java.util.*;
// Class definition for removing duplicate letters from a string
class Duplicate {
// Main method for program execution
public static void main(String args[]) {
// Scanner object for user input
Scanner in = new Scanner(System.in);
// String variables to store input and result
String s1, s2 = "";
// Integer variables for looping and comparisons
int i, p, j, t;
// Display a prompt to the user
System.out.println("Enter a String");
// Read the input string from the user
s1 = in.next();
// Char variables for individual characters in the string
char ch1, ch2;
// Get the length of the input string
p = s1.length();
// Loop through each character in the input string
for (i = 0; i < p; i++) {
// Get the i-th character of the input string
ch1 = s1.charAt(i);
// Initialize a flag to check for duplicate letters
t = 0;
// Loop through each character in the result string
for (j = 0; j < s2.length(); j++) {
// Get the j-th character of the result string
ch2 = s2.charAt(j);

45
// Check if the characters are equal
if (ch1 == ch2)
t = 1; // Set the flag if characters are equal
}
// If the flag is not set, concatenate the character to the result string
if (t == 0)
s2 = s2 + ch1;
}
// Display the result
System.out.println("The new String after removing duplicate letters: " + s2);
}
}

Variable Description:
Variable Data Type Function
s1 String Input string to store the user's input.
s2 String Result string to store the modified string
without duplicate letters.
i int Loop control variable for iterating through
characters in the input string.
p int Length of the input string s1.
j int Loop control variable for iterating through
characters in the result string s2.
t int Flag to check for duplicate letters. If t is 0,
the character is not a duplicate.
ch1 char Temporary variable to store individual
characters from the input string s1.
ch2 char Temporary variable to store individual
characters from the result string s2.

46
Output:

47
Program 9:
Write a program in Java that converts a decimal number to its
binary equivalent.
Example:
Enter the decimal number:
25
The binary equivalent:
11001

Algorithm:
1. Start.
2. Declare integer variables i, d, n, n1, and j with an initial value of 0.
3. Declare an array num of integers with a size of 20.
4. Create a Scanner object in for user input.
5. Display the prompt: "Enter the decimal number:".
6. Read the input decimal number n from the user.
7. Set n1 to the value of n.
8. Start a while loop with the condition n1 > 0. 9. Inside the loop, calculate
the remainder d when n1 is divided by 2.
9. Store the remainder d in the array num at index j.
10. Increment j by 1.
11. Update n1 by dividing it by 2.
12. Display the message: "The binary equivalent:".
13. Start a for loop with the condition i = j-1 to i >= 0.
14. Inside the loop, print the element at index i of the array num.
15. End.

48
Code:
import java.util.*;
// Class definition for converting decimal to binary
public class Binary {
// Main method for program execution
public static void main(String[] args) {
// Declare integer variables
int i, d, n, n1, j = 0;
// Declare an array to store binary digits
int num[] = new int[20];
// Create a Scanner object for user input
Scanner in = new Scanner(System.in);
// Display a prompt for the user
System.out.println("Enter the decimal number: ");
// Read the input decimal number from the user
n = in.nextInt();
// Copy the value of n to n1 for further processing
n1 = n;
// Start a while loop to convert decimal to binary
while (n1 > 0) {
// Calculate the remainder when n1 is divided by 2
d = n1 % 2;
// Store the remainder in the array num at index j
num[j] = d;
// Increment the index j
j = j + 1;
// Update n1 by dividing it by 2
n1 = n1 / 2;
}
// Display the message indicating the start of binary equivalent

49
System.out.println("The binary equivalent:");
// Start a for loop to print the binary equivalent
for (i = j - 1; i >= 0; i--)
// Print each binary digit in reverse order
System.out.print(num[i]);
}
}

Variable Description:
Variable Data Type Function
i int Loop control variable for the binary
conversion loop.
d int Temporary variable to store the
remainder when dividing n1 by 2.
n int Input variable to store the decimal
number provided by the user.
n1 int Copy of the input variable n for further
processing in the conversion.
j int Index variable for the array num, keeps
track of the position to store binary digits.
num int[] Array to store the binary digits of the
converted number.

Output:

50
Program 10:
Write a program in Java that takes 10 numbers as input into an
array, then prompts the user to enter a number to be searched
in the array. If the number is present in the array, determine if
it's a prime number or not.
Examples:
Enter 10 numbers in the array:
5 8 12 7 20 3 15 9 11 25
Enter the number to be searched:
11
The number is present & Prime

Algorithm:
1. Start: Begin the execution of the program.
2. Declare integer variables i, j, n, c, and k with initial values.
3. Declare an array m of integers with a size of 20.
4. Create a Scanner object in for user input.
5. Display the prompt: "Enter 10 numbers in the array:".
6. Start a for loop with the condition i = 0 to i < 10. 7. Inside the loop, read
10 numbers from the user and store them in the array m.
7. Display the prompt: "Enter the number to be searched".
8. Read the number n to be searched from the user.
9. Start a for loop with the condition i = 0 to i < 10. 11. Inside the loop,
check if the current element in the array m is equal to n.
10. If true, set k to 1.
11. Check if k is equal to 1.
12. If true, start another for loop with the condition i = 1 to i <= n.
51
13. Inside the loop, check if n is divisible by i with no remainder.
14. If true, increment the variable c.
15. Check if c is equal to 2. 18. If true, display "The number is present &
Prime".
16. If false, display "The number is present & not Prime".
17. If k is not equal to 1, display "The number is not present".
18. End: Finish the execution of the program.

52
Code:
import java.util.*;
// Class definition for finding a number in an array and determining if it's prime
public class FindinArray {
// Main method for program execution
public static void main(String[] args) {
// Declare integer variables
int i, j, n, c = 0, k = 0;
// Declare an array to store numbers
int m[] = new int[20];
// Create a Scanner object for user input
Scanner in = new Scanner(System.in);
// Display a prompt: "Enter 10 numbers in the array:"
System.out.println("Enter 10 numbers in the array: ");
// Start a loop to read 10 numbers from the user and store them in the array
for (i = 0; i < 10; i++) {
m[i] = in.nextInt();
}
// Display a prompt: "Enter the number to be searched"
System.out.println("Enter the number to be searched");
// Read the number to be searched from the user
n = in.nextInt();
// Start a loop to check if the number is present in the array
for (i = 0; i < 10; i++) {
if (m[i] == n)
k = 1; // Set k to 1 if the number is found
}
// Check if the number is present
if (k == 1) {
// Start a loop to check if the number is prime

53
for (i = 1; i <= n; i++) {
if (n % i == 0)
c = c + 1; // Increment c for each divisor
}
// Check if the number of divisors is 2 (prime)
if (c == 2)
System.out.println("The number is present & Prime");
else
System.out.println("The number is present & not Prime");
}
else {
// If the number is not present
System.out.println("The number is not present");
}
}
}

Variable Description:

Variable Data Type Function


i int Loop control variable for various loops.
j int Additional loop control variable.
n int Input variable to store the number to be
searched.
c int Counter variable to count divisors of the
searched number.
k int Flag variable to determine if the number
is present in the array.
m int[] Array to store 20 numbers.

54
Output:

55
Program 11:
Write a program in Java that takes the coordinates of three
points as input and determines whether the triangle formed by
these points is a right-angled isosceles triangle.
Examples:
Enter the coordinates:
11
14
41
Right Angled Isosceles Triangle & Right angled at B

Algorithm:
1. Start.
2. Declare integer variables x1, x2, x3, y1, y2, y3, ab, bc, and ca.
3. Create a Scanner object in for user input.
4. Display the prompt: "Enter the coordinates".
5. Read the values of x1, y1, x2, y2, x3, y3 from the user.
6. Calculate the squares of the distances between points: ab, bc, and ca.
7. Check if the sum of ab and bc is greater than or equal to ca.
8. If true, check if the sum of ab and bc is equal to ca.
9. If true, display "Right Angled Isosceles Triangle & Right angled at B".
10. If false, check if the sum of bc and ca is equal to ab.
11. If true, display "Right Angled Isosceles Triangle & Right angled at C".
12. If false, check if the sum of ca and ab is equal to bc.
13. If true, display "Right Angled Isosceles Triangle & Right angled at A".
14. If all conditions are false, display "Not a Right Angled Triangle".

56
15. If the sum of ab and bc is less than ca, display "Not a Triangle".
16. End: Finish the execution of the program.

Code:
import java.util.*;
// Class definition for determining the type of triangle based on coordinates
public class Coordinates {
// Main method for program execution
public static void main(String args[]) {
// Create a Scanner object for user input
Scanner in = new Scanner(System.in);
// Declare integer variables for coordinates and distances
int x1, x2, x3, y1, y2, y3, ab, bc, ca;
// Display a prompt for the user to enter coordinates
System.out.println("Enter the coordinates");
// Read the coordinates from the user
x1 = in.nextInt();
y1 = in.nextInt();
x2 = in.nextInt();
y2 = in.nextInt();
x3 = in.nextInt();
y3 = in.nextInt();
// Calculate the squares of the distances between points
ab = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
bc = (x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2);
ca = (x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1);
// Check if the sum of ab and bc is greater than or equal to ca
if ((ab + bc) >= ca) {
// Check if the sum of ab and bc is equal to ca
if ((ab + bc) == ca)

57
System.out.println("Right Angled Isosceles Triangle & Right angled at B");
// Check if the sum of bc and ca is equal to ab
else if ((bc + ca) == ab)
System.out.println("Right Angled Isosceles Triangle & Right angled at C");
// Check if the sum of ca and ab is equal to bc
else if ((ca + ab) == bc)
System.out.println("Right Angled Isosceles Triangle & Right angled at A");
// If none of the above conditions are true, it's not a right-angled triangle
else
System.out.println("Not a Right Angled Triangle");
}
// If the sum of ab and bc is less than ca, it's not a triangle
else
System.out.println("Not a Triangle");
}
}

Variable Descriptoin:
Variable Data Type Function
x1, x2, x3, y1, y2, y3 int Coordinates of three points
ab, bc, ca int Squares of distances between
points

Output:

58
Program 12:
Write a program in Java to calculate the power of a number
using recursion.
Example:
Enter the value of base: 2
Enter the value of exponent: 5
2^5: 32
Algorithm:
1. Start
2. Create an instance of the PowerRec class.
3. Declare variables a, b, and res of type long.
4. Use a try block to handle exceptions.
5. Create a BufferedReader for user input.
6. Prompt the user to enter the value of 'Base'.
7. Read and parse the input value of 'Base'.
8. Prompt the user to enter the value of 'Exponent'.
9. Read and parse the input value of 'Exponent'.
10. Call the pow method with 'a' and 'b' as arguments and store the result in
'res'.
11. Display the result in the format "base^exponent: result".
12. End (Normal execution).
13. Exception Handling:
14. If an exception occurs, catch it and print the error message.
15. End (Exception handling).
16. Recursive Power Calculation:
17. In the pow method, check if 'n' is equal to 1.

59
18. If true, return 'm' as the base case of the recursion.
19. If false, return the product of 'm' and the result of the recursive call to
pow with 'm' and 'n-1'.
20. End (Algorithm completion).

Code:
import java.io.*;
// Class definition for calculating power using recursion
public class PowerRec {
// Main method for program execution
public static void main(String args[]) {
// Create an instance of the PowerRec class
PowerRec ob = new PowerRec();
// Declare variables a, b, and res of type long
long a, b, res;
try {
// Create a BufferedReader for user input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Prompt the user to enter the value of 'a'
System.out.print("Enter the value of base: ");
// Read and parse the input value of 'a'
a = Long.parseLong(br.readLine());
// Prompt the user to enter the value of 'b'
System.out.print("Enter the value of exponent: ");
// Read and parse the input value of 'b'
b = Long.parseLong(br.readLine());
// Call the pow method with 'a' and 'b' as arguments and store the result in 'res'
res = ob.pow(a, b);
// Display the result in the format "a^b: result"
System.out.println(a + "^" + b + ":" + res);
} catch (Exception e) {

60
// If an exception occurs, catch it and print the error message
System.out.println(e);
}
}
// Private method to calculate power using recursion
private long pow(long m, long n) {
// Check if 'n' is equal to 1
if (n == 1)
// Return 'm' as the base case of the recursion
return m;
else
// Return the product of 'm' and the result of the recursive call to pow with 'm' and 'n-1'
return (m * pow(m, n - 1));
}
}

Variable Description:

Variable Data Type Function


a long Stores the user-input value for base 'a'
b long Stores the user-input value for exponent 'b'
res long Stores the result of the power calculation
m long Represents the base value during recursive
calls
n long Represents the exponent value during
recursive calls

Output:

61
Program 13:
Write a program in Java that accepts elements for a
vector(maximum 25), removes duplicates, and displays the
resulting vector.
Example:
Enter how many elements (max 25): 6
Enter elements of vector ->
1
2
3
2
4
1
Orignal vector ->
1 2 3 2 4 1
Vector after deleting duplicates ->
1 2 3 4

Algorithm:
1. Start
2. Declare variables:
- Initialize `in` as a `DataInputStream` object.
- Declare `size` as a constant integer with value 25.
- Declare integer variables `i`, `j`, `n`, `k`, and `ans`, all initialized to 0.

62
- Declare an integer array `v` of size `size`.
3. Use a try-catch block to handle exceptions:
- Inside the try block:
- Print "Enter how many elements (max 25): ".
- Read the value of `n` from user input using `in.readLine()`, and parse it to
an integer.
- Print "Enter elements of vector -> ".
- Use a for loop to read `n` elements into the array `v`.
- Catch any exceptions silently.
4. Print "Original vector -> ".
5. Use a for loop to iterate over the elements of array `v` and print each element
followed by a tab character.
6. Use nested loops to compare elements and remove duplicates:
- Outer loop (`i`): Initialize `i` to 0; continue while `i` is less than `n-1`;
increment `i`.
- Inner loop (`j`): Initialize `j` to `i+1`; continue while `j` is less than `n`;
increment `j`.
- If `v[i]` equals `v[j]`, indicating a duplicate:
- Reduce the value of `n` by 1.
- Use a loop to shift elements to the left, starting from `j`.
- Set `ans` to 1 to indicate duplicates were found.
- Decrement `j` to recheck the current position.
7. Check if `ans` is 0:
- If true, print "Vector is without duplicates".
- If false, print "Vector after deleting duplicates ->".
8. Use a for loop to iterate over the elements of array `v` up to index `n`, and
print each element followed by a tab character.
9. End.

63
Code:
import java.io.DataInputStream;
// Class definition for vector operations
class vector {
// Main method for program execution
public static void main(String args[]) {
// Create a DataInputStream object for user input
DataInputStream in = new DataInputStream(System.in);
// Declare a constant integer size for the vector
final int size = 25;
// Declare integer variables i, j, n, k, and ans, initialize n and ans to 0
int i, j, n = 0, k, ans = 0;
// Declare an integer array v with size 'size'
int v[] = new int[size];
try {
// Prompt the user to enter the number of elements
System.out.println("Enter how many elements (max 25): ");
// Read and parse the input as an integer and store it in n
n = Integer.parseInt(in.readLine());
// Prompt the user to enter elements of the vector
System.out.println("Enter elements of vector -> ");
// Read 'n' elements from the user and store them in the array 'v'
for (i = 0; i < n; i++)
v[i] = Integer.parseInt(in.readLine());
} catch (Exception e) {
// Catch any exceptions silently
}
// Print "Original vector -> "
System.out.println("Orignal vector -> ");
// Iterate over the elements of 'v' and print each element followed by a tab character

64
for (i = 0; i < n; i++)
System.out.print(v[i] + "\t");
// Loop to compare and remove duplicates
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++) {
// Check if v[i] equals v[j]
if (v[i] == v[j]) {
// Reduce the size of 'n' by 1
n = n - 1;
// Shift elements to the left starting from 'j'
for (k = j; k < n; k++)
v[k] = v[k + 1];
// Set 'ans' to 1 to indicate duplicates were found
ans = 1;
// Decrement 'j' to recheck the current position
j = j - 1;
}
}
if (ans == 0) // Check if 'ans' is 0
// Print "Vector is without duplicates"
System.out.println("\nVector is without duplicates");
else {
// Print "Vector after deleting duplicates ->"
System.out.println("\nVector after deleting duplicates ->");
// Iterate over the elements of 'v' up to index 'n' and print each element followed by a
tab character
for (i = 0; i < n; i++)
System.out.print(v[i] + "\t");
}
}
}

65
Variable Description:
Variable Data Type Function
size int Constant integer representing the
maximum size of the vector
i, j, k int Loop control variables
n int Number of elements in the vector
ans int Flag to indicate if duplicates were found (0
for no, 1 for yes)
v int[] Array to store the elements of the vector

Output:

66
Program 14:
Write a program in Java to check if a number is fascinating or
not. A fascinating number is a number that when multiplied
by 2 and 3, and the results concatenated with the original
number, forms a sequence containing all digits from 1 to 9
exactly once.
Example:
Enter a no. greater than 99
192
The number 192 is a fascinating number
Enter a no. greater than 99
123
The number 123 is not a fascinating number
Algorithm:
1. Start.
2. Import the `java.util.*` package for using Scanner class.
3. Declare the class `fascinating`.
4. Define the main method `public static void main(String Args[])`.
5. Create a Scanner object `in` to read input from the console.
6. Print the message "Enter a no. greater than 99" to prompt the user.
7. Read the input number `n` using `nextInt()` method.
8. Initialize a string `a` with the digits "123456789".
9. Check if the input number `n` is less than or equal to 99.
10. If `n` is less than or equal to 99, print "The number is less than 99" and exit
the program using `System.exit(0)`.
11. Convert the input number and its multiples of 2 and 3 to strings and
concatenate them to form string `b`.

67
12. Initialize an integer variable `k` to count the occurrence of digits.
13. Start a nested loop to iterate over each digit from 1 to 9.
14. Inside the nested loop, iterate through the characters of string `b`.
15. Check if the current digit from string `a` matches any character in string `b`.
16. If a match is found, increment the counter `k`.
17. After both loops complete execution, check if `k` is equal to 9.
18. If `k` is equal to 9, print "The number is a fascinating number".
19. If `k` is not equal to 9, print "The number is not a fascinating number".
20. End.

Code:
import java.util.*;
// Class definition for determining if a number is fascinating
public class fascinating {
// Main method for program execution
public static void main(String Args[]) {
// Create a Scanner object to read input from the console
Scanner in = new Scanner(System.in);
// Prompt the user to enter a number greater than 99
System.out.println("Enter a no. greater than 99");
// Read the input number
int n = in.nextInt();
// Define a string with digits from 1 to 9
String a = "123456789";
// Check if the input number is less than or equal to 99
if (n <= 99) {
// If so, print a message and exit the program
System.out.println("The number is less than 99");
System.exit(0);

68
}
// Concatenate the input number, its double, and triple into a string
String b = Integer.toString(n) + Integer.toString(n * 2) + Integer.toString(n * 3);
// Initialize a counter variable
int k = 0;
// Iterate through each digit from 1 to 9
for (int i = 0; i < 9; i++) {
// Iterate through each character in the concatenated string
for (int j = 0; j < b.length(); j++) {
// Check if the current digit from string 'a' matches any character in string 'b'
if (a.charAt(i) == b.charAt(j))
// If so, increment the counter
k++;
}
}
// Check if the counter is equal to 9
if (k == 9)
// If so, print that the number is fascinating
System.out.println("The number" + n + " is a fascinating number");
else
// If not, print that the number is not fascinating
System.out.println("The number " + n + " is not a fascinating number");
}
}

69
Variable Description:
Variable Data Type Function
n int Stores the input number
a String String with digits from 1 to 9
b String Concatenated string of input number,
its double, and triple
k int Counter variable to count matching
digits

Output:

70
Program 15:
Write a program in Java to determine if a number is an Evil
Number or not. An Evil Number is a non-negative number
that has an even number of 1's in its binary representation.
Example:
Enter a positive number: 15
Binary Equivalent: 1111
No. of 1's: 4
The number is not an Evil Number

Algorithm:
1. Start.
2. Initialize a Scanner object `in` to read input from the console.
3. Prompt the user with the message "Enter a positive number: ".
4. Read the input number `n` using `nextInt()` method from Scanner.
5. Check if `n` is less than 0:
- If true, print "Invalid Input" and end the program.
6. Initialize an integer variable `count` and set it to 0 to count the number of 1's
in the binary representation.
7. Initialize an integer variable `p` and set it to 0 to keep track of the position of
the current digit in the binary representation.
8. Initialize an integer variable `binNum` and set it to 0 to store the binary
equivalent of the input number.
9. Enter a while loop:
- Continue the loop as long as `n` is greater than 0.
10. Within the loop:

71
- Calculate the remainder `d` when `n` is divided by 2 to determine the binary
digit.
- If `d` is equal to 1, increment the `count` variable.
- Update `binNum` by adding `(d * 10^p)` to it.
- Increment `p`.
- Update `n` by dividing it by 2.
11. Print "Binary Equivalent: " followed by the value of `binNum`.
12. Print "No. of 1's: " followed by the value of `count`.
13. Check if the remainder of `count` divided by 2 is equal to 0:
- If true, print "The number is an Evil Number".
- If false, print "The number is not an Evil Number".
14. End.

Code:
import java.util.*;
public class EvilNumber {
public static void main(String args[]) {
// Create a Scanner object to read input from the console
Scanner in = new Scanner(System.in);
// Prompt the user to enter a positive number
System.out.print("Enter a positive number: ");
// Read the input number
int n = in.nextInt();
// Check if the input number is negative
if (n < 0) {
// If negative, print "Invalid Input" and return
System.out.println("Invalid Input");
return;
}

72
// Initialize a counter variable to count the number of 1's
int count = 0;
// Initialize a variable to keep track of the position of the current digit in the binary
representation
int p = 0;
// Initialize a variable to store the binary equivalent of the input number
int binNum = 0;
// Loop to convert the input number to binary
while (n > 0) {
// Calculate the remainder when the input number is divided by 2
int d = n % 2;
// Increment the counter if the remainder is 1
if (d == 1)
count++;
// Update the binary number by adding the remainder multiplied by 10 raised to the
power of 'p'
binNum += (int) (d * Math.pow(10, p));
// Increment the position
p++;
// Update the input number by integer division with 2
n /= 2;
}
// Print the binary equivalent of the input number
System.out.println("Binary Equivalent: " + binNum);
// Print the number of 1's in the binary representation
System.out.println("No. of 1's: " + count);
// Check if the count of 1's is even
if (count % 2 == 0)
// If even, print that the number is an Evil Number
System.out.println("The number is an Evil Number");
else

73
// If odd, print that the number is not an Evil Number
System.out.println("The number is not an Evil Number");
}
}

Variable Description:
Variable Data Type Function
n int Stores the input number
count int Counts the number of 1's in the binary
representation
p int Tracks the position of the current digit in the
binary representation
binNum int Stores the binary equivalent of the input
number

Output

74
Program 16:
Write a program in Java to convert an octal number to
decimal. If the input octal number contains any digit greater
than 7, display "Invalid input for octal base" and exit the
program.
Examples:
Enter an octal number:
17
Invalid input for octal base

Enter an octal number:


235
Decimal of given octal is: 157

Algorithm:
1. Start.
2. Import the required classes from the Java utility package.
3. Define a class named Oct2Decimal.
4. Declare a method named getDecimal which takes an integer parameter octal
and returns an integer.
5. Declare integer variables decimal and ct and assign them initial values of 0.
6. Declare an integer variable b and assign it the value of octal.
7. Start a while loop with the condition b not equal to 0.
8. Within the loop, calculate the last digit of b by taking the modulus with 10
and store it in variable a.
9. Check if the last digit (a) is greater than 7.

75
10. If a is greater than 7, print "Invalid input for octal base" and exit the
program.
11. Divide b by 10 to remove the last digit.
12. Start a new while loop with the condition true.
13. Check if the octal number is 0, if so, exit the loop.
14. Otherwise, calculate the last digit of the octal number by taking the modulus
with 10 and store it in temp.
15. Update the decimal value by adding temp multiplied by 8 raised to the
power of ct.
16. Divide the octal number by 10 and increment ct.
17. Return the decimal value.
18. Define the main method.
19. Create a Scanner object for user input.
20. Prompt the user to enter an octal number, read the input, convert it to
decimal using the getDecimal method, and print the result.
21.End

Code:
import java.util.*;
// Class to convert octal numbers to decimal
public class Oct2Decimal{
// Method to convert octal to decimal
public static int getDecimal(int octal){
// Initialize variables for decimal and count
int decimal = 0;
int ct = 0;
int b= octal; // Copy the octal number for processing
// Loop to check if each digit in the octal number is valid
while (b != 0) {
int a = b%10; // Extract the last digit
if(a>7){

76
System.out.println("Invalid input for octal base"); // Print error message for invalid
input
System.exit(0); // Exit the program
}
b=b/10; // Remove the last digit
}
// Loop to convert octal to decimal
while(true){
if(octal == 0){
break; // Exit the loop if octal number becomes 0
}
else
{
int temp = octal % 10; // Extract the last digit of the octal number
decimal += temp*Math.pow(8, ct); // Update the decimal value
octal = octal/10; // Remove the last digit from the octal number
ct++; // Increment the count
}
}
return decimal; // Return the decimal value }
// Main method
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter an octal number:"); // Prompt the user to enter an octal
number
int num=sc.nextInt(); // Read the input octal number
Oct2Decimal od=new Oct2Decimal(); // Create an object of Oct2Decimal class
System.out.println("Decimal of given octal is: "+ od.getDecimal(num)); // Print the
decimal equivalent
}
}

77
Variable Description:
Variable Data Type Function
octal int Input parameter representing the octal
number
decimal int Stores the decimal equivalent of the octal
number
ct int Counter variable for tracking the position of
digits
b int Stores a copy of the input octal number for
processing
a int Stores the remainder when b is divided by 10
temp int Stores the last digit of the octal number
num int Stores the input octal number entered by the
user

Output:

78
Program 17:
Write a program in Java to generate the Fibonacci series up to
a specified limit entered by the user using recursion.
Example:
Enter the limit:
5
The Fibonacci series is:
01123
Algorithm:
1. Start
2. Import the required Java utilities.
3. Define a class named "fibo".
4. Define a method "fib" to calculate the Fibonacci sequence recursively.
5. Initialize variables "a" and "b" to 0 and 1 respectively.
6. Check if the input "n" is less than or equal to 1.
7. If true, return "a".
8. Check if "n" is equal to 2.
9. If true, return "b".
10. If none of the above conditions are met, calculate the Fibonacci sequence
recursively.
11. Define a method "genSeries" to generate the Fibonacci series.
12. Create a Scanner object for user input.
13. Prompt the user to enter the limit.
14. Read the input limit from the user.
15. Output a message indicating the start of the Fibonacci series.
16. Iterate from 1 to the input limit.

79
17. Within the loop, calculate the Fibonacci number for the current iteration.
18. Output the calculated Fibonacci number.
19. End the loop.
20. End.

Code:
import java.util.*;
// Define a class named fibo
class fibo{
// Method to calculate Fibonacci sequence recursively
int fib(int n){
int a=0,b=1;
// Check if n is less than or equal to 1
if (n <= 1)
return a;
// Check if n is equal to 2
else if(n==2)
return b;
// Calculate Fibonacci sequence recursively
else
return fib(n-1) + fib(n-2);
}
// Method to generate Fibonacci series
void genSeries(){
// Create Scanner object for user input
Scanner in=new Scanner(System.in);
int n ,c;
// Prompt user to enter the limit
System.out.println("Enter the limit:");
// Read input limit from user
80
n=in.nextInt();
// Output message indicating start of Fibonacci series
System.out.println("The Fibonacci series is:");
// Iterate from 1 to the input limit
for(int i=1;i<=n;i++) {
// Calculate Fibonacci number for current iteration
c=fib(i);
// Output the calculated Fibonacci number
System.out.print(c +" ");
}
}
// Main method
public static void main (String args[])
{
// Create an object of the fibo class
fibo ob=new fibo();
// Call the genSeries method to generate Fibonacci series
ob.genSeries();
}
}

Variable Description:
Variable Data Type Function
n int Stores the limit entered by the user
c int Stores the Fibonacci number for the current
iteration
a int Stores the first number in the Fibonacci
sequence
b int Stores the second number in the Fibonacci
sequence
i int Iterates through the Fibonacci sequence

81
Output:

82
Program 18:
Write a program in Java to determine whether a given square
matrix is a scalar matrix or not. A scalar matrix is defined as a
diagonal matrix where all the diagonal elements are equal.
Example:
Enter the size of the matrix : 3
Enter an element :(0,0) 3
Enter an element :(0,1) 0
Enter an element :(0,2) 0
Enter an element :(1,0) 0
Enter an element :(1,1) 3
Enter an element :(1,2) 0
Enter an element :(2,0) 0
Enter an element :(2,1) 0
Enter an element :(2,2) 3
The Matrix is :
3 0 0
0 3 0
0 0 3
The matrix is scalar

83
Algortihm:
1. Start
2. Import the required Java utilities.
3. Define a class named "ScalarMatrix".
4. Start the main method.
5. Create a Scanner object to read input from the user.
6. Prompt the user to enter the size of the matrix.
7. Read the size of the matrix entered by the user.
8. Initialize a 2D array "A" to store the matrix elements.
9. Start a nested loop to input the matrix elements.
10. Prompt the user to enter each element of the matrix.
11. Read each element and store it in the matrix array.
12. Output a message indicating the matrix.
13. Start a nested loop to print the matrix.
14. Print each element of the matrix separated by tabs.
15. Move through each row and print a newline after each row.
16. Initialize variables "p" and "q" to check for scalarity.
17. Initialize variable "x" to store the first main diagonal element.
18. Start nested loops to iterate through the matrix elements.
19. Check if the matrix is diagonal and scalar.
20. Output whether the matrix is scalar or not.
21. End.

84
Code:
import java.util.*;
// Define a class named ScalarMatrix
class ScalarMatrix{
// Main method
public static void main(String args[])throws Exception{
// Create a Scanner object to read user input
Scanner sc=new Scanner(System.in);
// Prompt the user to enter the size of the matrix
System.out.print("Enter the size of the matrix : ");
// Read the size of the matrix entered by the user
int m=sc.nextInt();
// Initialize a 2D array to store the matrix elements
int A[][]=new int[m][m];/* Inputting the matrix */
// Loop to input the matrix elements
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
// Prompt the user to enter each element of the matrix
System.out.print("Enter an element :("+i+","+j+") ");
// Read each element and store it in the matrix array
A[i][j]=sc.nextInt();
}
}
// Output a message indicating the matrix
System.out.println("The Matrix is : ");/* Printing the matrix */
// Loop to print the matrix
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
// Print each element of the matrix separated by tabs
System.out.print(A[i][j]+"\t");

85
}
// Move through each row and print a newline after each row
System.out.println();
}
// Initialize variables to check for scalarity
int p = 0, q = 0, x = A[0][0];
// 'x' is storing the 1st main diagonal element
// Loop to iterate through the matrix elements
for(int i=0;i<m;i++){
for(int j=0;j<m;j++){
/* Checking that the matrix is diagonal or not */
// All non-diagonal elements must be zero
if(i!=j && A[i][j]!=0) {
p=1;
break;
}
/* Checking the matrix for scalarity */
// All main diagonal elements must be equal to 'x' and non-zero
if(i==j && (A[i][j]==0 || A[i][j]!=x)) {
q=1;
break;
}
}
}
// Output whether the matrix is scalar or not
if(p==0 && q==0)
System.out.println("The matrix is scalar");
else
System.out.println("The matrix is not scalar");
}}

86
Variable Description:
Variable Data Type Function
m int Stores the size of the square matrix
A int[] Stores the elements of the square matrix
i,j int Iterators for loops to traverse the matrix
p int Flag to indicate if the matrix is not scalar
q int Flag to indicate if the matrix is not scalar
x int Stores the value of the first main diagonal
element

Output:

87
Program 19:
Write a program in Java to find the saddle points in a square
matrix. A saddle point is an element that is the smallest in its
row and largest in its column.
Example:
Enter the order of the matrix : 3
Inputting the elements in the matrix
Enter Element at [0][0] : 1
Enter Element at [0][1] : 2
Enter Element at [0][2] : 3
Enter Element at [1][0] : 4
Enter Element at [1][1] : 5
Enter Element at [1][2] : 6
Enter Element at [2][0] : 7
Enter Element at [2][1] : 8
Enter Element at [2][2] : 9
The Original Matrix is
1 2 3
4 5 6
7 8 9
Saddle point = 7

88
Algorithm:
1. Start
2. Import the required Java input/output utilities.
3. Define a class named "SaddlePoint".
4. Start the main method.
5. Create a BufferedReader object to read input from the user.
6. Prompt the user to enter the order of the matrix.
7. Read the order of the matrix entered by the user.
8. Initialize a 2D array "A" to store the matrix elements.
9. Output a message indicating the input process for the matrix elements.
10. Start nested loops to input the matrix elements.
11. Prompt the user to enter each element of the matrix.
12. Read each element and store it in the matrix array.
13. Output a message indicating the original matrix.
14. Start nested loops to print the original matrix.
15. Print each element of the matrix separated by tabs.
16. Move through each row and print a newline after each row.
17. Initialize variables to find the saddle point(s): "max", "min", "x", and "f".
18. Start a loop to iterate through each row of the matrix.
19. Inside the loop, find the minimum element of the row and its column
position.
20. Check if the minimum element of the row is equal to the maximum
element in its column. If so, output the saddle point. If not, continue to
the next row. If no saddle point is found, output a message indicating its
absence.
21. End.

89
Code:
import java.io.*;
// Define a class named SaddlePoint
class SaddlePoint{
// Main method
public static void main(String args[])throws IOException {
// Create a BufferedReader object to read input from the user
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// Prompt the user to enter the order of the matrix
System.out.print("Enter the order of the matrix : ");
// Read the order of the matrix entered by the user
int n=Integer.parseInt(br.readLine());
// Initialize a 2D array to store the matrix elements
int A[][]=new int[n][n];
// Output a message indicating the input process for the matrix elements
System.out.println("Inputting the elements in the matrix");
// Start nested loops to input the matrix elements
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
// Prompt the user to enter each element of the matrix
System.out.print("Enter Element at ["+i+"]["+j+"] : ");
// Read each element and store it in the matrix array
A[i][j]=Integer.parseInt(br.readLine());
}
}
// Output a message indicating the original matrix
System.out.println("The Original Matrix is");
// Start nested loops to print the original matrix
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {

90
// Print each element of the matrix separated by tabs
System.out.print(A[i][j]+"\t");
}
// Move through each row and print a newline after each row
System.out.println();
}
// Initialize variables to find the saddle point(s): "max", "min", "x", and "f"
int max, min, x, f=0;
// Start a loop to iterate through each row of the matrix
for(int i=0;i<n;i++) {
// Finding the minimum element of a row
min = A[i][0];
// Initializing min with first element of every row
x = 0;
for(int j=0;j<n;j++) {
if(A[i][j]<min) {
min = A[i][j];
x = j;
// Saving the column position of the minimum element of the row
}
}
// Finding the maximum element in the column corresponding to the minimum
element of row
max = A[0][x];
// Initializing max with first element of that column
for(int k=0;k<n;k++) {
if(A[k][x]>max) {
max = A[k][x];
}
}

91
// If the minimum of a row is same as maximum of the corresponding column, then,
we have that element as the Saddle point
if(max==min) {
System.out.println("Saddle point = "+max); f=1;
}
}
// Output whether a saddle point is found or not
if(f==0) {
System.out.println("No saddle point");
}
}
}

Variable Description:
Variable Data Type Function
n int Stores the order of the square matrix
A int[] Stores the elements of the square matrix
i,j int Iterators for loops to traverse the matrix
max int Stores the maximum element in a column
min int Stores the minimum element in a row
x int Stores the column position of the minimum
element of the row
f int Flag to indicate if a saddle point is found

Output:

92
Program 20:
Write a program in Java to determine if a given number is a
PalPrime number or not. A PalPrime number is both a
palindrome and a prime number.
Example:
Enter number to check
131
131 is a PalPrime number

Algorithm:
1. Start
2. Import the necessary Java utilities.
3. Define a class named “PalPrimeNumber” to check whether the given
number is a PalPrime number.
4. Start the main() method.
5. Create a Scanner object to get input from the user.
6. Declare and initialize variables: “number”, “temp”, “rem”, “i”, “count”,
and “sum”.
7. Prompt the user to enter a number to check.
8. Read the input number from the user.
9. Store the input number in a temporary variable “temp”.
10. Use a for loop to check whether the number is prime or not.
11. Increment the “count” variable when the remainder is 0.
12. Use a while loop to check whether the number is a palindrome or not.
13. Get the last digit of the number.
14. Store the last digit in the “sum” variable.
15. Extract all digits except the last.

93
16. Check whether the number is both a palindrome and a prime number.
17. If the number is a PalPrime number, output it.
18. If the number is not a PalPrime number, output it.
19. End.

Code:
import java.util.*;
// Create PalPrimeNumber class to check whether the given number is a PalPrime number or
not
class PalPrimeNumber
{
// main() method start
public static void main(String args[])
{
// Create scanner class object to get input from user
Scanner in = new Scanner(System.in);
// Declare and initialize variables
int number, temp, rem, i;
int count = 0;
int sum = 0;
// Prompt the user to enter number to check
System.out.println("Enter number to check");
// Get input from user
number = in.nextInt();
// Store number in a temporary variable temp
temp = number;

// Use for loop to check whether number is prime or not


for(i = 1; i <= temp; i++)
{
if(temp % i == 0)

94
{
count++; // Increment counter when the reminder is 0
}
}
// Use while loop to check whether the number is palindrome or not
while(number > 0)
{
// Get last digit of the number
rem = number % 10;
// Store the last digit
sum = sum * 10 + rem;

// Extract all digits except the last


number = number / 10;
}
// Check whether the number is palindrome and Prime or not
if(temp == sum && count == 2)
{
System.out.println(temp + " is a PalPrime number");
}
else
{
System.out.println(temp + " is not a PalPrime number");
}
}
}

95
Variable Description:
Variable Data Type Function
number int Stores the input number provided by the
user.
temp int Stores the original input number temporarily.
rem int Stores the remainder when extracting the last
digit.
i int Loop variable used for iterating.
count int Counts the number of factors of the input
number.
sum int Stores the reverse of the input number for
palindrome check.

Output:

96

You might also like