0% found this document useful (0 votes)
41 views53 pages

Class Xii Computer Science Project Work

Uploaded by

somdevroy007
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)
41 views53 pages

Class Xii Computer Science Project Work

Uploaded by

somdevroy007
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
You are on page 1/ 53

CLASS XII

COMPUTER SCIENCE
PROJECT WORK.

Name-Sreyan Saha
Class-12
Section-C
Roll No.-36
Subject-Computer Science

1|Computer Applications|Class XII Sreyan Saha|12C


CONTENTS

S.No
TOPIC Page No.

1 Program to check 4
Automorphic or Disarium

2 Program to check Prime, Armstrong and 7


Perfect Number from a square matrix.
3 Matrix multiplication 10

4 Stack operations 13

5 Queue operations 18

6 22
Circular queue operations
7 Date adder program 28

8 Sentence word sorting program 31

2|Computer Applications|Class XII Sreyan Saha|12C


9 Extract each word from a sentence and 33
convert to piglatin form

10 35
Decimal to octal and hexadecimal

11 Check whether matrix is wonder 38


square or not.

12 Check whether matrix is magic 42


square or not.

13 45
Convert a matrix to spiral form

14 48
Sentence operation program

15 Print first 10 Magic, duck, and 51


Krishnamurthy
numbers

3|Computer Applications|Class XII Sreyan Saha|12C


1. Write a program which will calculate the amount of electricity
bill on the basis of consumption of number of units consumed
according to following slab..

Program Coding:

import java.util.Scanner;

public class NumberCheck {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Create a Scanner object for user
input
System.out.print("Enter a number: ");
int num = sc.nextInt(); // Read the number input by the user

System.out.print("Enter 1 to check Automorphic or 2 to check Disarium: ");


int choice = sc.nextInt(); // Read the user's choice

switch (choice) {
case 1:
// Check if the number is Automorphic
if (isAutomorphic(num)) {
System.out.println(num + " is an Automorphic number.");
} else {
System.out.println(num + " is not an Automorphic number.");
}
break;
case 2:
// Check if the number is Disarium
if (isDisarium(num)) {
System.out.println(num + " is a Disarium number.");
} else {
System.out.println(num + " is not a Disarium number.");
}
break;
default:
System.out.println("Invalid choice."); // Handle invalid choice
}

sc.close(); // Close the Scanner object

4|Computer Applications|Class X Sreyan Saha|10C


}

// Function to check if a number is Automorphic


public static boolean isAutomorphic(int num) {
int square = num * num; // Calculate the square of the number
String numStr = String.valueOf(num); // Convert the number to a string
String squareStr = String.valueOf(square); // Convert the square to a string
return squareStr.endsWith(numStr); // Check if the square ends with the
number
}

// Function to check if a number is Disarium


public static boolean isDisarium(int num) {
int sum = 0, temp = num, length = String.valueOf(num).length(); // Initialize
variables

while (temp > 0) {


int digit = temp % 10; // Extract the last digit
sum += Math.pow(digit, length--); // Add the digit raised to the power of
its position
temp /= 10; // Remove the last digit
}

return sum == num; // Check if the sum is equal to the original number
}
}Output:

5|Computer Applications|Class X Sreyan Saha|10C


Variable glossary:

Variable Type Use

num int The number input by the user to be checked.

The user’s choice to check for either Automorphic (1) or


choice int Disarium (2).

The square of the number, used in the automorphic


square int check.

numStr String The string representation of the number.

squareStr String The string representation of the square of the number.

The sum of the digits powered with their respective


sum int positions, used in the disarium check.

A temporary variable used to iterate through the digits of


temp int the number.

The number of digits in the number, used to determine


length int the power for each digit in the disarium check.

6|Computer Applications|Class X Sreyan Saha|10C


2. Write a program to accept a square matrix, check for prime numbers,
Armstrong numbers, and perfect numbers, and print the matrix. .

Program Coding:

import java.util.Scanner;

public class MatrixCheck {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in); // Create a Scanner object for user input

