You are on page 1of 56

COMPUTER PRACTICAL

Name :

Class : 12

Section: A
Roll number :
Java Programs
1. Addition of two binary numbers

Question:

Write a Java program to add two binary numbers.

Working Algorithm:

1. Take input for two binary numbers.


2. Initialize carry as 0.
3. Traverse both binary numbers starting from the least significant bit.
4. For each bit, calculate the sum of bits of both binary numbers and the carry.
5. If the sum is 2 or 3, set carry as 1, else 0.
6. If the sum is 1 or 3, set the current bit in the result as 1, else 0.
7. Repeat the process for all bits.
8. If there's a carry at the end, add it to the result.
9. Return the resultant binary number.

Java Code:

import java.util.Scanner;

public class BinaryAddition {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter first binary number:");
String binary1 = scanner.nextLine();
System.out.println("Enter second binary number:");
String binary2 = scanner.nextLine();
scanner.close();

String result = addBinary(binary1, binary2);


System.out.println("Sum of two binary numbers: " + result);
}

public static String addBinary(String a, String b) {


StringBuilder result = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;

while (i >= 0 || j >= 0) {


int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
result.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) result.append(carry);
return result.reverse().toString();
}
}

Sample Input Output:

Enter first binary number:


1010
Enter second binary number:
1101
Sum of two binary numbers: 10111

2. Finding out the longest word of a sentence recursively

Question:

Write a Java program to find out the longest word in a sentence using recursion.

Working Algorithm:

1. Input a sentence from the user.


2. Split the sentence into words.
3. Initialize two indices, left and right, to point to the first and last word respectively.
4. Compare the lengths of the words pointed by the left and right indices.
5. If the left word is longer, increment the left index.
If the right word is longer, decrement the right index.
6. If the left and right indices are the same, return the word at that index as the
longest word.
Otherwise, recursively call the method with the updated left and right indices.
7. The returned word is the longest word in the sentence.

Java Code:

import java.util.Scanner;

public class LongestWordFinder

{ public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
scanner.close();

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


String longestWord = findLongestWord(words, 0, words.length - 1);
System.out.println("The longest word is: " + longestWord);
}

public static String findLongestWord(String[] words, int left, int right)


{ if (left == right) return words[left];
if (words[left].length() >= words[right].length()) {
return findLongestWord(words, left + 1, right);
} else {
return findLongestWord(words, left, right - 1);
}
}
}

Sample Input Output:

Enter a sentence:
Java is an object oriented programming language
The longest word is: programming
3. Printing lucky numbers in a given range

Question:

Write a Java program to print all the lucky numbers in a given range.

Working Algorithm:

1. A lucky number is defined by the following process:


Start with a list of integers beginning with 1:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
Every second number (all even numbers) is eliminated, leaving only the odd integers:
1, 3, 5, 7, 9, 11, ...
The first number remaining in the list after 1 is 3, so every third number is eliminated. The
first of these is 5:
1, 3, 7, 9, ...
The next surviving number is now 7, so every seventh number is eliminated.
Continue removing the nth remaining numbers, where n is the next number in the list
after the last surviving number.
Remaining numbers are called lucky numbers.
2. Input the range for which lucky numbers are to be found.
3. For each number in the range, check if it's a lucky number using the above process.
4. Print all the lucky numbers within the range.

Java Code:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LuckyNumbers {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the range (n) to find lucky numbers till n:");
int n = scanner.nextInt();
scanner.close();

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


{ if (isLucky(i)) {
System.out.print(i + " ");
}
}
}

public static boolean isLucky(int n)


{ List<Integer> numbers = new
ArrayList<>(); for (int i = 1; i <= n; i++) {
numbers.add(i);
}
int index = 1;
while (index < numbers.size())
{ int step =
numbers.get(index);
if (step > numbers.size() - index)
{ break;
}
int count = 0;
for (int i = index; i < numbers.size(); i += step - count)
{ numbers.remove(i - count);
count++;
}
index++;
}
return numbers.contains(n);
}
}

Sample Input Output:

Enter the range (n) to find lucky numbers till n:


100
Lucky numbers: 1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99

4. Computation of saddle point on matrix

Question:

Write a Java program to compute the saddle point of a matrix. A saddle point is an element
which is
smallest in its row and largest in its column.
Working Algorithm:

1. Input the matrix from the user.


2. For each row, find the minimum element and its column index.
3. Check if this element is the maximum in its column.
4. If both conditions are satisfied, then the element is a saddle point.
5. Print all the saddle points of the matrix.

Java Code:

import java.util.Scanner;

public class SaddlePoint {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the number of rows of the matrix:");
int rows = scanner.nextInt();
System.out.println("Enter the number of columns of the matrix:");
int cols = scanner.nextInt();

int[][] matrix = new int[rows][cols];


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

findSaddlePoint(matrix);
}

public static void findSaddlePoint(int[][] matrix)


{ for (int i = 0; i < matrix.length; i++) {
int minRow = matrix[i][0];
int colIdx = 0;
for (int j = 1; j < matrix[i].length; j++)
{ if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
colIdx = j;
}
}
boolean isSaddle = true;
for (int k = 0; k < matrix.length; k++)
{ if (matrix[k][colIdx] > minRow) {
isSaddle = false;
break;
}
}
if (isSaddle) {
System.out.println("Saddle point found: " + minRow);
}
}
}
}

