0% found this document useful (0 votes)
33 views200 pages

Com Piter

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

Com Piter

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

COMPUTER PROJECT CMS

MAHANAGAR

INTERNAL ASSESSMENT
NAME
CLASS
SECTION
MARKS
SIGN

EXTERNAL ASSESMENT
NAME
CLASS
SECTION
MARKS
SIGN

ACKNOWLEDGEMENT
INDEX
S.NO HEADING
1 PROGRAMMING-1
2 PROGRAMMING-2
3 PROGRAMMING-3
4 PROGRAMMING-4

5 PROGRAMMING-5
6 PROGRAMMING-6
7 PROGRAMMING-7
8 PROGRAMMING-8
9 PROGRAMMING-9
10 PROGRAMMING-10
11 PROGRAMMING-11

12 PROGRAMMING-12
13 PROGRAMMING-13
14 PROGRAMMING-14
15 PROGRAMMING-15
16 PROGRAMMING-16
17 PROGRAMMING-17
18 PROGRAMMING-18
19 PROGRAMMING-19
20 PROGRAMMING-20

I would like to express my special


thanks of grattude to my teacher Mr.
Sumit Kapoor as well as our principal
Kalpana Tripathi maam who gave me
golden opportunity to do this project
which also helped me in doing a lot
research and i came to knew about
many new things i am really thankful to
them. Secondly i would also like to
thank my parents and friends who
helped me in finalizing the project within
the limited time frame
Q1.A class MatrixTranspose has been
defined with the following details:

Data Members/Instance Variables:


- matrix[][] : To store the original matrix
- rows : For the number of rows in the
matrix
- cols : For the number of columns in
the matrix

Member Functions/Methods:
- MatrixTranspose(int r, int c) : Default
Constructor
- void getMatrix() : To initialize the
matrix
- void transpose() : To carry out the
transpose operation
- void display() : To display the
transposed matrix

Define the main() function to create an


object and call the functions
accordingly.

A1. import java.util.*;


class MatrixTranspose {
// Data Members/Instance Variables
int matrix[][];
int rows, cols;
Scanner sc = new
Scanner(System.in);

// Default Constructor
MatrixTranspose(int r, int c) {
rows = r;
cols = c;
matrix = new int[rows][cols];
}

// Method to initialize the matrix


void getMatrix() {
System.out.println("Enter elements
of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print("Element ["
+ i + "][" + j + "]: ");
matrix[i][j] = sc.nextInt();
}
}
}

// Method to carry out the transpose


operation
void transpose() {
int transposed[][] = new int[cols]
[rows];

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


for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}

// Displaying transposed matrix


System.out.println("Transposed
Matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transposed[i][j] + " ");
}
System.out.println();
}
}

// Method to display original matrix


(optional)
void display() {
System.out.println("Original
Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] +
" ");
}
System.out.println();
}
}
// Main method to create an object
and call functions accordingly
public static void main(String args[]) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter number of
rows: ");
int r = sc.nextInt();
System.out.print("Enter number of
columns: ");
int c = sc.nextInt();
MatrixTranspose ob = new
MatrixTranspose(r, c);
ob.getMatrix();
ob.display();
ob.transpose();
}
}

ALGORITHM:

1. Start the program.


2. Define a class MatrixTranspose with
variables matrix[][], rows, and cols.
3. Make a default constructor to
initialize size variables.
4. Initialize the array in the constructor.
5. Create a method getMatrix() to input
values into the matrix.
6. Run nested loops from i=0 to i=rows
and from j=0 to j=cols.
7. Prompt user to enter each element of
the matrix.
8. Create a method transpose() to
perform
transposition.
9. Create a new array for storing
transposed values.
10. Swap indices during assignment:
set transposed[j][i] = matrix[i][j].
11. Display method to show original and
transposed matrices.
12. Create a main method to instantiate
and run methods.
13. End the program.
Q2. A class ArmstrongNumbers has
been defined with the following details:

Data Members/Instance Variables:


- m : To store the starting range
- n : To store the ending range

Member Functions/Methods:
- ArmstrongNumbers(int start, int end) :
Default Constructor
- void findArmstrongNumbers() : To find
and display Armstrong numbers in the
range
- boolean isArmstrong(int number) : To
check if a number is an Armstrong
number

Define the main() function to create an


object and call the functions
accordingly.

A2. import java.util.*;

class ArmstrongNumbers {
// Data Members/Instance Variables
int m; // Starting range
int n; // Ending range
// Default Constructor
ArmstrongNumbers(int start, int end)
{
m = start; // Initialize starting range
n = end; // Initialize ending range
}

// Method to find and display


Armstrong numbers
in the range
void findArmstrongNumbers() {
System.out.println("Armstrong
numbers between " + m + " and " + n +
":");
for (int i = m; i <= n; i++) {
if (isArmstrong(i)) {
System.out.print(i + " "); //
Print Armstrong numbers
}
}
System.out.println(); // New line
after displaying all numbers
}

// Method to check if a number is an


Armstrong number
boolean isArmstrong(int number) {
int originalNumber = number;
int sum = 0;
int digits =
String.valueOf(number).length(); //
Count the number of digits
while (number > 0) {
int digit = number % 10; // Get
the last digit
sum += Math.pow(digit,
digits); // Raise it to the power of the
number of digits and add to sum
number /= 10; // Remove the
last digit
}

return sum == originalNumber; //


Check if sum equals original number
}

// Main method to create an object


and call functions accordingly
public static void main(String args[]) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter the
starting range (m): ");
int m = sc.nextInt(); // Get starting
range
System.out.print("Enter the ending
range (n): ");
int n = sc.nextInt(); // Get ending
range
ArmstrongNumbers ob = new
ArmstrongNumbers(m, n); // Create
object of ArmstrongNumbers class
ob.findArmstrongNumbers(); //
Find and display Armstrong numbers in
the specified range
}
}
ALGORITHM:

1. Start the program.


2. Define a class ArmstrongNumbers
with variables m and n.
3. Make a default constructor to
initialize m and n.
4. Create a method
findArmstrongNumbers() to find and
display Armstrong numbers.
5. Run a loop from m to n inclusive.
6. For each number, call isArmstrong()
method to check if it is an Armstrong
number.
7. Create a method isArmstrong(int
number) to check if a number is an
Armstrong number.
8. Store original value of number for
comparison later.
9. Calculate the sum of each digit
raised to the power of total digits.
10. Return true if sum equals original
number, otherwise return false.
11. In main method, prompt user for
starting and ending ranges.
12. Create an instance of
ArmstrongNumbers class.
13. Call findArmstrongNumbers()
method on the instance.
14. End the program.
Q3. A class DiagonalSum has been
defined with the following details:

Data Members/Instance Variables:


- matrix[][] : To store the matrix
- size : For the size of the matrix
(number of rows and columns)

Member Functions/Methods:
- DiagonalSum(int s) : Default
Constructor
- void getMatrix() : To initialize the
matrix
- void calculateDiagonalSums() : To
calculate and display the sums of both
diagonals
- void display() : To display the diagonal
with the highest sum
Define the main() function to create an
object and call the functions
accordingly.

A3. import java.util.*;

class DiagonalSum {
// Data Members/Instance Variables
int matrix[][];
int size;

// Default Constructor
DiagonalSum(int s) {
size = s; // Initialize size
matrix = new int[size][size]; //
Initialize square matrix
}

// Method to initialize the matrix


void getMatrix() {
System.out.println("Enter elements
of the matrix:");
Scanner sc = new
Scanner(System.in);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print("Element ["
+ i + "][" + j + "]: ");
matrix[i][j] = sc.nextInt(); //
Input values into the matrix
}
}
}