System.out.print("Enter the dimension n of the square matrix: ");

int n = sc.nextInt(); // Read the dimension of the matrix

int[][] matrix = new int[n][n]; // Initialize the square matrix

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

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

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

matrix[i][j] = sc.nextInt(); // Read the elements of the matrix

int primeCount = 0, armstrongCount = 0, perfectCount = 0;

// Check each element in the matrix

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

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

if (isPrime(matrix[i][j])) primeCount++;

if (isArmstrong(matrix[i][j])) armstrongCount++;

if (isPerfect(matrix[i][j])) perfectCount++;

// Print the matrix

System.out.println("The entered matrix is:");

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

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

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

7|Computer Science|Class XII Sreyan Saha|12C


System.out.println();

// Print the counts

System.out.println("Number of prime numbers: " + primeCount);

System.out.println("Number of Armstrong numbers: " + armstrongCount);

System.out.println("Number of perfect numbers: " + perfectCount);

// Function to check if a number is prime

public static boolean isPrime(int num) {

if (num <= 1) return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) return false;

return true;

// Function to check if a number is an Armstrong number

public static boolean isArmstrong(int num) {

int sum = 0, temp = num, digits = String.valueOf(num).length();

while (temp > 0) {

int digit = temp % 10;

sum += Math.pow(digit, digits);

temp /= 10;

return sum == num;

// Function to check if a number is a perfect number

public static boolean isPerfect(int num) {

int sum = 0;

for (int i = 1; i <= num / 2; i++) {

if (num % i == 0) sum += i;

return sum == num;}}

8|Computer Science|Class XII Sreyan Saha|12C


Output :

Variable Glossary:

Variable Type Use

n int The dimension of the square matrix.

matrix int[][] The square matrix to store the elements.

primeCount int The count of prime numbers in the matrix.

armstrongCount int The count of Armstrong numbers in the matrix.

perfectCount int The count of perfect numbers in the matrix.

i, j int Loop variables for iterating through the matrix.

The number to be checked for prime, Armstrong, or


num int perfect properties.

sum int The sum used in Armstrong and perfect number checks.

temp int A temporary variable used in Armstrong number check.

The number of digits in the number, used in Armstrong


digits int number check.

9|Computer Science|Class XII Sreyan Saha|12C


3.Write a program to accept two matrices and find their product.

Program Coding:

import java.util.Scanner;

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Create a Scanner object for user input

// Input dimensions for the first matrix


System.out.print("Enter the number of rows for the first matrix: ");
int rows1 = sc.nextInt();
System.out.print("Enter the number of columns for the first matrix: ");
int cols1 = sc.nextInt();

// Input dimensions for the second matrix


System.out.print("Enter the number of rows for the second matrix: ");
int rows2 = sc.nextInt();
System.out.print("Enter the number of columns for the second matrix: ");
int cols2 = sc.nextInt();

// Check if matrix multiplication is possible


if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible with the given
dimensions.");
return;
}

// Initialize the matrices


int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];

// Input elements for the first matrix


System.out.println("Enter the elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = sc.nextInt();
}
}

10|Computer Science|Class XII Sreyan Saha|12C


// Input elements for the second matrix
System.out.println("Enter the elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = sc.nextInt();
}
}

// Initialize the result matrix


int[][] product = new int[rows1][cols2];

// Perform matrix multiplication


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Display the first matrix


System.out.println("First matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}

// Display the second matrix


System.out.println("Second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}

// Display the product matrix


System.out.println("Product of the matrices:");
for (int i = 0; i < rows1; i++) {
11|Computer Science|Class XII Sreyan Saha|12C
for (int j = 0; j < cols2; j++) {
System.out.print(product[i][j] + " ");
}
System.out.println();
}
}
}

Output:

Variable Glossary:

Variable Type Use

rows1 int The number of rows in the first matrix.

cols1 int The number of columns in the first matrix.

rows2 int The number of rows in the second matrix.

cols2 int The number of columns in the second matrix.