Sample Input Output:

Enter the number of rows of the matrix:


3
Enter the number of columns of the matrix:
3
Enter the elements of the matrix:
123
456
789
Saddle point found: 7

5. Checking the validity of input date

Question:

Write a Java program to check if an input date is valid.

Working Algorithm:

1. Input day, month, and year from the user.


2. Check if the year is a leap year or not.
3. For each month, validate the day based on the number of days in the month and leap
year conditions.
4. If all conditions are satisfied, the date is valid. Otherwise, it's invalid.

Java Code:

import java.util.Scanner;

public class DateValidation {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month:");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
scanner.close();

if (isValidDate(day, month, year))


{ System.out.println("The date is valid.");
} else {
System.out.println("The date is invalid.");
}
}

public static boolean isLeapYear(int year) {


return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}

public static boolean isValidDate(int day, int month, int year)


{ if (month < 1 || month > 12) return false;
if (day < 1 || day > 31) return false;

if (month == 2) {
return isLeapYear(year) ? day <= 29 : day <= 28;
}
if (month == 4 || month == 6 || month == 9 || month == 11)
{ return day <= 30;
}
return true;
}
}

Sample Input Output:

Enter day:
29
Enter month:
2
Enter year:
2001
The date is invalid.

6. Sorting words of a sentence recursively

Question:

Write a Java program to sort the words of a sentence in ascending order using recursion.

Working Algorithm:

1. Input a sentence from the user.


2. Split the sentence into words.
3. Sort the words using a recursive approach similar to merge sort.
4. Display the sorted words.

Java Code:

import java.util.Scanner;

public class RecursiveWordSort {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
scanner.close();

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


sortWords(words, 0, words.length - 1);
System.out.println("Sorted sentence:");
for (String word : words) {
System.out.print(word + " ");
}
}

public static void sortWords(String[] words, int left, int right)


{ if (left < right) {
int mid = (left + right) / 2;
sortWords(words, left, mid);
sortWords(words, mid + 1, right);
merge(words, left, mid, right);
}
}

public static void merge(String[] words, int left, int mid, int right)
{ int n1 = mid - left + 1;
int n2 = right - mid;
String[] L = new
String[n1];
String[] R = new String[n2];
for (int i = 0; i < n1; i++) {
L[i] = words[left + i];
}
for (int j = 0; j < n2; j++)
{ R[j] = words[mid + 1 +
j];
}

int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i].compareTo(R[j]) <= 0) {
words[k] = L[i];
i++;
} else {
words[k] = R[j];
j++;
} k+
+;
}
while (i < n1)
{ words[k] = L[i];
i++;
k++;
}
while (j < n2)
{ words[k] =
R[j]; j++;
k++;
}
}
}

Sample Input Output:

Enter a sentence:
this is a sample sentence
Sorted sentence:
a is sample sentence this

7. Computation of HCF and LCM of two numbers using recursion

Question:

Write a Java program to compute the HCF (Highest Common Factor) and LCM (Least
Common Multiple)
of two numbers using recursion.

Working Algorithm:

1. Input two numbers from the user.


2. Calculate HCF using the recursive approach.
3. Calculate LCM using the formula: LCM(a, b) = (a * b) / HCF(a, b).
4. Display the HCF and LCM.

Java Code:

import java.util.Scanner;

public class HCFandLCM {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the first number:");
int num1 = scanner.nextInt();
System.out.println("Enter the second
number:"); int num2 = scanner.nextInt();
scanner.close();

int hcf = findHCF(num1, num2);


int lcm = (num1 * num2) / hcf;

System.out.println("HCF: " + hcf);


System.out.println("LCM: " + lcm);
}

public static int findHCF(int a, int b)


{ if (b == 0) {
return a;
}
return findHCF(b, a % b);
}
}

Sample Input Output:

Enter the first number:


12
Enter the second number:
15
HCF: 3
LCM: 60

8. Find the day of the week corresponding to a given date

Question:

Write a Java program to find the day of the week corresponding to a given date.

Working Algorithm:

1. Input day, month, and year from the user.


2. Use Zeller's Congruence formula to compute the day of the week.
3. Display the corresponding day of the week.

Java Code:

import java.util.Scanner;

public class DayOfWeekFinder {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month (1 for January, 12 for December):");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
scanner.close();

String dayOfWeek = findDayOfWeek(day, month, year);


System.out.println("The day of the week is: " + dayOfWeek);
}

public static String findDayOfWeek(int day, int month, int year) {


if (month < 3) {
month += 12;
year -= 1;
}
int q = day;
int m = month;
int K = year % 100;
int J = year / 100;
int f = q + ((13 * (m + 1)) / 5) + K + (K / 4) + (J / 4) - (2 * J);
int dayOfWeek = f % 7;

switch (dayOfWeek) {
case 0:
return "Saturday";
case 1:
return "Sunday";
case 2:
return "Monday";
case 3:
return "Tuesday";
case 4:
return "Wednesday";
case 5:
return "Thursday";
case 6:
return "Friday";
default:
return "Invalid";
}
}
}

Sample Input Output:

Enter day:
15
Enter month (1 for January, 12 for December):
8
Enter year:
2023
The day of the week is: Sunday

9. Find the date after a certain number of days