// Method to calculate and display


sums of both diagonals
void calculateDiagonalSums() {
int leftDiagonalSum = 0; // Sum for
left diagonal
int rightDiagonalSum = 0; // Sum
for right diagonal

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


leftDiagonalSum += matrix[i]
[i]; // Sum of left diagonal (top-left to
bottom-right)
rightDiagonalSum += matrix[i]
[size - 1 - i]; // Sum of right diagonal
(top-right to bottom-left)
}
display(leftDiagonalSum,
rightDiagonalSum); // Call display
method with sums
}

// Method to display which diagonal


has the highest sum
void display(int leftDiagonalSum, int
rightDiagonalSum) {
if (leftDiagonalSum >
rightDiagonalSum) {
System.out.println("Left
Diagonal has the highest sum: " +
leftDiagonalSum);
} else if (rightDiagonalSum >
leftDiagonalSum) {
System.out.println("Right
Diagonal has the highest sum: " +
rightDiagonalSum);
} else {
System.out.println("Both
diagonals have equal sums: " +
leftDiagonalSum);
}
}

// Main method to create an object


and call functions accordingly
public static void main(String args[]) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter the size of
the square matrix: ");
int s = sc.nextInt(); // Get size of
the matrix
DiagonalSum ob = new
DiagonalSum(s); // Create object of
DiagonalSum class
ob.getMatrix(); // Initialize the
matrix with user input
ob.calculateDiagonalSums(); //
Calculate and display diagonal sums
}
}

ALGORITHM:

1. Start the program.


2. Define a class DiagonalSum with
variables matrix[][] and size.
3. Make a default constructor to
initialize size and allocate memory for a
square matrix.
4. Create a method getMatrix() to input
values into the matrix.
5. Run nested loops from i=0 to i=size
for rows and columns.
6. Prompt user to enter each element of
the matrix.
7. Create a method
calculateDiagonalSums() to compute
sums of both diagonals.
8. Initialize variables for left and right
diagonal sums.
9. Use a loop to calculate sums:
- For left diagonal, use indices [i][i].
- For right diagonal, use indices [i]
[size - 1 - i].
10. Call display() method with both
diagonal sums as arguments.
11. Create a method display(int
leftDiagonalSum, int rightDiagonalSum)
to compare sums.
12. Print which diagonal has a higher
sum or if they are equal.
13. In main method, prompt user for
size of square matrix.
14. Create an instance of DiagonalSum
class.
15. Call getMatrix() and
calculateDiagonalSums() methods on
the instance.
16. End the program.

Q4. A Smith number is a composite


number, whose sum of the digits is
equal to the sum of its prime factors.
For example:
4, 22, 27, 58, 85, 94, 121 ………. are
Smith numbers.

Write a program in Java to enter a


number and check whether it is a Smith
number or not.
Sample Input: 666
Sum of the digits: 6 + 6 + 6 = 18
Prime factors are: 2, 3, 3, 37
Sum of the digits of the prime factors: 2
+ 3 + 3 + (3 + 7) = 18
Thus, 666 is a Smith Number.

import java.util.Scanner;

public class SmithNumber


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