matrix1 int[][] The first matrix to store the elements.

matrix2 int[][] The second matrix to store the elements.

product int[][] The matrix to store the product of the two matrices.

i, j, k int Loop variables for iterating through the matrices.

12|Computer Science|Class XII Sreyan Saha|12C


4.Write a program that will accept ten names and perform all stack
operations on them using switch case.
Program Coding:

import java.util.Scanner;

public class StackOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] stack = new String[10];
int top = -1;

// Accepting ten names


System.out.println("Enter ten names:");
for (int i = 0; i < 10; i++) {
String name = scanner.nextLine();
stack[++top] = name; // Push operation
}

while (true) {
System.out.println("\nChoose an operation:");
System.out.println("1. Display Stack");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Search");
System.out.println("5. Exit");
int choice = scanner.nextInt();

13|Computer Science|Class XII Sreyan Saha|12C


scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
// Displaying stack
System.out.print("Stack: ");
for (int i = 0; i <= top; i++) {
System.out.print(stack[i] + " ");
}
System.out.println();
break;

case 2:
// Pop operation
if (top >= 0) {
System.out.println("Popped element: " + stack[top--]);
} else {
System.out.println("Stack is empty.");
}
break;

case 3:
// Peek operation
if (top >= 0) {
System.out.println("Top element: " + stack[top]);
} else {
System.out.println("Stack is empty.");

14|Computer Science|Class XII Sreyan Saha|12C


}
break;

case 4:
// Search operation
System.out.println("Enter a name to search:");
String searchName = scanner.nextLine();
int position = -1;
for (int i = 0; i <= top; i++) {
if (stack[i].equals(searchName)) {
position = i;
break;
}
}
if (position != -1) {
System.out.println(searchName + " found at position: " + (position
+ 1));
} else {
System.out.println(searchName + " not found in the stack.");
}
break;

case 5:
// Exit
System.out.println("Exiting...");
return;

15|Computer Science|Class XII Sreyan Saha|12C


default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}
Output

16|Computer Science|Class XII Sreyan Saha|12C


Variable Glossary:
Variable Name Type Use

scanner Scanner Reads user input

stack String[] Stores names

top int Tracks top of the stack

name String Holds each name input

choice int Stores menu choice

searchName String Holds the name to search

position int Stores search result position

17|Computer Science|Class XII Sreyan Saha|12C


5.Write a program which will do all queue operations.
.
Program Coding:

import java.util.Scanner;

public class QueueOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] queue = new String[10];
int front = -1, rear = -1;

// Accepting ten names


System.out.println("Enter ten names:");
for (int i = 0; i < 10; i++) {
String name = scanner.nextLine();
if (rear == -1) {
front = 0;
}
queue[++rear] = name; // Enqueue operation
}

while (true) {
System.out.println("\nChoose an operation:");
System.out.println("1. Display Queue");
System.out.println("2. Dequeue");
System.out.println("3. Peek");
System.out.println("4. Search");
System.out.println("5. Exit");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
// Displaying queue
System.out.print("Queue: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
18|Computer Science|Class XII Sreyan Saha|12C
break;

case 2:
// Dequeue operation
if (front <= rear) {
System.out.println("Dequeued element: " + queue[front++]);
if (front > rear) {
front = rear = -1; // Reset queue if empty
}
} else {
System.out.println("Queue is empty.");
}
break;

case 3:
// Peek operation
if (front <= rear) {
System.out.println("Front element: " + queue[front]);
} else {
System.out.println("Queue is empty.");
}
break;

case 4:
// Search operation
System.out.println("Enter a name to search:");
String searchName = scanner.nextLine();
int position = -1;
for (int i = front; i <= rear; i++) {
if (queue[i].equals(searchName)) {
position = i;
break;
}
}
if (position != -1) {
System.out.println(searchName + " found at position: " + (position - front +
1));
} else {
System.out.println(searchName + " not found in the queue.");
}
break;

19|Computer Science|Class XII Sreyan Saha|12C


case 5:
// Exit
System.out.println("Exiting...");
return;

default:
System.out.println("Invalid choice. Please try again.");
}
}
}
}

