Com Piter
Com Piter
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
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
// Default Constructor
MatrixTranspose(int r, int c) {
rows = r;
cols = c;
matrix = new int[rows][cols];
}
ALGORITHM:
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
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
}
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.
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
}
ALGORITHM:
import java.util.Scanner;
if (n <= 0) {
System.out.println(n + " is not a
Smith Number.");
return;
}
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.
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;
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.
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;
}
// Constructor
public LibraryManagementSystem() {
books = new ArrayList<>(); //
Initialize the book list
}
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.
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
Algorithm:
start
1. **Input a string** from the user.
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();
}
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.
A11.import java.util.Scanner;
class Coding {
String wrd;
int len;
// Constructor
public Coding() {
wrd = "";
len = 0;
}
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
}
} // 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
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
}
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.
A14.import java.util.*;
class Vehicle {
String brand;
int year;
// Constructor
public Vehicle(String brand, int year)
{
this.brand = brand;
this.year = year;
}
// Constructor
public Car(String brand, int year,
String model) {
super(brand, year); // Call the
constructor of the base class
this.model = model;
}
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
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;
}
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);
}
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.
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.
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
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;
}
findGoldbachPairs(N, primes,
primeCount);
}
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.
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;
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.