if (n <= 0) {
System.out.println(n + " is not a
Smith Number.");
return;
}

boolean isComposite = false;


for (int i = 2; i < n; i++) {
if (n % i == 0) {
isComposite = true;
break;
}
}

if (isComposite && n != 1) {
int sumDigits = 0;
int t = n;
while (t != 0) {
int d = t % 10;
sumDigits += d;
t /= 10;
}

int sumPrimeDigits = 0;
t = n;
for(int i = 2; i < t; i++) {
while(t % i == 0) {
t /= i;
int temp = i;
while (temp != 0) {
int d = temp % 10;
sumPrimeDigits += d;
temp /= 10;
}
}
}
if(t > 2) {
while (t != 0) {
int d = t % 10;
sumPrimeDigits += d;
t /= 10;
}
}

if (sumPrimeDigits ==
sumDigits)
System.out.println(n + " is a
Smith Number.");
else
System.out.println(n + " is not
a Smith Number.");
}
else {
System.out.println(n + " is not a
Smith Number.");
}
}
}
Algorithm:
1. Start the program.
2.Import the Scanner class for user
input.
3.Create a main method.
4.Prompt the user to enter a number
and read the input.
5.Check if the number is less than or
equal to zero:
If true, print that it is not a Smith
Number and exit.
6.Initialize a boolean variable
isComposite to false.
6.Use a loop to check if the number is
composite:
Iterate from 2 to n-1.
If n is divisible by any number in this
range, set isComposite to true and
break the loop.
If the number is composite and not
equal to 1:
Initialize sumDigits to zero.
7.Create a temporary variable t and set
it equal to n.
8.Use a loop to calculate the sum of the
digits of n:
While t is not zero, extract the last digit
and add it to sumDigits. Then remove
the last digit from t.
Initialize sumPrimeDigits to zero and
reset t to n.
Use another loop from 2 to t to find
prime factors of n:
While t is divisible by i, divide t by i.
9.For each prime factor, calculate the
sum of its digits:
10.Use a temporary variable to extract
each digit of i and add it to
sumPrimeDigits.
After exiting the loop, check if t is
greater than 2:
If true, calculate the sum of its digits
similarly as done before.
11.Compare sumPrimeDigits with
sumDigits:
If they are equal, print that n is a Smith
Number.
Otherwise, print that it is not a Smith
Number.
If the number was not composite or was
equal to 1, print that it is not a Smith

Number.
12.End the program.

Q5.Class name: Stack


Data members/instance variables:
cha[]: array to hold the characters
size: stores the maximum capacity of
the stack
top: to point the index of the topmost
element of the stack
Member functions/methods:
Stack(int mm): constructor to initialize
the data member size = mm, top = -1
and create the character array
void push_char(char v): to add
characters from the top end if possible
else display the message “Stack full”
char pop_char(): to remove and return
characters from the top end, if any, else
returns ‘$’
void display(): to display elements of
the stack

Specify the class Stack, giving the


details of void push_char(char) and
char pop_char(). Assume that the other
functions have been defined.

A5. import java.util.Scanner;


class Stack{
char cha[];
int size;
int top;
public Stack(int mm){
size = mm;
top = -1;
cha = new char[size];
}
public void push_char(char v){
if(top + 1 == size)
System.out.println("Stack full");
else
cha[++top] = v;
}
public char pop_char(){
if(top == -1)
return '$';
else
return cha[top--];
}
public void display(){
if(top == -1)
System.out.println("Stack
empty");
else{
for(int i = 0; i <= top; i++)
System.out.print(cha[i] + " ");
System.out.println();
}
}
public static void main(String[] args){
Scanner in = new
Scanner(System.in);
System.out.print("Stack size: ");
int s =
Integer.parseInt(in.nextLine());
Stack obj = new Stack(s);
while(true){
System.out.println("1. Push
character");
System.out.println("2. Pop
character");
System.out.println("3. Display
characters");
System.out.println("4. Exit");
System.out.print("Enter your
choice: ");
int choice =
Integer.parseInt(in.nextLine());
switch(choice){
case 1:
System.out.print("Character
to be pushed:
");
char ch =
in.nextLine().charAt(0);
obj.push_char(ch);
break;
case 2:
ch = obj.pop_char();
if(ch == '$')
System.out.println("Stack
empty");
else
System.out.println(ch + "
popped");
break;
case 3:
obj.display();
break;
default:
System.out.println("Bye");
return;
}
}
}
}

Algorithm:
1.Start
2.Initialize Stack:
3.Create the Stack class with the
following
attributes:
char[] cha for storing stack elements.
int size to set the maximum stack size.
int top initialized to -1 to represent an
empty stack.
Constructor:
Set size to mm.
4.Initialize cha with length size.
Push Method (push_char):
5.If top + 1 == size, print "Stack full".
Else, increment top and store v at
cha[top].
Pop Method (pop_char):
6.If top == -1, return '$' (stack is empty).
Else, return cha[top] and decrement
top.
Display Method (display):
7.If top == -1, print "Stack empty".
Else, loop from 0 to top, printing each
element of cha.
Main Program:
8.Prompt user for stack size and
initialize Stack obj.
Enter a loop for the menu:
Push: Prompt for a character and call
push_char.
Pop: Call pop_char. If return value is '$',
print "Stack empty"; otherwise, print the
popped character.
Display: Call display.
9.Exit
Q6. accept sort and search a car
between 10 cars using binary search
technique

A6.import java.util.Arrays;
import java.util.Scanner;

public class CarNumberBinarySearch {


public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
String[] carNumbers = new
String[10];
// Input 10 car numbers
System.out.println("Enter 10 car
numbers:");
for (int i = 0; i < 10; i++) {
System.out.print("Car number "
+ (i + 1) + ": ");
carNumbers[i] =
scanner.nextLine();
}

// Sort the array of car numbers


Arrays.sort(carNumbers);
// Display sorted car numbers
System.out.println("Sorted Car
Numbers:");
for (String carNumber :
carNumbers) {
System.out.println(carNumber);
}

// Input the car number to search


for
System.out.print("Enter a car
number to search: ");
String targetCarNumber =
scanner.nextLine();

// Perform binary search


int index =
binarySearch(carNumbers,
targetCarNumber);

// Display the result


if (index != -1) {
System.out.println("Car number
" + targetCarNumber + " found at index
" + index + ".");
} else {
System.out.println("Car number
" + targetCarNumber + " not found.");
}
}

// Binary search method


public static int binarySearch(String[]
array, String target) {
int left = 0;
int right = array.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Compare the middle element


with the target
int comparison =
array[mid].compareTo(target);
if (comparison == 0) {
return mid; // Target found
} else if (comparison < 0) {
left = mid + 1; // Search in the
right half
} else {
right = mid - 1; // Search in
the left half
}
}
return -1; // Target not found
}
}

Algorithm:
1. Start the Program.
2. Initialize Scanner: Create a Scanner
object for user input.
3. Input Car Numbers:
- Create an array to store 10 car
numbers.
- Prompt the user to enter each car
number and store them in the array.
4. Sort Car Numbers: Use Arrays.sort()
to sort the array of car numbers.
5. Display Sorted Car Numbers: Print
the sorted list of car numbers.
6. Input Target Car Number: Prompt the
user to enter a car number to search
for.
7. Perform Binary Search:
- Define a method
binarySearch(array, target):
- Set left to 0 and right to the last
index of the array.
- While left is less than or equal to
right:
- Calculate mid as the average of
left and right.
- Compare the middle element with
the target:
- If equal, return mid.
- If less, update left to mid + 1.
- If greater, update right to mid - 1.
- If not found, return -1.
8. Display Result:
- If the index is found, print that the
car number was found and its index.
- If not found, print that the car
number was not
found.
9. End the Program.

Q7.Write a Java program that manages


a simple library system. The program
should allow users to add books,
display all books, and search for a book
by its title. Each book should have a
title, an author, and an ISBN number.
A7.import java.util.ArrayList;
import java.util.Scanner;

class Book {
private String title;
private String author;
private String isbn;

// Constructor
public Book(String title, String author,
String isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}

// Getters
public String getTitle() {
return title;
}

public String getAuthor() {


return author;
}

public String getIsbn() {


return isbn;
}

// Method to display book details


public void displayBookDetails() {
System.out.println("Title: " + title +
", Author: " + author + ", ISBN: " + isbn);
}
}

public class LibraryManagementSystem


{
private ArrayList<Book> books; // List
to store books

// Constructor
public LibraryManagementSystem() {
books = new ArrayList<>(); //
Initialize the book list
}

// Method to add a book


public void addBook(String title,
String author, String isbn) {
Book newBook = new Book(title,
author, isbn);
books.add(newBook);
System.out.println("Book added
successfully!");
}

// Method to display all books


public void displayBooks() {
if (books.isEmpty()) {
System.out.println("No books
available in the library.");
return;
}
System.out.println("Books in the
library:");
for (Book book : books) {
book.displayBookDetails();
}
}

// Method to search for a book by title


public void searchBookByTitle(String
title) {
boolean found = false;
for (Book book : books) {
if
(book.getTitle().equalsIgnoreCase(title))
{
System.out.println("Book
found:");
book.displayBookDetails();
found = true;
break;
}
}
if (!found) {
System.out.println("Book not
found.");
}
}

public static void main(String[] args) {


Scanner scanner = new
Scanner(System.in);
LibraryManagementSystem library
= new LibraryManagementSystem();
while (true) {
System.out.println("\nLibrary
Management System");
System.out.println("1. Add
Book");
System.out.println("2. Display
All Books");
System.out.println("3. Search
Book by Title");
System.out.println("4. Exit");
System.out.print("Choose an
option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume
newline

switch (choice) {
case 1:
System.out.print("Enter
book title: ");
String title =
scanner.nextLine();
System.out.print("Enter
book author: ");
String author =
scanner.nextLine();
System.out.print("Enter
book ISBN: ");
String isbn =
scanner.nextLine();
library.addBook(title,
author, isbn);
break;

case 2:
library.displayBooks();
break;
case 3:
System.out.print("Enter the
title of the book to search: ");
String searchTitle =
scanner.nextLine();
library.searchBookByTitle(searchTitle);
break;

case 4:
System.out.println("Exiting
the program.");
scanner.close();
return;

default:
System.out.println("Invalid
choice. Please try again.");
}
}
}
}
1. Start the program.
2. Define a class Book with attributes
for title, author, and ISBN.
3. Create a constructor in the Book
class to initialize
these attributes.
4. Define methods in the Book class to
get attribute values and display book
details.
5. Define a class
LibraryManagementSystem with an
ArrayList to store Book objects.
6. Create a constructor in
LibraryManagementSystem to initialize
the book list.
7. Define a method addBook(title,
author, isbn) to create a Book object
and add it to the list.
8. Define a method displayBooks() to
print all books in the library.
9. Define a method
searchBookByTitle(title) to search for a
book by its title and display its details if
found.
10. In the main method, initialize a
Scanner for user input and create an
instance of LibraryManagementSystem.
11. Use a loop to display a menu with
options: add book, display all books,
search for a book, or exit.
12. Based on user choice, call the
appropriate method:
- If adding a book, prompt for title,
author, and ISBN, then call addBook().
- If displaying books, call
displayBooks().
- If searching for a book, prompt for
the title and call searchBookByTitle().
- If exiting, terminate the program.
13. End the program.

Q8. Write a Java program that uses


recursion to calculate the factorial of a
given positive integer.

A8. import java.util.Scanner;


public class FactorialRecursion {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter a positive
integer: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not
defined for negative numbers.");
} else {
long result = factorial(number);
System.out.println("The factorial of
" + number + " is: " + result);
}
scanner.close();
}
// Recursive method to calculate
factorial
public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of
0 or 1 is 1
} else {
return n * factorial(n - 1); //
Recursive case
}
}

Algorithm:
1.Start the program.
2.Initialize a Scanner object for user
input.
3.Prompt the user to enter a positive
integer.
4.Read the integer input from the user.
5.Check if the number is negative:
6.If negative, print that factorial is not
defined for negative numbers.
7.If the number is non-negative, call the
recursive method factorial() with the
input number.
In the factorial method:
8.If n is 0 or 1, return 1 (base case).
9.Otherwise, return n multiplied by
factorial(n - 1) (recursive case).
10.Print the result of the factorial
calculation.
11.Close the scanner(basically optional)
12.End the program.
Q9.Write a java program to implement
ceaser cipher encryption (ie replacing
each letter of a string with the letter +13
to it for the first 13 letters and -13 for
the next 13 letters) for eg
input:hello world
output:khoor zruog

A9. import java.util.Scanner;

public class CaesarCipher {


public static void main(String args[]) {
Scanner in = new
Scanner(System.in);
// Ask for user input
System.out.println("Enter plain
text:");
String str = in.nextLine();
int len = str.length();
// Check if the length is between 3
and 100
if (len < 3 || len > 100) {
System.out.println("INVALID
LENGTH");
return;
}

// Initialize the result string


String cipher = "";

// Loop through each character in


the input string
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
// If the character is between 'A'
and 'M' or 'a' and 'm', shift by +13
if ((ch >= 'A' && ch <= 'M') || (ch
>= 'a' && ch <= 'm')) {
cipher += (char)(ch + 13); //
Shift forward by 13
}
// If the character is between 'N'
and 'Z' or 'n' and 'z', shift by -13
else if ((ch >= 'N' && ch <= 'Z') ||
(ch >= 'n' && ch <= 'z')) {
cipher += (char)(ch - 13); //
Shift backward by 13
}
// If the character is not a letter,
keep it unchanged
else {
cipher += ch; // Non-
alphabetic characters remain
unchanged
}
}

// Output the ciphered text


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

Algorithm:
start
1. **Input a string** from the user.

2. **Initialize an empty result string** to


store the transformed characters.

3. **Iterate through each character** in


the input string:
- If the character is a letter:
- If the character is uppercase (A-Z),
shift it by 13 positions within the
uppercase letters.
- If the character is lowercase (a-z),
shift it by 13 positions within the
lowercase letters.
- If the character is not a letter (e.g.,
number, punctuation), leave it
unchanged.

4. **Output the transformed string**


after
processing all characters.
end

Q10.Write a Java program that uses


recursion to find the nth Fibonacci
number.

A10.import java.util.Scanner;
public class FibonacciRecursion {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the position of
the Fibonacci number to find (n >= 0):
");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Fibonacci is
not defined for negative numbers.");
} else {
long result = fibonacci(n);
System.out.println("The Fibonacci
number at position " + n + " is: " +
result);
}
scanner.close();
}

// Recursive method to calculate the nth


Fibonacci number
public static long fibonacci(int n) {
if (n == 0) {
return 0; // Base case:
Fibonacci(0) is 0
} else if (n == 1) {
return 1; // Base case:
Fibonacci(1) is 1
} else {
return fibonacci(n - 1) +
fibonacci(n - 2); // Recursive case
}
}}

Algorithm:
1.Start the program.
2.Initialize a Scanner object for user
input.
3.Prompt the user to enter the position
of the Fibonacci number (n).
4.Read the integer input from the user.
5.Check if the number is negative:
6.If negative, print that Fibonacci is not
defined for negative numbers.
7.If the number is non-negative, call the
recursive method fibonacci() with the
input number.
8.In the fibonacci method:
If n is 0, return 0 (base case).
If n is 1, return 1 (base case).
Otherwise, return fibonacci(n - 1) +
fibonacci(n - 2) (recursive case).
9.Print the result of the Fibonacci
calculation.
10.Close the scanner.
11.End the program.

Q11. A class is defined as follows


Class name: Coding
Data members/instance variables:
wrd: stores the word
len: stores the length of the word
Methods/Member functions:
Coding(): constructor to initialize the
data members with legal initial values
void accept(): to accept a word
void find(): to display all the characters
of ‘wrd’ along with their ASCII codes.
Also display the
lowest ASCII code and the highest
ASCII code, in ‘wrd’
void show(): to display the original word
and all the characters of ‘wrd’ along
with their ASCII codes. Also display the
lowest ASCII code and the highest
ASCII code in ‘wrd’, by invoking the
function find()

Specify the class Coding giving details


of the constructor(), void accept(), void
find() and void show(). Define a main()
function to create an object and call all
the functions accordingly to enable the
task

A11.import java.util.Scanner;
class Coding {
String wrd;
int len;
// Constructor
public Coding() {
wrd = "";
len = 0;
}

// Method to accept input


public void accept() {
Scanner in = new
Scanner(System.in);
System.out.print("Enter the word:
");
wrd = in.next();
len = wrd.length();
}

// Method to find the lowest and


highest ASCII values
public void find() {
if (len == 0)
return;

// Initialize low and high with


extreme values
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;

// Loop to find lowest and highest


ASCII values
for (int i = 0; i < len; i++) {
char ch = wrd.charAt(i);
int ascii = (int) ch;

// Update low and high ASCII


values
if (low > ascii)
low = ascii;
if (high < ascii)
high = ascii;
// Optional: Print ASCII values
for each character
System.out.println(ch + " = " +
ascii);
}

// Print the lowest and highest


ASCII values
System.out.println("Lowest ASCII
code: " + low);
System.out.println("Highest ASCII
code: " + high);
}

// Method to display the word and its


ASCII codes
public void show() {
System.out.println("Original word:
" + wrd);
find();
}
// Main method
public static void main(String[] args) {
Coding obj = new Coding();
obj.accept(); // Accept user input
obj.show(); // Display results
}
}
Algorithm:
1.start
2.Initialize wrd to an empty string and
len to zero in the constructor Coding().
3.Accept Word:
4.Call the accept() method
5.Prompt the user to enter a word.
6.Store the input word in wrd.
7.Calculate and store the length of wrd
in len.
8.Find ASCII Codes and Extremes:
9.Call the find() method:
10.If len is zero, return immediately.
11.Initialize low and high with the ASCII
value of the first character in wrd.
12.For each character ch in wrd:
Convert ch to its ASCII value, storing it
in ascii.
13.Compare ascii with low and high,
updating low and high if necessary.
14.Print the character and its ASCII
value.
15.Print the lowest and highest ASCII
codes found.
Display Results:
16.Call the show() method:
17.Print the original word.
18.Call find() to display ASCII values
and the lowest and highest ASCII
codes.
Main Execution:
19.In main(), create an object of the
Coding class.
Call accept() to input the word and
show() to display the results.
20.end

Q12.Write a Java Program to input a


number and print Fibonacci series till
that number.
Input – 33
Output - 0 1 1 2 3 8 13 21
Input – 63
Output - 0 1 1 2 3 8 13 21 34 55

A12.import java.util.*; // Importing util


package

public class Fibonacci { // Class


declaration
int a = 0;
int b = 1;
int n; // Declaration of variables

void generateFibonacci() { // Method


to generate Fibonacci series
Scanner sc = new
Scanner(System.in);
System.out.println("Enter the
number up till you want to print the
Fibonacci series:");
n = sc.nextInt();

// Print the Fibonacci series until


the number exceeds 'n'
System.out.print("Fibonacci series
up to " + n + ": ");
// Handling edge case for n < 0
if (n >= 0) {
System.out.print(a + " "); // Print
the first number
}

if (n >= 1) {
System.out.print(b + " "); // Print
the second number
}

int c;
// Print Fibonacci numbers while
the next number doesn't exceed 'n'
while (true) {
c = a + b; // Next Fibonacci
number
if (c > n) {
break; // Stop if the next
number exceeds 'n'
}
System.out.print(c + " ");
a = b; // Update 'a' to the last 'b'
b = c; // Update 'b' to the new
Fibonacci number
}
System.out.println(); // Move to the
next line after printing the series
}

public static void main(String args[]) {


Fibonacci ob = new Fibonacci();
ob.generateFibonacci(); // Calling
the method to generate the Fibonacci
series
} // End of main method

} // End of class
ALGORITHM
1. Start
2. Import Scanner class from util
package.
3. Declare a class Fibonacci.
4. Create a method to calculate
Fibonacci number
and print it.
5. Declare main method.
6. Create the object for the class.
7. method calling.
8. End of main method.
9. End of class

Q13. Write a Java program that


demonstrates the use of a single-
dimensional array to manage student
grades. The program should allow the
user to input the names and grades of 5
students, calculate the average grade,
and display each student's name along
with their grade and whether they
passed or failed (assuming a passing
grade is 50 or above).
A13.import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
// Array to store student names
and grades for 5 students
String[] studentNames = new
String[5]; // Correct array initialization
int[] studentGrades = new int[5]; //
Correct array initialization
int sum = 0; // Variable to store the
sum of grades

// Input student names and grades


System.out.println("Enter the
names and grades of 5 students:");
for (int i = 0; i < 5; i++) {
System.out.print("Student " + (i
+ 1) + " Name: ");
studentNames[i] =
scanner.nextLine(); // Store each
student's name

System.out.print("Student " + (i
+ 1) + " Grade: ");
while (true) {
// Input validation for grades
int grade = scanner.nextInt();
if (grade >= 0 && grade <=
100) {
studentGrades[i] =
grade; // Store each student's grade
break;
} else {
System.out.print("Invalid
grade. Please
enter a grade between 0 and 100: ");
}
}
scanner.nextLine(); // Consume
the newline character
}

// Calculate the sum of grades and


display each student's information
System.out.println("\nStudent
Grades:");
for (int i = 0; i < 5; i++) {
sum += studentGrades[i]; // Add
each grade to the sum
String status =
(studentGrades[i] >= 50) ? "Passed" :
"Failed"; // Determine pass/fail status
System.out.println("Name: " +
studentNames[i] + ", Grade: " +
studentGrades[i] + ", Status: " + status);
}

// Calculate and display the


average grade
double average = sum / 5.0; //
Calculate average
System.out.println("\nAverage
Grade: " + average);

scanner.close(); // Close the


scanner
}
}

Algorithm:
1.Start the program.
2.Initialize a Scanner object for user
input.
3.Declare a single-dimensional array of
size 5 to store student names.
4.Declare a single-dimensional array of
size 5 to store student grades.
5.Initialize a variable to hold the sum of
grades.
6.Prompt the user to enter the names
and grades of 5 students.
7.Use a loop to read names and grades
from the user:
8.For each iteration, read a student's
name and grade, storing them in their
respective arrays.
9.Consume the newline character after
reading an integer.
10.Initialize a loop to calculate the sum
of grades and display each student's
information:
11.For each index, add the grade to the
sum and determine if the student
passed or failed based on their grade.
12.Print each student's name, grade,
and pass/fail status.
13.Calculate the average grade by
dividing the total
sum by 5.0.
14.Print the average grade.
15.Close the scanner.
16.End the program.

Q14.Write a Java program that


demonstrates the concept of
inheritance using a simple example of a
base class `Vehicle` and a derived
class `Car`. The program should show
how the `Car` class inherits properties
and methods from the `Vehicle` class.

A14.import java.util.*;
class Vehicle {
String brand;
int year;

// Constructor
public Vehicle(String brand, int year)
{
this.brand = brand;
this.year = year;
}

// Method to display vehicle details


public void displayInfo() {
System.out.println("Brand: " +
brand);
System.out.println("Year: " + year);
}
}

class Car extends Vehicle {


String model;

// Constructor
public Car(String brand, int year,
String model) {
super(brand, year); // Call the
constructor of the base class
this.model = model;
}

// Method to display car details


public void displayCarInfo() {
displayInfo(); // Call the displayInfo
method of the base class
System.out.println("Model: " +
model);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Car myCar = new Car("Toyota",
2020, "Camry");
myCar.displayCarInfo(); // Display
car details
}
}

Algorithm:
1. Start the program.
2. Define a base class `Vehicle` with
attributes for brand and year.
3. Create a constructor in the `Vehicle`
class to initialize these attributes.
4. Define a method `displayInfo()` in the
`Vehicle` class to print vehicle details.
5. Define a derived class `Car` that
extends the `Vehicle` class.
6. In the `Car` class, add an attribute for
model.
7. Create a constructor in the `Car`
class that calls the superclass
constructor using `super()`.
8. Define a method `displayCarInfo()` in
the `Car` class to display car details,
including calling the base class method.
9. In the main method, create an
instance of the `Car` class.
10. Call the `displayCarInfo()` method
on the car instance to display its details.
11. End the program.
Q15.Define a class 'Account' with two
extended classes ‘Simple’ & 13
‘Compound’ for calculating interest :-

A15.import java.io.*;
import java.util.*;
class Account
{
protected int accountNumber;
protected double principal;
Account()
{
accountNumber = 0;
principal = 0;
}
Account(int acn,double np)
{
accountNumber=acn;
principal=np;
}
void display()
{
System.out.println("Account Number
: "+accountNumber);
System.out.println("Principal :
"+principal);
}
}
class Simple extends Account
{
protected double time,rate;
Simple()
{
time = 0;
rate = 0;
}
Simple(int acn,double np,double
nt,double nr)
{
super(acn,np);
time = nt;
rate = nr;
}
void display()
{
super.display();
System.out.println("Rate : "+rate);
System.out.println("Time : "+time);
System.out.println("Interest :
"+interest());
}
double interest()
{
return principal*rate*time/100;
}
}
class Compound extends Account
{
protected double time,rate;
Compound()
{
time = 0;
rate = 0;
}
Compound(int acn,double np,double
nt,double nr)
{
super(acn,np);
time = nt;
rate = nr;
}
void display()
{
super.display();
System.out.println("Rate : "+rate);
System.out.println("Time : "+time);
System.out.println("Interest :
"+interest());
}
double interest()
{
return
principal*(Math.pow(1+rate/100,time)-
1);
}
}
class testaccount
{
public static void main(String
args[])throws Exception
{
Scanner sc=new
Scanner(SSytem.in);
Account a=new Account();
System.out.print("Enter Acc# : ");
int acn = sc.nextInt();
System.out.print("Enter principal : ");
double p = sc.nextDouble();
System.out.print("Enter rate : ");
int r = sc.nextInt();
System.out.print("Enter time : ");
int t = sc.nextInt();
System.out.print("Enter type of
account (S/C) : ");
if(sc.nextLine().charAt(0)=='S')
a = new Simple(acn,p,t,r);
else
a = new Compound(acn,p,t,r);
a.display();
}
}

ALGORITHM
Step 1: define class account and a
constructor to initialize principal and
account number by 0.
Step 2: create another parametrized
constructor o initialize data members.
Step 3: in function void display() print
the data members.
Step 4: create another class simple
which extend class account using
extends keyword.
Step 5: create a parameterize
constructor of this class .
Step 6:display in void display().
Step 7:create a function double interest
which calculates interest and returns it.
Step 8:end of class simple.
Step 9: create another class compound
which
inherits class simple.
Step 10: create constructor of the class
compound.
Step 11:display account number time
rate etc. in void display().
Step 12:calculate compound interest in
double compound and return it.
Step 13:end the class compound.
Step 14:create a class Account which
extends compound and call necessary
methods accordingly.
Step 15:end the class

Q16. A class ConsChange has been


defined with the following details:
Class name: ConsChange
Data members / instance variables:
word:
stores the word
len:
stores the length of the word
Member functions / methods:
ConsChange():
default constructor
void readword():
accepts the word in lowercase
void shiftcons():
shifts all the consonants of the word at
the beginning followed by the vowels
(e.g. spoon becomes spnoo)
void changeword():
changes the case of all occurring
consonants of the shifted word to
uppercase, for e.g. (spnoo becomes
SPNoo)
void show(): displays the original word,
shifted word and the changed word
Specify the class ConsChange giving
the details of the constructor ), void
readword ( ), void shiftcons (), void
changeword() and void show(). Define
the main() function to create an object
and call the functions accordingly to
enable the task.

A16.

import java.util.Scanner;
class ConsChange {
String word;
String shiftedWord;
String changedWord;

ConsChange() {
word = "";
shiftedWord = "";
changedWord = "";
}

void readword() {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter a word in
lowercase: ");
word = sc.nextLine();
}

void shiftcons() {
String consonants = "";
String vowels = "";
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
if (isVowel(ch)) {
vowels += ch;
} else {
consonants += ch;
}
}
shiftedWord = consonants +
vowels;
}

boolean isVowel(char ch) {


return (ch == 'a' || ch == 'e' || ch ==
'i' || ch == 'o' ||
ch == 'u');
}

void changeword() {
StringBuilder sb = new
StringBuilder(shiftedWord);
for (int i = 0; i <
shiftedWord.length(); i++) {
char ch = shiftedWord.charAt(i);
if (!isVowel(ch)) {
sb.setCharAt(i,
Character.toUpperCase(ch));
}
}
changedWord = sb.toString();
}

void show() {
System.out.println("Original word:
" + word);
System.out.println("Shifted word: "
+ shiftedWord);
System.out.println("Changed word:
" + changedWord);
}

public static void main(String[] args) {


ConsChange obj = new
ConsChange();
obj.readword();
obj.shiftcons();
obj.changeword();
obj.show();
}
}

ALGORITHM
STEP 1: Start of the program
STEP 2: Initialize an instance of the
ConsChange class.
STEP 3: Call the readword() method:
STEP 4 :Prompt the user to enter a
word in lowercase.
STEP 5: Store the input in the word
variable.
STEP 6: Call the shiftcons() method:
STEP 7: Initialize an empty string
consonants.
STEP 8: Initialize an empty string
vowels.
STEP 9: For each character ch in word,
do the following:
If ch is a vowel, append it to
vowels but if ch is a consonant,
append it to consonants.
STEP 10: Combine consonants and
vowels and
store the result in shiftedWord.
STEP 11: Call the changeword()
method:
STEP 12: Initialize a String sb with the
value of shiftedWord.
STEP 13: For each character ch in
shiftedWord:
STEP 14: If ch is a consonant, change
it to uppercase in sb.
STEP 15: Store the modified value of
sb in changedWord.
STEP 16: Call the show() method:
STEP 17: Display word, shiftedWord,
and changedWord.

STEP 18: End of the program


Q17. Data Members/Instance
Variables:
• email: A String to store the email ID.
• check: A boolean flag to indicate
whether the email ID is valid or not.
Member Functions/Methods:
1. EmailID(String id): A constructor that
initializes the email ID with the given
string.
2. boolean present(): A method to
check if the
email ID contains exactly one '@'
character and a '.' character after the
'@'.
3. boolean left2(): A method to check if
there are at least two characters before
the '@' character.
4. void decide(): A method that sets the
check flag to true if the email ID passes
both the present() and left2() checks;
otherwise, sets it to false.
5. void display(): A method to display
"Correct" if the email ID is valid (check
is true), otherwise display "False".
Define the main() method:

A17.
import java.util.*;
class EmailID {
String email;
boolean check;
EmailID(String id) {
email = id;
}
boolean present() {
int a = email.indexOf('@');
int b = email.lastIndexOf('@');
int c = email.indexOf('.');
if (a != -1 && c != -1 && a == b &&
a < c)
return true;
return false;
}
boolean left2() {
int a = email.indexOf('@');
return a >= 2;
}
void decide() {
if (present()) {
if (left2()) {
check = true;
} else {
check = false;
}
} else {
check = false;
}
}
void display() {
if (check)
System.out.println("Correct");
else
System.out.println("False");
}
public static void main(String args[]) {
Scanner sc = new
Scanner(System.in);
System.out.println("Enter Email
I.D.");
String a = sc.nextLine();
EmailID ob = new EmailID(a);
ob.decide();
ob.display();
sc.close();
}
}

ALGORITHM:
Step 1: Start the code.
Step 2: Accept the email ID from the
user and store it in the variable email.
Step 3: Initialize the EmailID object with
the email ID.
Step 4: Define Method present()
Step 5: Find the index of the '@'
character in the string and store it in a
Step 6: Find the last index of the '@'
character in the string and store it in b.
Step 7: Find the index of the '.'
character in the string and store it in c.
Step 8: Check if the '@' character is
present (a != -1), there is only one '@'
character (a == b) and the '.' character
is present after the '@' character (a <
c).
Step 9: If all conditions are true, return
true; otherwise, return false.
Step 10: Define Method left2()
Step 11: Find the index of the '@'
character and store it in a.
Step 12: Check if there are at least two
characters before the '@' character (a
>= 2).
Step 13: Return true if the condition is
met; otherwise, return false.
Step 14: Define Method decide()
Step 15: If the present() method
returns true, call the left2() method.If
left2() returns true, set check to
true.Otherwise, set check to false. If
present() returns false, set check to
false.
Step 16: Define Method display()
Step 17: If check is true, display
"Correct". Otherwise, display "False".
Step 18: Create main method
Step 19: Create an EmailID object
using the input email ID.
Step 20: Call decide() method to
determine if the email ID is valid and
display() method to display the result.
Step 21: End the code.

Q18.Data Members/Instance Variables:


• num: An integer to store the input
number.
• bin: An integer to store the binary
equivalent of the input number.
Member Functions/Methods:
1. Evil(): A constructor that initializes
num and bin to 0.
2. void acceptnum(): A method to
accept a number from the user.
3. void toBin(): A method to convert the
decimal number (num) into its binary
equivalent and store it in bin.
4. void check(): A method that checks
whether the number is an Evil Number
(i.e., the number of 1s in the binary
representation is even).
5. void main(String args[]): The main
method to create an object of the Evil
class, accept a number, convert it to
binary, and check if it's an Evil Number.

A18.import java.util.*;
class Evil
{
int num;
int bin;
Evil()
{
num=0;
bin=0;
}
void acceptnum()
{
Scanner sc= new
Scanner(System.in);
System.out.println("Enter a
number");
num= sc.nextInt();
}
void toBin()
{
int m= num, p=0;
while(m!=0)
{
int r= m%2;
bin= bin + r* (int)Math.pow(10, p+
+);
m=m/2;
}
}
void check()
{
toBin();
int b= bin, c=0;
while(b!=0)
{
if(b%10==1)
c++;
b=b/10;
}
if(c%2==0)
System.out.println("number is
evil");
else
System.out.println("number is not
evil");
}
public static void main(String args[])
{
Evil ob= new Evil();
ob.acceptnum();
ob.toBin();
ob.check();
}
}

ALGORITHM
Step 1: Start the code
Step 2: Initialize the variables by setting
num = 0 and bin = 0 in the constructor.
Step 3: Define Method acceptnum()
Step 4: Store the number in num
Step 5: Define Method toBin()
Step 6: Initialize m = num and p = 0
Step 7: While m is not zero, compute
the remainder r = m % 2.
Step 8: Update bin = bin + r * 10^p.
Step 9: Increment p by 1
Step 10: Divide m by 2
Step 11: Define Method check()
Step 12: Call toBin() to convert the
number to binary.
Step 13: Initialize b = bin and c = 0.
Step 14: While b is not zero, if the last
digit of b is 1 (b % 10 == 1)
Step 15: Increment c by 1
Step 16: Divide b by 10.
Step 17: • If c (the number of 1s) is
even, print "number is evil” else, print
"number is not evil".
Step 18: Create a main() Method
Step 19: Create an Evil object ob
Step 20: Call acceptnum() to input the
number.
Step 21: Call toBin() to convert the
number to binary.
Step 22: Call check() to determine if the
number is an Evil Number and display
the result.
Step 23: End of the code.
Q19.A Piglatin word is formed by
arranging the word from the first vowel
followed by the letters left in beginning
and then adding ‘AY’ at the end.
Write a program to enter a word and
perform the following process on it.
Class: Piglatin
Data Members:
String a- Stores the word
int l- Stores the length of a
Member methods:
void input()-Input the word
void Frequency(w1,w2)-prints the
frequency of vowels present in the
word.
void compute()- prints the piglatin form
of the word.
Create the main method and call the
above methods

INPUT: SCHOOL
OUTPUT: The Frequency of vowel is 2.
The Piglatin form is OOLSCHAY
A19.import java.util.*;//importing util
package
class Piglatin//class declation
{
String a;//to store word
int l;//to store length
void input()//enter word by the user
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the word");
a=sc.nextLine();
l=a.length();
}
void Frequency()//prints The Frequency
of Vowels
{
String v="aeiouAEIOU";
int c=0;
for(int i=0;i<a.length();i++)
{
if(v.indexOf(a.charAt(i))>-1)
c++;
}
System.out.println("The Frequency of
Vowels is "+c);
}
void compute()//prints the piglatin form
of words

{
String v="aeiouAEIOU";
int p=-1;
for(int i=0;i<a.length();i++)
{
char ch=a.charAt(i);
if(v.indexOf(ch)>0)
{
p=i;
break;
}
}
System.out.print("The Piglatin form is
");
if(p!=-1)
System.out.println(a.substring(p)
+a.substring(0,p)+"AY");
}
public static void main()//main method
declaration
{
Piglatin obj=new Piglatin();
obj.input();
obj.Frequency();
obj.compute();
}//end of main
}//end of class

ALGORITHM
1. Start
2. Import Scanner class from util
package.
3. Declare the class Hamming.
4. Declare data member a and l.
5. Create void input() method
6. Create object of Scanner class and
input the words from user and store
their lengths.
7. Declare themethod Frequency() that
prints the frequency of vowels present
in a.
8. Create a method compute().
9. Create a String that contain all the
vowels.
10. Extract each characters and store
the index of 1st vowel present in p.
11. Print the Piglatin form of the word.
12. Declare main method and create
object and call the above methods.
13. End of main method
14. End of class

Q20. 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.
import java.util.*;
public class Rearrange
{
String wrd, newwrd;
static Scanner x=new
Scanner(System.in);
Rearrange(){}
void readword()
{
System.out.println("Enter a word" );
wrd=x.next();
wrd=wrd.toUpperCase();
}
void freq_vow_con()
{
int s=0,s1=0;
char ch;
for(int i=0;i<wrd.length();i++)
{
ch=wrd.charAt(i);
if("AEIOU".indexOf(ch)!=-1)
s++;
}
s1= wrd.length()-s;
System.out.println("vowels = "+ s);
System.out.println("consonants = " +
s1);
}
void arrange()
{
char ch;
String p="",q="";
for(int i=0;i<wrd.length();i++)
{
ch=wrd.charAt(i);
if("AEIOU".indexOf(ch)!=-1)
p +=ch;
else
q +=ch;
}
newwrd= p+q;
}
void display()
{ System.out.println("Original word = "+
wrd);
System.out.println("Rearranged word =
"+ newwrd);
}
static void main()
{ Rearrange obj=new Rearrange();
obj.readword();
obj.freq_vow_con();
obj.arrange();
obj.display();
}
ALGORITHM :
1.Start
2 Count Vowels and Consonants:
3 Iterate through each character of the
word.
4 Check if the character is a vowel
using a set of vowels or a vowel string.
5 Increment counters for vowels and
consonants.
6. Separate Vowels and Consonants:
7.Create two empty strings to store
vowels and consonants.
8. Iterate through each character of the
word again:
9. If the character is a vowel, append it
to the vowel string.
10. If the character is a consonant,
append it to the consonant string.
11. Combine the Strings:
12. Concatenate the vowel string and
the consonant string to form the
rearranged word.
13.End

Q21.A class InsSort has been defined


with the following details:
Data Members/Instance Variable:
arr[] : To
store an array
size : For
the size of the array
Member Fuctions/Methods:
InsSort(int s) :
Default Constructor
void getArray() : To
initialise the array
void insertionSort() : to
carry out insertion sort
double find() : to
find the average of the odd numbers in
the sorted array
void display() : to
display the number
Define the main() functions to create an
object and call the functions
accordingly.
import java.util.*;

A21.class InsSort {
int arr[], size;
Scanner sc = new
Scanner(System.in);
InsSort(int s) {
size = s;
arr = new int[size];
}
void getArray() {
for (int i = 0; i < size; i++) {
System.out.print("Enter Value:
");
arr[i] = sc.nextInt();
}
}
void insertionSort() {
for (int i = 1; i < size; i++) {
int m = arr[i], j = i - 1;
while (j >= 0 && m > arr[j]) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = m;
}
}
double find() {
double avg, sum = 0;
int c = 0;
for (int i = 0; i < size; i++) {
if (arr[i] % 2 != 0) {
sum += arr[i];
c++;
}
}
avg= sum/c;
return avg;
}
void display() {
insertionSort();
System.out.println("Sorted Array
(Descending Order):");
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Average of odd
numbers = " + find());
}
public static void main(String args[]) {
Scanner sc = new
Scanner(System.in);
System.out.println("Enter size: ");
int s = sc.nextInt();
InsSort ob = new InsSort(s);
ob.getArray();
ob.display();
}
}

ALGORITHM:
STEP 1: Start the program.
STEP 2: Define a class InsSort with
variable ‘arr[]’ and ‘size’ and a Scanner
STEP 3: Make a default constructor.
STEP 4: Initialise the array
STEP 5: Make a method ‘getArray()’
STEP 6: Run a loop from i=0 to i= size
STEP 7: Enter the size of the array
STEP 8: Create a method
‘insertionSort()’
STEP 9: Store arr[i] in m and set j to i -
1.
STEP 10: While j is greater than or
equal to 0 and arr[j] is less than m then
shift arr[j] to arr[j + 1] and decrement j.
STEP 11: Create a method ‘double
find()’
STEP 12: Run a loop from i=0 to i=
size.
STEP 13: Check if the value at position
‘i’ is odd
STEP 14: Add the value to sum
STEP 15: Repeat the steps 12 to 14 till
the i=0
STEP 16: Take out the average of the
odd numbers
STEP 17: return the average of the odd
numbers
STEP 18: Create a method ‘void
display()’
STEP 19: Call insertionSort() and print
the average of the odd numbers
STEP 20: Create a main method to call
accept and display.
STEP 21: End the program.
Q22. 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’. A
Goldbach number is a positive even
integer that can be expressed as the
sum of two odd primes. For example,
for N = 10, the pairs are (3, 7) and (5,
5).

A22.import java.util.Scanner;
public class GoldbachNumbers {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter an even
integer N (10 < N < 50): ");
int N = scanner.nextInt();

if (N <= 9 || N >= 50 || N % 2 != 0) {
System.out.println("Please enter
a valid even integer greater than 9 and
less than 50.");
return;
}

// Find the maximum number of


odd primes less than N
int maxPrimes = (N / 2); // Rough
estimate for the maximum number of
odd primes
int[] primes = new int[maxPrimes];
int primeCount =
generateOddPrimes(primes,
N);

findGoldbachPairs(N, primes,
primeCount);
}

private static int


generateOddPrimes(int[] primes, int
limit) {
int count = 0;
for (int num = 3; num < limit; num
+= 2) {
if (isPrime(num)) {
primes[count] = num;
count++;
}
}
return count; // Return the number
of primes found
}

private static boolean isPrime(int


num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num);
i++) {
if (num % i == 0) return false;
}
return true;
}

private static void


findGoldbachPairs(int N, int[]
primes, int primeCount) {
System.out.println("Goldbach pairs
for " + N + ":");
for (int i = 0; i < primeCount; i++) {
for (int j = i; j < primeCount; j++)
{
int sum = primes[i] +
primes[j];
if (sum == N) {
System.out.println(primes[i]
+ " + " + primes[j]);
}
}
}
}
}

Algorithm:
1. Start.
2. Prompt the user to enter an even
integer N where N > 9 and N < 50.
3. Check if the input is valid (even and
within the specified range). If not,
display an error message and
terminate.
4. Create an integer array `primes` with
a size that can hold potential odd
primes less than N.
5. Call `generateOddPrimes` to fill the
`primes` array with odd primes less
than N.
a. Initialize a counter for the number
of found primes.
b. Loop through all odd numbers from
3 to N-1.
c. For each number, check if it is
prime using a helper function.
d. If it is prime, store it in the `primes`
array and increment the counter.
6. Call `findGoldbachPairs` to find pairs
of odd primes that sum up to N.
a. Use nested loops to iterate through
the `primes` array.
b. Calculate the sum of each pair of
primes.
c. If the sum equals N, print the pair.
7. End.

Q23.Write a program to declare a


square matrix a[][] of order (m × m)
where
‘m’ is the number of rows and the
number of columns such that ‘m’ must
be greater than 2 and less than 20.
Allow the user to input integers into this
matrix. Display appropriate error
message for an invalid input
Perform the following tasks:
(a) Display the input matrix.
(b) Create a mirror image of the
inputted matrix.
(c) Display the mirror image matrix.

A23.import java.util.*; //importing


java.util package
class MirrorMat //Declaring class
{
public static void main(String args[])
//Start of psvm
{ Scanner sc=new
Scanner(System.in); //Creating an
object sc
System.out.print("m = ");
int m = sc.nextInt();
if(m < 3 || m > 19) //To terminate
program if value is invalid
{System.out.println("SIZE OUT OF
RANGE");
return; }
int i ,j, a[][] = new int[m][m];
System.out.println("Enter matrix
elements:"); //To input matrix elements
for(i=0;i<m;i++){
for(j=0;j<m;j++){
a[i][j]=sc.nextInt(); }
System.out.println("ORIGINAL
MATRIX");
for(i = 0; i< m; i++) { //Loop to print
for(j = 0; j < m; j++){
System.out.print(a[i][j] + "\t"); }
System.out.println(); }
System.out.println("MIRROR IMAGE
MATRIX");
for(i = 0; i< m; i++) { //Loop to print
mirror matrix
for(j = m-1; j >=0; j--) {
System.out.print(a[i][j]+"\t"); }
System.out.println(); }
}}

ALGORITHM
1. Start
2. Import java.util package
3. Declare class MirrorMat
4. Declare public static void main
5. Make object sc of the Scanner class
6. Input int m from the user
7. Terminate program if m less than 3 or
m greater than 19
8. Declare int i,j and a double
dimension array a of size m*m
9. Input matrix elements from the user
10. Print original matrix
11. Print mirror matrix
12.End public static void main
13.End class
14.Stop
Q24.Class : Ducknum
Data Members / Instance Variables :
num : to store an integer
Member functions / Methods :
Ducknum(int nx) : parameterized
constructor to initialize num
int countzero(int n) : to count nad return
the number of zeros using recursive
technique
void checkDuck() : checks whether the
given number is a duck number of not.
Write the main method

A24.import java.util.*;
class Ducknum
{
int num;
Ducknum(int nx)
{
num = nx;
}
int countzero(int n)
{
if(n==0)
return 1;
else if (n<10)
return 0;
else if (n%10==0)
return 1 + countzero(n/10);
else
return countzero(n/10);
}
void checkDuck()
{
System.out.println("Number of zeros
are : " +countzero(num));
if (countzero(num)>0)
System.out.println("Duck Number");
else
System.out.println("Not a Duck
Number");
}
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = sc.nextInt();
System.out.println();
Ducknum ob = new Ducknum(num);
ob.checkDuck();
}
ALGORITHM :
Step 1 : Start
Step 2 : Define a recursive function that
takes an integer n as input.
Step 3 : Base case : If n is 0, return
false, as duck numbers cannot start
with 0.
Step 4 : Recursively call the function
with n/10.
Step 5 : Inside the recursion, if the last
digit of n is 0, return true, as it indicates
a
duck number.
Step 6 : If the last digit is not 0, return
the result of the recursive call.
Step 7 : Implement a main function to
input a number and call the function to
check
if it's a duck number or not.
Step 8: End the program
Q25. Write a Java program that takes
two binary numbers as input and
calculates their sum, displaying the
result in binary format.

A20.import java.util.Scanner;

public class BinarySum {


public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter the first
binary number: ");
String binary1 =
scanner.nextLine();
System.out.print("Enter the second
binary number: ");
String binary2 =
scanner.nextLine();
// Convert binary strings to
integers
int num1 =
Integer.parseInt(binary1, 2);
int num2 =
Integer.parseInt(binary2, 2);
// Calculate the sum
int sum = num1 + num2;
// Convert the sum back to binary
String binarySum =
Integer.toBinaryString(sum);
// Display the result
System.out.println("Sum of " +
binary1 + " and " + binary2 + " is: " +
binarySum);
scanner.close(); // Close the
scanner
}
}

Algorithm:
1. Start the program.
2. Initialize a Scanner object for user
input.
3. Prompt the user to enter the first
binary number.
4. Read the first binary number as a
string.
5. Prompt the user to enter the second
binary number.
6. Read the second binary number as a
string.
7. Convert both binary strings to
integers using `Integer.parseInt()` with
base 2.
8. Calculate the sum of the two integer
values.
9. Convert the sum back to a binary
string using `Integer.toBinaryString()`.
10. Display the result showing the
original binary numbers and their sum
in binary format.
11. Close the scanner.
12. End the program.

You might also like