Output:

20|Computer Science|Class XII Sreyan Saha|12C


Variable Glossary:

Variable Name Type Use

scanner Scanner Reads user input

queue String[] Stores names

front int Tracks front of the queue

rear int Tracks rear of the queue

name String Holds each name input

choice int Stores menu choice

searchName String Holds the name to search

position int Stores search result position

21|Computer Science|Class XII Sreyan Saha|12C


6. Circular queue.

Program Coding:
import java.util.Scanner

public class CircularQueueOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String[] queue = new String[10];

int front = -1, rear = -1, size = 10;

// Accepting ten names

System.out.println("Enter ten names:");

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

String name = scanner.nextLine();

if ((rear + 1) % size == front) {

System.out.println("Queue is full. Cannot enqueue.");

} else {

if (front == -1) {

front = 0;}

rear = (rear + 1) % size;

queue[rear] = name; // Enqueue operation

}}

while (true) {

System.out.println("\nChoose an operation:");

22|Computer Science|Class XII Sreyan Saha|12C


System.out.println("1. Display Queue");

System.out.println("2. Dequeue");

System.out.println("3. Peek");

System.out.println("4. Search");

System.out.println("5. Exit");

int choice = scanner.nextInt();

scanner.nextLine(); // Consume newlin

switch (choice) {

case 1:

// Displaying queue

System.out.print("Queue: ");

if (front == -1) {

System.out.println("Queue is empty.");

} else {

int i = front;

while (true) {

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

if (i == rear) break;

i = (i + 1) % size;

System.out.println();

23|Computer Science|Class XII Sreyan Saha|12C


break;

case 2:

// Dequeue operation

if (front == -1) {

System.out.println("Queue is empty.");

} else {

System.out.println("Dequeued element: " + queue[front]);

if (front == rear) {

front = rear = -1; // Reset queue if empty

} else {

front = (front + 1) % size;

}}

break

case 3: //Peek operation

if (front == -1) {

System.out.println("Queue is empty.");

} else {

System.out.println("Front element: " + queue[front]);

break;

case 4:

// Search operation

24|Computer Science|Class XII Sreyan Saha|12C


System.out.println("Enter a name to search:");

String searchName = scanner.nextLine();

int position = -1;

if (front != -1) {

int i = front;

while (true) {

if (queue[i].equals(searchName)) {

position = i;

break;

if (i == rear) break;

i = (i + 1) % size;

}}

if (position != -1) {

System.out.println(searchName + " found at position: " + ((position -


front + size) % size + 1));

} else {

System.out.println(searchName + " not found in the queue.");

break;

case 5:

// Exit

System.out.println("Exiting...");
25|Computer Science|Class XII Sreyan Saha|12C
return;

default:

System.out.println("Invalid choice. Please try again.");

}}}}}

Output:

26|Computer Science|Class XII Sreyan Saha|12C


Variable Glossary:

Variable Name Type Use

scanner Scanner Reads user input

queue String[] Stores names

front int Tracks front of the queue

rear int Tracks rear of the queue

size int Size of the queue

name String Holds each name input

choice int Stores menu choice

searchName String Holds the name to search

position int Stores search result position

27|Computer Science|Class XII Sreyan Saha|12C


7.Write a program which will accept A date from a user and then accept the
number of days and add the number of days to the previous date.

Program Coding:

import java.util.Scanner;
public class DateAdder1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Accepting the date from the user
System.out.println("Enter the date (dd mm yyyy):");
int day = scanner.nextInt();
int month = scanner.nextInt();
int year = scanner.nextInt();
// Accepting the number of days to add
System.out.println("Enter the number of days to add:");
int daysToAdd = scanner.nextInt();
// Adding days to the date
int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Adjust for leap year
if (isLeapYear(year)) {
daysInMonth[1] = 29;
}
day += daysToAdd;
while (day > daysInMonth[month - 1]) {
day -= daysInMonth[month - 1];
month++;
if (month > 12) {
month = 1;
year++;
if (isLeapYear(year)) {
daysInMonth[1] = 29;
28|Computer Science|Class XII Sreyan Saha|12C
} else {
daysInMonth[1] = 28;
}
}
}

System.out.printf("New date: %02d %02d %04d\n", day, month, year);


}

// Method to check if a year is a leap year


public static boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true;
}
}
return false;
}
}