Question:

Write a Java program to compute the date after adding a certain number of days to a given
date.

Working Algorithm:

1. Input day, month, and year of the initial date from the user.
2. Input the number of days to be added.
3. Iteratively add days, updating month and year as required.
4. Display the resulting date.
Java Code:

import java.util.Scanner;

public class DateAfterDays {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter day:");
int day = scanner.nextInt();
System.out.println("Enter month (1 for January, 12 for December):");
int month = scanner.nextInt();
System.out.println("Enter year:");
int year = scanner.nextInt();
System.out.println("Enter the number of days to add:");
int daysToAdd = scanner.nextInt();
scanner.close();

int[] result = findDateAfterDays(day, month, year, daysToAdd);


System.out.println("The date after adding the days is: " + result[0] + "/" + result[1] +
"/"
+ result[2]);
}

public static int[] findDateAfterDays(int day, int month, int year, int daysToAdd)
{ int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year))
{ daysInMonth[2] =
29;
}

day += daysToAdd;
while (day > daysInMonth[month]) {
day -= daysInMonth[month];
month++;
if (month > 12) {
month = 1;
year++;
if (isLeapYear(year))
{ daysInMonth[2] = 29;
} else {
daysInMonth[2] = 28;
}
}
}
return new int[]{day, month, year};
}

public static boolean isLeapYear(int year) {


return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}
}

Sample Input Output:

Enter day:
25
Enter month (1 for January, 12 for December):
8
Enter year:
2023
Enter the number of days to add:
40
The date after adding the days is: 4/10/2023

10. Boundary sorting of an array

Question:

Write a Java program to sort the boundary elements of a 2D array.

Working Algorithm:

1. Input a 2D array from the user.


2. Extract the boundary elements from the 2D array.
3. Sort the boundary elements.
4. Place the sorted boundary elements back to their boundary positions in the 2D array.
5. Display the resultant 2D array.

Java Code:

import java.util.Scanner;
import java.util.Arrays;
public class BoundarySort {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the number of rows:");
int rows = scanner.nextInt();
System.out.println("Enter the number of columns:");
int cols = scanner.nextInt();

int[][] matrix = new int[rows][cols];


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

sortBoundary(matrix);
System.out.println("Matrix after boundary sorting:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{ System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

public static void sortBoundary(int[][] matrix)


{ int rows = matrix.length;
int cols = matrix[0].length;
int n = 2 * (rows + cols) - 4; // Number of boundary elements
int[] boundary = new int[n];
int idx = 0;

// Extract boundary elements


for (int j = 0; j < cols; j++) {
boundary[idx++] = matrix[0][j];
}
for (int i = 1; i < rows; i++) { boundary[idx+
+] = matrix[i][cols - 1];
}
for (int j = cols - 2; j >= 0; j--) {
boundary[idx++] = matrix[rows - 1][j];
}
for (int i = rows - 2; i > 0; i--)
{ boundary[idx++] = matrix[i][0];
}

// Sort boundary elements


Arrays.sort(boundary);

// Place the sorted elements back


idx = 0;
for (int j = 0; j < cols; j++)
{ matrix[0][j] = boundary[idx++];
}
for (int i = 1; i < rows; i++) { matrix[i]
[cols - 1] = boundary[idx++];
}
for (int j = cols - 2; j >= 0; j--)
{ matrix[rows - 1][j] = boundary[idx++];
}
for (int i = rows - 2; i > 0; i--)
{ matrix[i][0] = boundary[idx++];
}
}
}

Sample Input Output:

Enter the number of rows:


3
Enter the number of columns:
4
Enter the elements of the matrix:
1234
5678
9 10 11 12
Matrix after boundary sorting:
1234
12 6 7 5
11 10 9 8
11. Stack implementation using array

Question:

Write a Java program to implement a stack using an array.

Working Algorithm:

1. Define a class Stack with attributes:


- An integer array to store elements.
- An integer top to keep track of the topmost element.
2. Implement the following methods:
- push: To add an element to the top of the stack.
- pop: To remove and return the topmost element of the stack.
- peek: To return the topmost element without removing it.
- isEmpty: To check if the stack is empty.
- isFull: To check if the stack is full.
3. Demonstrate the stack operations in the main method.

Java Code:

public class StackImplementation

{ static class Stack {


int MAX;
int[] arr;
int top;

Stack(int size) {
MAX = size;
arr = new int[MAX];
top = -1;
}

boolean isFull() {
return top == MAX - 1;
}

boolean isEmpty() {
return top == -1;
}
void push(int x) {
if (isFull()) {
System.out.println("Stack Overflow");
return;
}
arr[++top] = x;
System.out.println(x + " pushed to stack");
}

int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top--];
}

int peek() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top];
}
}

public static void main(String[] args) {


Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Top element: " + stack.peek());
System.out.println(stack.pop() + " popped from stack");
System.out.println("Top element: " + stack.peek());
}
}

Sample Input Output:

1 pushed to stack
2 pushed to stack
3 pushed to stack
Top element: 3
3 popped from stack
Top element: 2

12. Queue implementation using array

Question:

Write a Java program to implement a queue using an array.

Working Algorithm:

1. Define a class Queue with attributes:


- An integer array to store elements.
- Two integers: front and rear, to keep track of the first and last elements of the queue.
2. Implement the following methods:
- enqueue: To add an element to the end of the queue.
- dequeue: To remove and return the first element of the queue.
- peek: To return the first element without removing it.
- isEmpty: To check if the queue is empty.
- isFull: To check if the queue is full.
3. Demonstrate the queue operations in the main method.

Java Code:

public class QueueImplementation {

static class Queue {


int MAX;
int[] arr;
int front, rear, size;

Queue(int size) {
MAX = size;
arr = new int[MAX];
front = 0;
rear = -1;
size = 0;
}
boolean isFull()
{ return size ==
MAX;
}

boolean isEmpty() {
return size == 0;
}

void enqueue(int x) {
if (isFull()) {
System.out.println("Queue Overflow");
return;
}
rear = (rear + 1) % MAX;
arr[rear] = x;
size++;
System.out.println(x + " enqueued to queue");
}

int dequeue() {
if (isEmpty()) {
System.out.println("Queue Underflow");
return -1;
}
int item = arr[front];
front = (front + 1) % MAX;
size--;
return item;
}

int peek() {
if (isEmpty()) {
System.out.println("Queue Underflow");
return -1;
}
return arr[front];
}
}

public static void main(String[] args)


{ Queue queue = new Queue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
System.out.println("Front element: " + queue.peek());
System.out.println(queue.dequeue() + " dequeued from queue");
System.out.println("Front element: " + queue.peek());
}
}

Sample Input Output:

10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
Front element: 10
10 dequeued from queue
Front element: 20

13. Computation of factorial of a large number

Question:

Write a Java program to compute the factorial of a large number.

Working Algorithm:

1. Input a number from the user.


2. Use the BigInteger class from the Java standard library to calculate the factorial as it
can handle very large numbers.
3. Display the factorial of the number.

Java Code:

import java.util.Scanner;
import java.math.BigInteger;

public class LargeFactorial {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the number:");
int num = scanner.nextInt();
scanner.close();

BigInteger factorial = findFactorial(num);


System.out.println("Factorial of " + num + " is: " + factorial);
}

public static BigInteger findFactorial(int num)


{ BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= num; i++) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}

Sample Input Output:

Enter the number:


25
Factorial of 25 is: 15511210043330985984000000

13. Implementation of a linked list in Java

Question:

Write a Java program to implement a singly linked list. The program should have operations
for inserting at the beginning, inserting at the end, deleting from the beginning, deleting
from the end, and displaying the list.

Working Algorithm:

1. Implement a Node class to represent each element in the linked list.


2. Implement a LinkedList class to handle linked list operations.
3. Provide methods for inserting at the beginning, inserting at the end, deleting from
the beginning, deleting from the end, and displaying the list.
4. In the main method, provide a menu-driven program to test the linked list operations.
Java Code:

class Node
{ int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

class LinkedList {
Node head;

public void insertAtBeginning(int data) {


Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}

public void insertAtEnd(int data)


{ Node newNode = new
Node(data); if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

public void deleteFromBeginning() {


if (head != null) {
head = head.next;
} else {
System.out.println("List is empty.");
}
}

public void deleteFromEnd() {


if (head == null)
{ System.out.println("List is empty.");
} else if (head.next == null) {
head = null;
} else {
Node temp = head;
while (temp.next.next != null)
{ temp = temp.next;
}
temp.next = null;
}
}

public void display()


{ Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}
}

public class LinkedListImplementation


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

int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Insert at beginning");
System.out.println("2. Insert at end");
System.out.println("3. Delete from beginning");
System.out.println("4. Delete from end");
System.out.println("5. Display");
System.out.println("6. Exit");
System.out.println("Enter your choice:");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value to insert:");
int value1 = scanner.nextInt();
list.insertAtBeginning(value1);
break;
case 2:
System.out.println("Enter value to insert:");
int value2 = scanner.nextInt();
list.insertAtEnd(value2);
break;
case 3:
list.deleteFromBeginning();
break;
case 4:
list.deleteFromEnd();
break;
case 5:
list.display();
break;
case 6:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 6);

scanner.close();
}
}

Sample Input Output:

Menu:
1. Insert at beginning
2. Insert at end
3. Delete from beginning
4. Delete from end
5. Display
6. Exit
Enter your choice:
1
Enter value to insert:
10
Menu:
...
1. Insert at beginning
...
5. Display
6. Exit
Enter your choice:
5
10 -> null
...
6. Exit
Enter your choice:
6
Exiting...

14. Swapping two numbers without using a third variable

Question:

Write a Java program to swap the values of two numbers without using a third variable.

Working Algorithm:

1. Input two numbers from the user.


2. Use arithmetic operations to swap the values without using a third variable.
3. Display the swapped values.

Java Code:

import java.util.Scanner;

public class SwapWithoutThirdVariable


{ public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number:");
int a = scanner.nextInt();
System.out.println("Enter the second
number:"); int b = scanner.nextInt();
scanner.close();

a = a + b;
b = a - b;
a = a - b;

System.out.println("After swapping:");
System.out.println("First number: " + a);
System.out.println("Second number: " + b);
}
}

Sample Input Output:

Enter the first number:


5
Enter the second number:
10
After swapping:
First number: 10
Second number: 5

14. Generation of Pascal triangle pattern

Question:

Write a Java program to generate the Pascal triangle pattern for a given number of rows.

Working Algorithm:

1. Input the number of rows for the Pascal triangle.


2. Loop through each row.
3. For each row, compute the coefficients using the formula:

1. Input the number of rows for the Pascal triangle.


2. Loop through each row.
3. For each row, compute the coefficients using the
formula: C(n, k) = n! / (k! * (n-k)!)
where n is the row number and k is the position in that row.
4. Print the coefficients to form the Pascal triangle.
15. Circular queue implementation

Question:

Write a Java program to implement a circular queue using an array. The program should
have operations for enqueuing, dequeuing, and displaying the elements of the queue.

Working Algorithm:

1. Create a class "CircularQueue" with methods for enqueue, dequeue, and


display operations.
2. In the main method, display a menu for the user to choose the desired operation.
3. Perform the chosen operation and continue until the user decides to exit.

Java Code:

import java.util.Scanner;

class CircularQueue {
private int[] queue;
private int front;
private int rear;
private int size;

public CircularQueue(int size) {


this.size = size;
queue = new int[size];
front = -1;
rear = -1;
}

public void enqueue(int value) {


if ((front == 0 && rear == size - 1) || (rear == (front - 1) % (size - 1)))
{ System.out.println("Queue is full. Can't enqueue.");
return;
}
if (front == -1) {
front = 0;
rear = 0;
} else if (rear == size - 1 && front != 0) {
rear = 0;
} else {
rear++;
}
queue[rear] = value;
System.out.println("Enqueued " + value + " to the queue.");
}

public void dequeue() {


if (front == -1) {
System.out.println("Queue is empty. Can't dequeue.");
return;
}
System.out.println("Dequeued " + queue[front] + " from the queue.");
if (front == rear) {
front = -1;
rear = -1;
} else if (front == size - 1) {
front = 0;
} else {
front++;
}
}

public void display() {


if (front == -1) {
System.out.println("Queue is empty.");
return;
}
System.out.print("Queue elements: ");
if (rear >= front) {
for (int i = front; i <= rear; i++)
{ System.out.print(queue[i] + " ");
}
} else {
for (int i = front; i < size; i++)
{ System.out.print(queue[i] + "
");
}
for (int i = 0; i <= rear; i++)
{ System.out.print(queue[i] + "
");
}
}
System.out.println();
}
}

public class CircularQueueImplementation {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter the size of the queue:");
int size = scanner.nextInt();
CircularQueue queue = new CircularQueue(size);

while (true) {
System.out.println("\nEnter an option:\n1. Enqueue\n2. Dequeue\n3. Display\n4.
Exit");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("Enter the value to enqueue:");
int value = scanner.nextInt();
queue.enqueue(value);
break;
case 2:
queue.dequeue();
break;
case 3:
queue.display();
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid option! Try again.");
}
}
}
}

Sample Input Output:

Enter the size of the queue:


4
Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
1
Enter the value to enqueue:
5
Enqueued 5 to the queue.
Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
3
Queue elements: 5
Enter an option:
1. Enqueue
2. Dequeue
3. Display
4. Exit
4
Exiting...

16. Magic square

Question:

Write a Java program to generate a magic square for an odd-sized matrix. A magic square is
a matrix in which the sums of the numbers in each row, each column, and both main
diagonals are the same.

Working Algorithm:

1. Input the size (odd value) of the matrix.


2. Initialize the magic square with all zeros.
3. Start filling the magic square from the middle column of the topmost row with
the number 1.
4. For each subsequent number, move up and to the right (diagonally).
5. If the current row becomes -1, set it to the last row. If the current column becomes
the size of the matrix, set it to the first column.
6. If the cell is already filled, move one step down.
7. Repeat until the matrix is filled.
8. Display the magic square.

Java Code:

import java.util.Scanner;

public class MagicSquare {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the size of the magic square (odd number only):");
int n = scanner.nextInt();
scanner.close();

if (n % 2 == 0) {
System.out.println("Size should be an odd number.");
return;
}

int[][] magicSquare = generateMagicSquare(n);

System.out.println("Magic Square:");
for (int i = 0; i < n; i++)
{ for (int j = 0; j < n; j++)
{
System.out.print(magicSquare[i][j] + "\t");
}
System.out.println();
}
}

public static int[][] generateMagicSquare(int n) { int[]


[] magicSquare = new int[n][n];
int i = 0;
int j = n / 2;
int num = 1;

while (num <= n * n)


{ magicSquare[i][j] =
num; num++;
int nextRow = (i - 1 + n) % n;
int nextCol = (j + 1) % n;

if (magicSquare[nextRow][nextCol] == 0) {
i = nextRow;
j = nextCol;
} else {
i = (i + 1) % n;
}
}
return magicSquare;
}
}

Sample Input Output:

Enter the size of the magic square (odd number only):


3
Magic Square:
2 7 6
9 5 1
4 3 8

17. Conversion of decimal number to any given base

Question:

Write a Java program to convert a decimal number to its representation in a given base
(between 2 and 16).

Working Algorithm:

1. Input a decimal number and the desired base for conversion.


2. Create a character array to store the characters for bases greater than 10.
3. Repeatedly divide the number by the base and store the remainder in a stack.
4. Convert the remainder to the appropriate character if the base is greater than 10.
5. Pop the values from the stack and append them to the result string.
6. Display the converted number.
Java Code:

import java.util.Scanner;
import java.util.Stack;

public class DecimalToBase {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the decimal number:");
int decimalNumber = scanner.nextInt();
System.out.println("Enter the base (between 2 and 16):");
int base = scanner.nextInt();
scanner.close();

if (base < 2 || base > 16) {


System.out.println("Invalid base. Enter a base between 2 and 16.");
return;
}

String convertedNumber = convertToBase(decimalNumber, base);

System.out.println("Number " + decimalNumber + " in base " + base + " is: " +
convertedNumber);
}

public static String convertToBase(int number, int base)


{ Stack<Character> stack = new Stack<>();
char[] baseChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

while (number > 0) {


int remainder = number % base;
stack.push(baseChars[remainder]);
number /= base;
}

StringBuilder result = new StringBuilder();


while (!stack.isEmpty()) {
result.append(stack.pop());
}

return result.toString();
}
}

Sample Input Output:

Enter the decimal number:


255
Enter the base (between 2 and 16):
16
Number 255 in base 16 is: FF

18. Distance between two points in X-Y plane (passing of objects)

Question:

Write a Java program to calculate the distance between two points in the X-Y plane. The
program should use objects to represent points and pass them to a method to compute the
distance.

Working Algorithm:

1. Create a class "Point" with attributes for X and Y coordinates.


2. In the main method, take inputs for the coordinates of two points.
3. Create two Point objects using the input coordinates.
4. Pass the Point objects to a method that calculates the distance using the formula:
\( ext{distance} = \sqrt{(x2 - x1)^2 + (y2 - y1)^2} \)
5. Display the calculated distance.

Java Code:

import java.util.Scanner;

class Point {
double x, y;

public Point(double x, double y) {


this.x = x;
this.y = y;
}
}
public class DistanceBetweenPoints {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the coordinates for Point 1 (x y):");
double x1 = scanner.nextDouble();
double y1 = scanner.nextDouble();
System.out.println("Enter the coordinates for Point 2 (x y):");
double x2 = scanner.nextDouble();
double y2 = scanner.nextDouble();
scanner.close();

Point point1 = new Point(x1, y1);


Point point2 = new Point(x2, y2);

double distance = calculateDistance(point1, point2);

System.out.println("Distance between the two points is: " + distance);


}

public static double calculateDistance(Point p1, Point p2) {


return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
}

Sample Input Output:

Enter the coordinates for Point 1 (x y):


11
Enter the coordinates for Point 2 (x y):
45
Distance between the two points is: 5.0

18. Distance between two points in X-Y plane (passing of objects)

Question:

Write a Java program to compute the distance between two points in the X-Y plane. Define a
class "Point" with members x and y. Pass objects of the Point class to a function to compute
the distance.

Working Algorithm:

1. Define a class "Point" with instance variables x and y.


2. Define a constructor to initialize x and y.
3. Define a method "distance" that takes another Point object as a parameter and
computes the distance between the two points using the formula:
\( ext{distance} = \sqrt{(x2 - x1)^2 + (y2 - y1)^2} \)
4. In the main method, take input for the coordinates of the two points.
5. Create two Point objects and compute the distance between them using the
"distance" method.
6. Display the result.

Java Code:

import java.util.Scanner;

class Point {
double x, y;

Point(double x, double y) {
this.x = x;
this.y = y;
}

double distance(Point p) {
return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2));
}
}

public class DistanceBetweenPoints {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the coordinates of the first point (x1 y1):");
double x1 = scanner.nextDouble();
double y1 = scanner.nextDouble();

System.out.println("Enter the coordinates of the second point (x2 y2):");


double x2 = scanner.nextDouble();
double y2 = scanner.nextDouble();
scanner.close();

Point p1 = new Point(x1, y1);


Point p2 = new Point(x2, y2);

double distance = p1.distance(p2);

System.out.println("Distance between the two points is: " + distance);


}
}

Sample Input Output:

Enter the coordinates of the first point (x1 y1):


12
Enter the coordinates of the second point (x2 y2):
46
Distance between the two points is: 5.0

19. Text file creation

Question:

Write a Java program to create a text file and write user-input content to it.

Working Algorithm:

1. Import necessary classes for file handling.


2. Prompt the user for the filename and content to be written.
3. Create a FileWriter object using the provided filename.
4. Write the user-input content to the file.
5. Close the file writer.
6. Display a message indicating that the file has been created successfully.

Java Code:

import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;

public class TextFileCreation {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the filename (with .txt extension):");
String filename = scanner.nextLine();
System.out.println("Enter the content to write to the file:");
String content = scanner.nextLine();
scanner.close();

try {
FileWriter fileWriter = new FileWriter(filename);
fileWriter.write(content);
fileWriter.close();
System.out.println("File " + filename + " has been created successfully!");
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
}

Sample Input Output:

Enter the filename (with .txt extension):


sample.txt
Enter the content to write to the file:
This is a sample content for the text file.
File sample.txt has been created successfully!

19. Text file creation

Question:

Write a Java program to create a text file and write user input to that file until the user
enters "exit".
Working Algorithm:

1. Use the FileWriter and BufferedWriter classes to create and write to a text file.
2. Take input from the user using the Scanner class.
3. Write each line of input to the file until the user enters "exit".
4. Close the BufferedWriter and FileWriter objects.
5. Display a message indicating that the file has been created successfully.

Java Code:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class TextFileCreation {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter the name of the file (e.g., 'output.txt'):");
String fileName = scanner.nextLine();

try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)))