Output:

29|Computer Science|Class XII Sreyan Saha|12C


Variable Description Table:

Variable Name Type Use

scanner Scanner Reads user input

day int Holds the day part of the date

month int Holds the month part of the date

year int Holds the year part of the date

daysToAdd int Number of days to add

daysInMonth int[] Array of days in each month

30|Computer Science|Class XII Sreyan Saha|12C


8. Write a program to sort the words in a sentence in ascending order.
Program coding:
import java.util.Scanner;

public class SentenceSorter {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter a sentence


System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();

// Split the sentence into words


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

// Display the original sentence


System.out.println("Original sentence: " + sentence);

// Sort the words by length in ascending order manually


for (int i = 0; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
if (words[i].length() > words[j].length()) {
// Swap words[i] and words[j]
String temp = words[i];
words[i] = words[j];
words[j] = temp;
31|Computer Science|Class XII Sreyan Saha|12C
}}}
// Create the new sentence
String sortedSentence = "";
for (int i = 0; i < words.length; i++) {
sortedSentence += words[i];
if (i < words.length - 1) {
sortedSentence += " ";
}}
// Display the sorted sentence-
System.out.println("Sorted sentence: " + sortedSentence);
}}

Output:

Variable glossary:

Variable Name Type Use

scanner Scanner To read input from the user

sentence String The input sentence

words String[] Array of words from the sentence

temp String Temporary variable for swapping words

sortedSentence String The sentence with words sorted by length

32|Computer Science|Class XII Sreyan Saha|12C


9.Write a program which converts a sentence into PigLatin.

Program Coding:
import java.util.Scanner;

public class PigLatinConverter {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Accepting a sentence from the user


System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
String[] words = sentence.split(" ");
String pigLatinSentence = "";

// Converting each word to Pig Latin


for (String word : words) {
pigLatinSentence += convertToPigLatin(word) + " ";
}

// Printing the Pig Latin sentence


System.out.println("Pig Latin Sentence: " + pigLatinSentence.trim());
}

// Method to convert a word to Pig Latin


public static String convertToPigLatin(String word) {
String vowels = "AEIOUaeiou";
int firstVowelIndex = -1;

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


if (vowels.indexOf(word.charAt(i)) != -1) {
firstVowelIndex = i;
break;
}
}

if (firstVowelIndex == -1) {
return word + "ay";
} else if (firstVowelIndex == 0) {
return word + "yay";

33|Computer Science|Class XII Sreyan Saha|12C


} else {
return word.substring(firstVowelIndex) + word.substring(0, firstVowelIndex)
+ "ay";
}
}
}

Output:

Variable Glossary:

Variable Name Type Use

scanner Scanner Reads user input

sentence String Holds the input sentence

words String[] Array of words in the sentence

pigLatinSentence String Builds the Pig Latin sentence

word String Holds each word in the sentence

vowels String Contains all vowel characters

firstVowelIndex int Index of the first vowel in a word

34|Computer Science|Class XII Sreyan Saha|12C


10.Write a program to convert from Decimal to Octal and hexadecimal using
switch.

Program coding:

import java.util.Scanner;

public class DecimalConverter {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter a decimal number


System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();

// Prompt user to choose the conversion type


System.out.println("Choose the conversion type:");
System.out.println("1. Decimal to Octal");
System.out.println("2. Decimal to Hexadecimal");
int choice = scanner.nextInt();

// Perform the conversion based on user choice


switch (choice) {
case 1:
// Convert decimal to octal manually
String octal = decimalToOctal(decimal);
System.out.println("Octal value: " + octal);
break;
case 2:
// Convert decimal to hexadecimal manually
String hex = decimalToHexadecimal(decimal);
System.out.println("Hexadecimal value: " + hex);
break;
default:
System.out.println("Invalid choice. Please select 1 or 2.");
}
}

// Method to convert decimal to octal manually


public static String decimalToOctal(int decimal) {
35|Computer Science|Class XII Sreyan Saha|12C
String octal = "";
while (decimal > 0) {
int remainder = decimal % 8;
octal = remainder + octal;
decimal /= 8;
}
return octal;
}

// Method to convert decimal to hexadecimal manually


public static String decimalToHexadecimal(int decimal) {
String hex = "";
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
while (decimal > 0) {
int remainder = decimal % 16;
hex = hexChars[remainder] + hex;
decimal /= 16;
}
return hex;
}
}

OUTPUT:

36|Computer Science|Class XII Sreyan Saha|12C


Variable Glossary:

Variable Name Type Use

scanner Scanner To read input from the user

decimal int The input decimal number

choice int User’s choice for conversion type

octal String The octal representation of the decimal

hex String The hexadecimal representation of the decimal

remainder int Remainder when dividing by 8 or 16

hexChars char[] Array of hexadecimal characters

37|Computer Science|Class XII Sreyan Saha|12C


11.Write a program to accept a matrix and check if it is wonder square.

Program coding:

import java.util.Scanner;

public class WonderSquare {


public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();

if (n < 2 || n > 10) {


System.out.println("Invalid value of n!");
return;
}

int a[][] = new int[n][n];

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


for (int i = 0; i < n; i++) {
System.out.println("Enter Row " + (i + 1) + " :");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}

System.out.println("The 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();
}

// Check Wondrous
int nSq = n * n;
double validSum = 0.5 * n * (nSq + 1);
boolean wondrous = isWondrous(a);

if (wondrous) {

38|Computer Science|Class XII Sreyan Saha|12C


System.out.println("Yes, it represents a wondrous square");
} else {
System.out.println("Not a wondrous square");
}

// Print Prime Numbers


printPrime(a);
}

public static boolean isWondrous(int arr[][]) {


int n = arr.length;
int nSq = n * n;
double validSum = 0.5 * n * (nSq + 1);

// seenArr is used to check that numbers are not repeated


boolean seenArr[] = new boolean[nSq];

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


int rSum = 0, cSum = 0;

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


if (arr[i][j] < 1 || arr[i][j] > nSq) {
return false;
}

// Number is not distinct


if (seenArr[arr[i][j] - 1]) {
return false;
}

seenArr[arr[i][j] - 1] = true;

rSum += arr[i][j];
cSum += arr[j][i];
}

if (rSum != validSum || cSum != validSum) {


return false;
}
}

39|Computer Science|Class XII Sreyan Saha|12C


return true;
}

public static void printPrime(int arr[][]) {


int n = arr.length;

System.out.println("Prime\tRow Index\tColumn Index");

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


for (int j = 0; j < n; j++) {
if (isPrime(arr[i][j])) {
System.out.println(arr[i][j] + "\t" + i + "\t\t" + j);
}}}}

public static boolean isPrime(int num) {


int c = 0;

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


if (num % i == 0) {
c++;
}}

return c == 2;
}}
OUTPUT:

40|Computer Science|Class XII Sreyan Saha|12C


Variable Glossary:

Variable Name Type Use

in Scanner Reads user input

n int Size of the matrix

a int[][] Stores the elements of the matrix

nSq int Square of the matrix size

validSum double Required sum for rows and columns

wondrous boolean Indicates if the matrix is a wondrous square

seenArr boolean[] Tracks seen numbers

rSum int Sum of elements in a row

cSum int Sum of elements in a column

arr int[][] Matrix passed to methods

num int Number to check for primality

c int Counter for divisors

41|Computer Science|Class XII Sreyan Saha|12C


12.Write a program to accept a matrix and check if it is MAGIC square.

Program coding:

import java.util.Scanner;