{ System.out.println("Enter text (type 'exit' to stop):");
while (true) {
String line = scanner.nextLine();
if ("exit".equalsIgnoreCase(line)) {
break;
}
writer.write(line);
writer.newLine();
}
System.out.println("File " + fileName + " created successfully!");
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
}
scanner.close();
}
}
Sample Input Output:

Enter the name of the file (e.g., 'output.txt'):


sample.txt
Enter text (type 'exit' to stop):
Hello, this is a sample text.
Writing to a file in Java.
exit
File sample.txt created successfully!

20. Bank account balance calculation using inheritance

Question:

Write a Java program that simulates a bank system. Create a base class "Account" and derive
two subclasses "SavingsAccount" and "CurrentAccount" from it. Implement methods to
deposit, withdraw, and display balance in each account type.

Working Algorithm:

1. Create a class "Account" with attributes for account number and balance.
2. Implement methods for depositing, withdrawing, and displaying the balance.
3. Derive "SavingsAccount" and "CurrentAccount" subclasses from "Account".
4. In the main method, create objects of both account types and perform operations
on them.

Java Code:

class Account {
String accountNumber;
double balance;

public Account(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited " + amount + ". New balance: " + balance);
}

public void withdraw(double amount)


{ if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew " + amount + ". New balance: " + balance);
} else {
System.out.println("Insufficient balance!");
}
}

public void displayBalance()


{ System.out.println("Account balance: " + balance);
}
}

class SavingsAccount extends Account {


public SavingsAccount(String accountNumber, double balance) {
super(accountNumber, balance);
}
}

class CurrentAccount extends Account {


public CurrentAccount(String accountNumber, double balance) {
super(accountNumber, balance);
}
}

public class BankAccountDemo {

public static void main(String[] args) {


SavingsAccount savings = new SavingsAccount("SA1234", 5000.00);
CurrentAccount current = new CurrentAccount("CA5678", 10000.00);

System.out.println("Operations on Savings Account:");


savings.deposit(2000);
savings.withdraw(1500);
savings.displayBalance();

System.out.println("\nOperations on Current Account:");


current.deposit(3000);
current.withdraw(4000);
current.displayBalance();
}
}

Sample Input Output:

Operations on Savings Account:


Deposited 2000.0. New balance: 7000.0
Withdrew 1500.0. New balance: 5500.0
Account balance: 5500.0

Operations on Current Account:


Deposited 3000.0. New balance: 13000.0
Withdrew 4000.0. New balance: 9000.0
Account balance: 9000.0

21. Pendulum arrangement of numbers

Question:

Write a Java program to arrange a given array of numbers in a pendulum fashion. The
smallest element should be in the center, the next larger to its left, the next larger to its
right, and so on.

Working Algorithm:

1. Sort the given array of numbers.


2. Initialize two pointers: one starting from the middle of the array (for the
smallest element) and the other from the end of the array (for the largest element).
3. Iterate through the sorted array and arrange the numbers in the pendulum fashion
using the two pointers.
4. Display the pendulum arrangement.
Java Code:

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

public class PendulumArrangement

{ public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();

int[] pendulumArr = getPendulumArrangement(arr);

System.out.println("Pendulum arrangement:");
for (int num : pendulumArr)
{ System.out.print(num + " ");
}
}

public static int[] getPendulumArrangement(int[] arr)


{ Arrays.sort(arr);
int n = arr.length;
int[] result = new int[n];
int mid = (n - 1) / 2;
int left = mid;
int right = mid + 1;

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


{ if (i % 2 == 0) {
result[left--] = arr[i];
} else {
result[right++] = arr[i];
}
}
return result;
}
}

Sample Input Output:

Enter the number of elements:


5
Enter the elements:
52813
Pendulum arrangement:
85123

22. Permutation of characters of string

Question:

Write a Java program to generate all possible permutations of a given string.

Working Algorithm:

1. Define a method to recursively generate permutations of the string.


2. If the string has only one character, return that character.
3. For each character in the string:
a. Fix that character and find permutations of the remaining characters.
b. Concatenate the fixed character with the permutations of the remaining characters.
4. Display the generated permutations.

Java Code:

import java.util.Scanner;

public class StringPermutations {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter a string:");
String str = scanner.nextLine();
scanner.close();

generatePermutations(str, "");
}

public static void generatePermutations(String str, String prefix)


{ if (str.length() == 0) {
System.out.println(prefix);
} else {
for (int i = 0; i < str.length(); i++) {
String rem = str.substring(0, i) + str.substring(i + 1);
generatePermutations(rem, prefix + str.charAt(i));
}
}
}
}

Sample Input Output:

Enter a string:
abc
Permutations:
abc
acb
bac
bca
cab
cba

23. Binary tree traversal

Question:

Write a Java program to demonstrate the in-order, pre-order, and post-order traversal of a
binary tree.

Working Algorithm:

1. Define a class "Node" with attributes for the value and left and right child nodes.
2. Define methods for in-order, pre-order, and post-order traversal.
3. In the main method, create a sample binary tree and call the traversal methods to
display the results.
Java Code:

class Node
{ int value;
Node left, right;

public Node(int item) {


value = item;
left = right = null;
}
}

public class BinaryTreeTraversal {

Node root;

void inorder(Node node) {


if (node == null) {
return;
}
inorder(node.left);
System.out.print(node.value + " ");
inorder(node.right);
}

void preorder(Node node) {


if (node == null) {
return;
}
System.out.print(node.value + " ");
preorder(node.left);
preorder(node.right);
}

void postorder(Node node) {


if (node == null) {
return;
}
postorder(node.left);
postorder(node.right);
System.out.print(node.value + " ");
}
public static void main(String[] args)
{ BinaryTreeTraversal tree = new
BinaryTreeTraversal(); tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);

System.out.println("Inorder traversal:");
tree.inorder(tree.root);

System.out.println("\nPreorder traversal:");
tree.preorder(tree.root);

System.out.println("\nPostorder traversal:");
tree.postorder(tree.root);
}
}

Sample Input Output:

Inorder traversal:
42513
Preorder traversal:
12453
Postorder traversal:
45231

24. Palindrome string check

Question:

Write a Java program to check whether a given string is a palindrome or not. A palindrome
is a word, phrase, number, or other sequences of characters that reads the same forward
and backward (ignoring spaces, punctuation, and capitalization).
Working Algorithm:

1. Input a string.
2. Convert the string to lowercase and remove non-alphanumeric characters.
3. Compare the modified string with its reverse.
4. If they are the same, the string is a palindrome.
5. Display whether the string is a palindrome or not.

Java Code:

import java.util.Scanner;

public class PalindromeStringCheck

{ public static void main(String[] args)

{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String str = scanner.nextLine();
scanner.close();

if (isPalindrome(str)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}

public static boolean isPalindrome(String str) {


String cleanedString = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
String reversedString = new StringBuilder(cleanedString).reverse().toString();
return cleanedString.equals(reversedString);
}
}

Sample Input Output:

Enter a string:
A man, a plan, a canal, Panama!
The string is a palindrome.
25. Finding Armstrong numbers

Question:

Write a Java program to check whether a given number is an Armstrong number. An


Armstrong number (or narcissistic number) is a number that is equal to the sum of its own
digits raised to the power of the number of digits.

Working Algorithm:

1. Convert the number to a string to get the number of digits (n).


2. For each digit in the number, compute the nth power of the digit and sum them up.
3. If the computed sum is equal to the original number, then it is an Armstrong number.
4. Display whether the number is an Armstrong number or not.

Java Code:

import java.util.Scanner;

public class ArmstrongNumber {

public static void main(String[] args)


{ Scanner scanner = new
Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
scanner.close();

if (isArmstrong(num)) {
System.out.println(num + " is an Armstrong number.");
} else {
System.out.println(num + " is not an Armstrong number.");
}
}

public static boolean isArmstrong(int num) {


int originalNum = num;
int sum = 0;
int n = String.valueOf(num).length();

while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, n);
num /= 10;
}

return originalNum == sum;


}
}

Sample Input Output:

Enter a number:
153
153 is an Armstrong number.

26. Finding factorial using recursion

Question:

Write a Java program to compute the factorial of a number using recursion.

Working Algorithm:

1. Define a recursive function to compute factorial.


2. If the number is 0 or 1, return 1.
3. Otherwise, return the number multiplied by the factorial of the number minus one.
4. In the main method, take input for the number and call the factorial function.
5. Display the computed factorial.

Java Code:

import java.util.Scanner;

public class FactorialUsingRecursion

{ public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
scanner.close();
long factorial = computeFactorial(num);

System.out.println("Factorial of " + num + " is: " + factorial);


}

public static long computeFactorial(int num) {


if (num == 0 || num == 1) {
return 1;
}
return num * computeFactorial(num - 1);
}
}

Sample Input Output:

Enter a number:
5
Factorial of 5 is: 120

27. Finding common elements in three sorted arrays

Question:

Write a Java program to find common elements in three sorted arrays.

Working Algorithm:

1. Use three pointers, one for each array.


2. If the elements pointed by the three pointers are the same, print the element and move
all pointers to the next position.
3. If the first element is smaller, move the pointer for the first array.
4. If the second element is smaller, move the pointer for the second array.
5. If the third element is smaller, move the pointer for the third array.
6. Repeat until any of the arrays is completely traversed.

Java Code:

public class CommonElementsInArrays {


public static void main(String[] args)
{ int[] arr1 = {1, 5, 10, 20, 40, 80};
int[] arr2 = {6, 7, 20, 80, 100};
int[] arr3 = {3, 4, 15, 20, 30, 70, 80, 120};

System.out.println("Common elements are:");


findCommon(arr1, arr2, arr3);
}

public static void findCommon(int[] arr1, int[] arr2, int[] arr3)


{ int i = 0, j = 0, k = 0;

while (i < arr1.length && j < arr2.length && k < arr3.length)


{ if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
System.out.print(arr1[i] + " ");
i++;
j++;
k++;
} else if (arr1[i] < arr2[j]) {
i++;
} else if (arr2[j] < arr3[k]) {
j++;
} else {
k++;
}
}
}
}

Sample Input Output:

Common elements are:


20 80

You might also like