public class MagicSquare {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter the dimension of the matrix


System.out.print("Enter the dimension n of the matrix: ");
int n = scanner.nextInt();

// Initialize the matrix


int[][] matrix = new int[n][n];

// Prompt user to enter the elements of the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Display the matrix


System.out.println("The matrix is:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Check if the matrix is a magic square and display the result


if (isMagicSquare(matrix, n)) {
System.out.println("The matrix is a magic square.");
} else {
System.out.println("The matrix is not a magic square.");
}

42|Computer Science|Class XII Sreyan Saha|12C


}

// Method to check if a matrix is a magic square


public static boolean isMagicSquare(int[][] matrix, int n) {
int sumDiagonal1 = 0, sumDiagonal2 = 0;

// Calculate the sum of the first diagonal


for (int i = 0; i < n; i++) {
sumDiagonal1 += matrix[i][i];
}

// Calculate the sum of the second diagonal


for (int i = 0; i < n; i++) {
sumDiagonal2 += matrix[i][n - 1 - i];
}

// If the sums of the diagonals are not equal, it's not a magic square
if (sumDiagonal1 != sumDiagonal2) {
return false;
}

// Check the sums of rows and columns


for (int i = 0; i < n; i++) {
int sumRow = 0, sumCol = 0;
for (int j = 0; j < n; j++) {
sumRow += matrix[i][j];
sumCol += matrix[j][i];
}
// If any row or column sum is not equal to the diagonal sum, it's not a magic
square
if (sumRow != sumDiagonal1 || sumCol != sumDiagonal1) {
return false;
}
}

// If all checks pass, it's a magic square


return true;
}
}

43|Computer Science|Class XII Sreyan Saha|12C


OUTPUT:

Variable Glossary:

Variable Type Use

scanner Scanner To read input from the user

n int Dimension of the matrix

matrix int[][] To store the elements of the matrix

sumDiagonal1 int Sum of the primary diagonal elements

sumDiagonal2 int Sum of the secondary diagonal elements

sumRow int Sum of the elements in the current row

sumCol int Sum of the elements in the current column

44|Computer Science|Class XII Sreyan Saha|12C


13.Write a program to accept a matrix and print its spiral form
.
Program coding:

import java.util.Scanner;

public class SpiralMatrix {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter the dimension of the matrix


System.out.print("Enter the dimension n of the matrix: ");
int n = scanner.nextInt();

// Initialize the matrix


int[][] matrix = new int[n][n];

// Prompt user to enter the elements of the matrix


System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Display the original matrix


System.out.println("The original matrix is:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

// Display the matrix in spiral form


System.out.println("The matrix in spiral form is:");
printSpiral(matrix, n);
}
45|Computer Science|Class XII Sreyan Saha|12C
// Method to print the matrix in spiral form
public static void printSpiral(int[][] matrix, int n) {
int top = 0, bottom = n - 1, left = 0, right = n - 1;

// Traverse the matrix in spiral order


while (top <= bottom && left <= right) {
// Print the top row
for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;

// Print the right column


for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;

// Print the bottom row if there are remaining rows


if (top <= bottom) {
for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}

// Print the left column if there are remaining columns


if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}
}
}

46|Computer Science|Class XII Sreyan Saha|12C


OUTPUT:

Variable Glossary:

Variable Type Use

scanner Scanner To read input from the user

n int Dimension of the matrix

matrix int[][] To store the elements of the matrix

top int Top boundary for spiral traversal

bottom int Bottom boundary for spiral traversal

left int Left boundary for spiral traversal

right int Right boundary for spiral traversal

47|Computer Science|Class XII Sreyan Saha|12C


14. Write a program in Java to accept a sentence from the user and print the
common characters and consonants in it. Now form a new sentence by changing
the consonants by their previous characters
.
Program coding:

import java.util.Scanner;

public class SentenceProcessor {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter a sentence


System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine().toUpperCase();

// Get common letters, consonants, and new sentence


String commonLetters = getCommonLetters(sentence);
String consonants = getConsonants(sentence);
String newSentence = getNewSentence(sentence);

// Display the results


System.out.println("THE COMMON LETTERS ARE: ");
System.out.println(commonLetters);
System.out.println("THE CONSONANTS ARE: ");
System.out.println(consonants);
System.out.println("FINAL OUTPUT: ");
System.out.println(newSentence);
}

// Method to get common letters (vowels) in the sentence


public static String getCommonLetters(String sentence) {
String commonLetters = "";
for (char c = 'A'; c <= 'Z'; c++) {
if (sentence.indexOf(c) != -1 && "AEIOU".indexOf(c) != -1) {
commonLetters += c + " ";
}
}
48|Computer Science|Class XII Sreyan Saha|12C
return commonLetters;
}

// Method to get consonants in the sentence


public static String getConsonants(String sentence) {
String consonants = "";
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
if ("BCDFGHJKLMNPQRSTVWXYZ".indexOf(c) != -1) {
consonants += c + " ";
}
}
return consonants;
}

// Method to create a new sentence by shifting consonants


public static String getNewSentence(String sentence) {
String newSentence = "";
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
if ("BCDFGHJKLMNPQRSTVWXYZ".indexOf(c) != -1) {
newSentence += (char) (c - 1);
} else {
newSentence += c;
}
}
return newSentence;
}
}

49|Computer Science|Class XII Sreyan Saha|12C


OUTPUT:

Variable Glossary:

Variable Type Use

scanner Scanner To read input from the user

sentence String To store the input sentence

commonLetters String To store common letters

consonants String To store consonants

newSentence String To store the new sentence

c char To iterate through characters

i int Loop index

50|Computer Science|Class XII Sreyan Saha|12C


15. Write a program in Java to print the first 10 magic and duck numbers along
with the first 4 Krishnamurthy number.
.
Program coding:

import java.util.Scanner;

public class SpecialNumbers {


// Method to check if a number is a magic number
public static boolean isMagicNumber(int num) {
int sum = 0;
while (num > 0 || sum > 9) {
if (num == 0) {
num = sum;
sum = 0;
}
sum += num % 10;
num /= 10;
}
return (sum == 1);
}

// Method to check if a number is a duck number


public static boolean isDuckNumber(int num) {
String strNum = Integer.toString(num);
return strNum.contains("0") && strNum.charAt(0) != '0';
}

// Method to check if a number is a Krishnamurthy number


public static boolean isKrishnamurthyNumber(int num) {
int sum = 0, temp = num;
while (temp > 0) {
sum += factorial(temp % 10);
temp /= 10;
}
return (sum == num);
}

// Method to calculate factorial of a number


51|Computer Science|Class XII Sreyan Saha|12C
public static int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int magicCount = 0, duckCount = 0, krishnamurthyCount = 0;
int num = 1;

System.out.println("First 10 Magic Numbers:");


while (magicCount < 10) {
if (isMagicNumber(num)) {
System.out.print(num + " ");
magicCount++;
}
num++;
}

System.out.println("\nFirst 10 Duck Numbers:");


num = 1;
while (duckCount < 10) {
if (isDuckNumber(num)) {
System.out.print(num + " ");
duckCount++;
}
num++;
}

System.out.println("\nFirst 4 Krishnamurthy Numbers:");


num = 1;
while (krishnamurthyCount < 4) {
if (isKrishnamurthyNumber(num)) {
System.out.print(num + " ");
krishnamurthyCount++;
}
52|Computer Science|Class XII Sreyan Saha|12C
num++;
}
}
}
OUTPUT:

Variable Glossary:

Variable Name Type Use

num int Current number being checked

magicCount int Counter for magic numbers

duckCount int Counter for duck numbers

krishnamurthyCount int Counter for Krishnamurthy numbers

sum int Sum of digits

temp int Temporary variable for number operations

fact int Factorial of a digit

strNum String String representation of number

****************************The End****************************

53|Computer Science|Class XII Sreyan Saha|12C

You might also like