Professional Documents
Culture Documents
Dsa 1
Dsa 1
Practical Journal
on
IT11L- Data Structure and
Algorithms (SEM-I)
Submitted By:
Seat No - 6812
Roll No- 26
Date : 15/12/2023
Course Outcomes:
Solution: Program
class Node
{
constructor(data){
this.data = data;
this.next = null;
}}
class LinkedListCreation {
constructor() {
this.head = null;
}
create(data) {
var nn = new Node(data);
if (this.head == null) {
this.head = nn; }
else{
let cur = this .head;
while(cur.next != null) {
cur = cur.next; }
cur.next = nn;
}}
insertAtFirst(data)
{
let nnF = new Node(data);
nnF.next = this.head;
this.head = nnF;
}
insertAtLast(data) {
let nnL = new Node(data);
let cur = this.head;
while(cur.next != null) {
cur = cur.next; }
cur.next = nnL;
}
insertAtPos(data,pos) {
let nnp = new Node(data);
let temp = this.head;
for (let i = 1; i < pos-1 && temp.next != null;i++) {
temp = temp.next; }
nnp.next = temp.next;
temp.next = nnp;
}
DeleteFromFirst() {
if(this.head.next==null) {
this.head = null; }
else{
this.head = this.head.next;
}}
DeleteFromPos(pos)
{
let p = this.head;
for(let i = 1; i<pos && p != null; i++)
{
var q = p;
p=p.next;
}
q.next = p.next;
}
DeleteFromLast()
{
let cur = this.head;
while(cur.next != null)
{
var p = cur;
cur=cur.next;
}
p.next = null;
DisplayList()
{
let cur = this .head;
while(cur!= null)
{
console.log(cur.data);
cur = cur.next;
}
}
Output:
Screen Shot
Creating linked list, Inserting element at first , last and Position and Display.
After inserrtion and deleting element from first, last, and Position.-
Q2. Write a program to implement Doubly linked list with required member function(Create, insert, delete,
Display )
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.prev = null;
}}
class DoublyLinkedList {
constructor()
{
this.head = null;
this.tail = null;
}
create(data) {
const newNode = new Node(data);
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.prev = this.tail;
this.tail.next = newNode;
this.tail = newNode;
}}
InsertAtFirst(data) {
nf.next = this.head;
if (this.head) {
this.head.prev = nf;
}
this.head = nf;
}
InsertAtLast(data) {
let nl = new Node(data)
this.tail.next = nl;
Data Structure and Algorithms
nl.prev = this.tail;
this.tail = nl;
}
InsertAtPos(pos, data) {
const newNode = new Node(data);
if (pos === 0) {
newNode.next = this.head;
if (this.head) {
this.head.prev = newNode;
}
this.head = newNode;
} else {
let current = this.head;
let count = 0;
if (!current) {
return;
}
newNode.next = current.next;
newNode.prev = current;
if (current.next) {
current.next.prev = newNode;
}
current.next = newNode;
}
}
DeleteFromFrist() {
if (this.head) {
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
}
}
}
DeleteFromLast() {
if (this.tail) {
this.tail = this.tail.prev;
Data Structure and Algorithms
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
}
}
DeleteFromPos(pos) {
let current = this.head;
let count = 1;
if (!current) {
console.log("Position not found");
return;
}
if (current.prev) {
current.prev.next =
current.next;
} else {
this.head = current.next;
}
if (current.next) {
current.next.prev = current.prev;
} else {
this.tail = current.prev;
}
}
Display() {
let current = this.head;
while (current != null) {
console.log(current.data);
current = current.next;
}}}
const list = new DoublyLinkedList();
list.create(41);
list.create(42);
list.create(43);
list.create(44);
list.create(45);
console.log("Elements in list are:");
list.Display();
console.log("The element after inserted new element at
first:");
list.InsertAtFirst(40);
list.Display();
console.log("The element after inserted new element at last:");
list.InsertAtLast(46);
Data Structure and Algorithms
list.Display();
console.log("The element after inserted new element at given
position:");
list.InsertAtPos(2, 55);
list.Display();
console.log("The element after deleted element from first:");
list.DeleteFromFrist();
list.Display();
console.log("The element after deleted element from last:");
list.DeleteFromLast();
list.Display();
console.log("The element after deleted element from given
position:");
list.DeleteFromPos(2);
list.Display();
Output -
Screenshot-
Q3. Write a program to implement STACK using Array with PUSH, POP operations
Program-
class STKA{
constructor(sz)
{
this.data=[];
this.top=-1;
this.size=sz;
}
push(val)
{
if(this.top==this.size-1)
{
console.log("Stack is full");
}
else{
this.top++;
this.data[this.top]=val;
return
}
}
pop()
{
if(this.top==-1)
{
console.log("Stack is empty");
}
else{
let t = this.data[this.top];
this.top--;
console.log(t);
}
}
display()
{
for(let i = this.top; i>=0; i--)
{
console.log(this.data[i]+" ");
}
}
}
var mystka = new STKA(5);
mystka.push(10);
mystka.push(20);
mystka.push(30);
mystka.push(40);
mystka.push(50);
console.log(".....................");
mystka.display();
console.log(".....................");
console.log("Popped element is :");
mystka.pop();
console.log(".....................");
mystka.display();
Output-
Screenshot-
Q4. Write a program to implement Stack using Linked List.
Program
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Stackk {
constructor() {
this.top = null;
push(data) {
const newNode = new Node(data);
newNode.next = this.top;
this.top = newNode;
pop() {
if(this.top == null)
{
console.log("Stack is empty");
}
else{
console.log("popped element is:",this.top.data);
this.top = this.top.next;
}
}
display() {
if(this.top == null)
{
console.log("Stack is empty !");
}
else{
let current = this.top;
while (current !== null) {
console.log(current.data);
current = current.next;
}
}
}
}
const stk = new Stackk();
stk.push(1000);
stk.push(2000);
stk.push(3000);
stk.push(4000);
console.log("Stack elements:");
stk.display();
stk.pop();
console.log("Now elements in stack are:");
stk.display();
Output-
Screenshots-
Q5 Write a program of stack to Check for balanced parentheses.
Program-
function areBracketsBalanced(expr)
{ let stack = [];
if (stack.length == 0)
return false;
let check;
switch (x){
case ')':
check = stack.pop();
if (check == '{' || check == '[')
return false;
break;
case '}':
check = stack.pop();
if (check == '(' || check == '[')
return false;
break;
case ']':
check = stack.pop();
if (check == '(' || check == '{')
return false;
break;
}}
if (areBracketsBalanced(expr))
console.log("Balanced ");
else
console.log("Not Balanced ");
Output
Q6. Write a program to Reverse a string using stack
Program
class newNode {
constructor(data) {
this.data = data
this.next = null
}}
class S {
constructor() {
this.top = null
}
push(ele) {
var node = new newNode(ele)
node.next = this.top
this.top = node
}
pop() {
var temp = this.top
var char = temp.data
this.top = this.top.next
temp = null
return char
}
reverseString(str) {
var i = 0
var reversestr = ""
while (i != str.length) {
this.push(str.charAt(i))
i++
}
var temp = this.top
while (temp != null) {
var char
char = this.pop()
reversestr += char
temp = this.top
}
return reversestr
}
display() {
var temp = this.top
while (temp != null) {
console.log(temp.data)
temp = temp.next
} }}
const s = new S();
const string = "Pratha"
const reverse = s.reverseString(string)
console.log(`The String provided - ${string}\nString in reverse format -${reverse}`)
output:-
Q7. Write a program to implement Linear Queue
Program-
class LinearQueue {
constructor(size) {
this.queue = [];
this.size = size;
this.front = -1;
this.rear = -1;
}
isEmpty() {
return this.front === -1;
}
isFull() {
return this.rear === this.size - 1;
}
enqueue(element) {
if (this.isFull()) {
console.log("Queue is full. Cannot enqueue.");
return;
}
if (this.isEmpty()) {
this.front = 0;
}
this.rear++;
this.queue[this.rear] = element;
console.log(`${element} enqueued to the queue.`);
}
dequeue() {
if (this.isEmpty()) {
console.log("Queue is empty. Cannot dequeue.");
return;
}
display() {
if (this.isEmpty()) {
Data Structure and Algorithms
console.log("Queue is empty.");
} else {
console.log("Elements in the queue:",
this.queue.slice(this.front, this.rear + 1));
}
}
}
Output-
Program-
class Stack {
constructor() {
this.items = [];
}
function reverseString(inputString) {
const stack = new Stack();
// Example usage
const originalString = 'PRATHAM';
const reversedString = reverseString(originalString);
Output-
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(key) {
this.root = this._insert(this.root, key);
}
_insert(root, key) {
if (root === null) {
return new Node(key);
}
return root;
}
delete(key) {
this.root = this._delete(this.root, key);
}
_delete(root, key) {
if (root === null) {
return root;
}
return root;
}
_minValueNode(node) {
let current = node;
while (current.left !== null) {
current = current.left;
}
return current;
}
_search(root, key) {
if (root === null || root.key === key) {
return root;
}
inorder() {
const result = [];
this._inorderRec(this.root, result);
return result;
}
_inorderRec(node, result) {
if (node !== null) {
this._inorderRec(node.left, result);
result.push(node.key);
this._inorderRec(node.right, result);
}
}
}
bst.delete(20);
console.log("Inorder traversal after deleting 20:", bst.inorder());
Program-
class Queue {
constructor() {
this.rear = -1;
this.front = -1;
this.size = 5;
this.arr = new Array();
}
enQueue(value) {
if (this.front == 0 && this.rear == this.size - 1)
{
console.log("Queue is Full");
return;
}
else if (this.front == -1) {
this.front = this.rear = 0;
this.arr[this.rear] = value;
}
else if (this.rear == this.size - 1 && this.front != 0) {
this.rear = 0;
this.arr[this.rear] = value;
}
else {
this.rear++;
this.arr[this.rear] = value;
}
}
deQueue() {
if (this.front == -1) {
console.log("Queue is Empty");
}
let data = this.arr[this.front];
this.arr[this.front] = -1;
if (this.front == this.rear) {
this.front = -1;
this.rear = -1;
}
else if (this.front == this.size - 1)
this.front = 0;
else
this.front++;
// console.log("Data: ",data);
return data;
}
displayQueue() {
if (this.front == -1) {
console.log("Queue is Empty");
return;
}
Data Structure and Algorithms
console.log("\nElements in Circular Queue are: ");
if (this.rear >= this.front) {
for (let i = this.front; i <= this.rear; i++)
console.log(this.arr[i]);
}
else {
for (let i = this.front; i < this.size; i++)
console.log(this.arr[i]);
for (let i = 0; i <= this.rear; i++)
console.log(this.arr[i]);
}
}
}
q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);
q.displayQueue();
Screenshot-
Q11 Write a Program to print Adjacency Matrix and Adjacency List by reading Edges of Graph.
Program-
function createGraph(edges) {
const adjacencyMatrix = [];
const adjacencyList = {};
if (!adjacencyList[start]) {
adjacencyList[start] = [];
}
adjacencyList[start].push(end);
}
edges.forEach(edge => {
const [start, end] = edge;
addEdge(start, end);
});
const edges = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]];
const { adjacencyMatrix, adjacencyList } = createGraph(edges);
console.log("Adjacency Matrix:");
adjacencyMatrix.forEach(row => console.log(row.join(" ")));
console.log("\nAdjacency List:");
for (const vertex in adjacencyList) {
console.log(`${vertex} -> ${adjacencyList[vertex].join(", ")}`); }
Output-
Q12. Write a Program to find the element in an array using Binary Search.
Program-
return -1;
}
Output-
Q13 Write a Program to find the element in an array using Linear Search
Program-
function LinearSearch(arra, k)
{
for ( let i=0; i < arra.length;i++)
{
if(arra[i]==k)
{
return i;
}
}
return -1
}
var a = [80,45,70,35,40,50];
i = LinearSearch(a, 35);
if(i==-1)
{
console.log("Element is not found");
}
else
{
console.log("Element is present at position:",i+1);
}
Output -
Q14. Write a Program to Print Pascal’s triangle for n=5
Program-
function PascalTriangle(numRows)
{
if (numRows===0) return []
}
else{
ar.push((result[row-2][col-1]+result[row -2][col]))
}
}
result.push(ar);
}
return result;
}
let n = 5;
console.log(PascalTriangle(n));
Output-
Q15. Write a Program to implement GCD of two numbers using Euclidean Algorithm
Program
function GCD(a,b)
{
if(a == 0)
{
return b;
}
else{
return GCD(b % a, a);
}
}
var a = 270 , b = 192;
console.log("GCD of "+ a + " and " + b +" = ", GCD(a, b));
Output
Q16 . Write a program to implement tower of Hanoi where number of disks=4.
Program
Output-
Q17. Write a program to implement Fibonacci series till N.
Program
console.log('Fibonnacci Series:');
Output-
Q18. Write a program to implement Rain terrace Problem
Program-
function maxWater(ary, n)
{
var res = 0;
for(var i = 1; i < n -1; i++)
{
var left = ary[i];
for (var j = 0; j < i; j++)
{
left = Math.max(left, ary[j])
}
var right = ary[i];
for(j = i+1; j < n; j++)
{
right = Math.max(right, ary[j])
}
res += Math.min(left, right) - ary[i];
}
return res;
}
var ary = [0,1,0,2,1,0,1,3,2,1,];
n = ary.length;
console.log(maxWater(ary,n));
Output-
Q19. Write a Program to implement Graph traversal 1.BFS 2.DFS
BFS-
class graph {
constructor() {
this.vertices = [];
this.adjacencyList = new Map();
}
addVertex(vertex) {
this.vertices.push(vertex);
this.adjacencyList.set(vertex, []);
}
addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1).push(vertex2);
this.adjacencyList.get(vertex2).push(vertex1);
}
bfs(startingVertex) {
const visited = new Set();
const queue = [];
visited.add(startingVertex);
queue.push(startingVertex);
gph.addVertex('A');
gph.addVertex('B');
gph.addVertex('C');
gph.addVertex('D');
gph.addVertex('E');
gph.addEdge('A', 'B');
gph.addEdge('A', 'C');
gph.addEdge('B', 'D');
Data Structure and Algorithms
gph.addEdge('C', 'E');
console.log('BFS Traversal:');
gph.bfs('A');
Output-
DFS-
class Graph {
constructor() {
this.adjacencyList = new Map();
}
addVertex(vertex) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1).push(vertex2);
this.adjacencyList.get(vertex2).push(vertex1);
}
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addVertex('E');
graph.addEdge('A', 'B');
graph.addEdge('B', 'C');
graph.addEdge('C', 'D');
graph.addEdge('D', 'E');
console.log("DFS Traversal:");
graph.dfs('A');
Output-
Q20. Write a program to implement sorting using Divide and Conquer strategy 1. Quick sort 2. Merge sort
Program
Quick Sort:
a[high] = a[j];
a[j] = pivot;
return j;
}
Merge Sort-
function merge(arr, l, m, r)
{
var n1 = m - l + 1;
var n2 = r - m;
var i =
0; var j
= 0; var
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
} k+
+;
}
Program-
class SegmentTree {
constructor(nums) {
this.n = nums.length;
this.tree = new Array(2 * this.n).fill(0);
update(index, value) {
this.updateHelper(0, 0, this.n - 1, index, value);
}
output-
Audyogik Tantra Shikshan Sansth’s
Certificate
This is to certify that Mr./Ms. PRATHAM VIKAS MEKHALE
is bonafide student of IICMR, studying in Master of Computer Application(MCA) Program (Batch 2023-2025).
Seat no 6812
Examiner 1. Examiner 2.
Date:
ATSS’s
INDEX
Teacher's
Sr. Course Page
Name of the Practical Sign with Remarks
No. Outcome No.
Date
Hybrid Inheritance - Class student should hold the
rollno,class test should hold marks scored in two
different subjects(m1,m2,m3), interface sports should
1 hold marks in sports and class Result should calculate CO1 5
the total marks. The program must print the rollno,
marks scored in individual subject marks, marks scored
in sports and the total marks.
PROGRAM-
interface Sports {
int getSportsMarks();
}
class Student { int
rollno;
public Test(int rollno, int m1, int m2, int m3) { super(rollno);
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}
public void displayTestMarks() {
System.out.println("Test Marks: " + m1 + ", " + m2 + ", " + m3);
}
}
class Result extends Test implements Sports { int sportsMarks;
public Result(int rollno, int m1, int m2, int m3, int sportsMarks) { super(rollno, m1, m2,
m3);
this.sportsMarks = sportsMarks;
}
@Override
public int getSportsMarks() { return
sportsMarks;
}
public void displayResult() { System.out.println("Roll No: "
+ rollno); displayTestMarks();
System.out.println("Sports Marks: " + sportsMarks); int totalMarks =
m1 + m2 + m3 + sportsMarks; System.out.println("Total Marks: " +
totalMarks);
}
}
public class HybridInheritance {
public static void main(String[] args) {
Result resultInstance = new Result(26, 90, 85, 95, 75); resultInstance.displayResult();
}
}
OUTPUT-
Q2. Design an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need
to write a class called MyCalculator which implements the interface. divisor_sum(int n) function takes an integer
as input and return the sum of all its divisors. Divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12.
(0<n<100).
PROGRAM-
int sum = 0;
for (int i = 1; i <= n; i++) { if (n % i
== 0) {
sum += i;
} }
return sum;
}}
public class AdvancedArithmeticDivSum { public static void
main(String[] args) {
MyCalculator myCalculator = new MyCalculator(); int result =
myCalculator.divisor_sum(6); System.out.println("Divisor Sum: " +
result);
}
}
OUTPUT-
‘
Q3. Design an interface Shape which contain method input() and area() to calculate area of cirlce,square and
rectangle.
PROGRAM-
OUTPUT-
Q4. Write an application which will throw OverwtProductException if Product weight is above 60kg. (Use User
defined exception).
PROGRAM-
overweightProduct.checkWeight();
} catch (OverweightProductException e) { System.out.println("Exception: " +
e.getMessage());
}
}
}
OUTPUT-
Q5. For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal diagonals.
PROGRAM-
import java.util.Scanner;
public class PrincipalDiagonalSum { public static
void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the size of the
square matrix (N): "); int N = scanner.nextInt();
int[][] matrix = new int[N][N]; System.out.println("Enter the elements of
the matrix:"); for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) { matrix[i][j] =
scanner.nextInt();
}
}
int principalDiagonalSum = calculatePrincipalDiagonalSum(matrix, N); System.out.println("Sum of elements in the
principal diagonal: " + principalDiagonalSum);
scanner.close();
}
private static int calculatePrincipalDiagonalSum(int[][] matrix, int N) { int sum = 0;
for (int i = 0; i < N; i++) { sum +=
matrix[i][i];
}
return sum;
}
}
OUTPUT-
Q6. Declare the integer array with 10 numbers. Generate 2 new arrays Prime and NonPrime with prime and non-
prime numbers from main array.
PROGRAM-
OUTPUT
Q7 Program to count occurance of given number in an integer array of size 10.
PROGRAM-
import java.util.Scanner;
public class NumberOccurrenceInArray { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); int[] array = new int[10];
System.out.println("Enter 10 numbers:"); for (int i = 0; i <
array.length; i++) { array[i] = scanner.nextInt(); }
System.out.print("Enter the number to count its occurrences: "); int numberToCount =
scanner.nextInt();
int occurrenceCount = countOccurrences(array, numberToCount); System.out.println("Number of occurrences of " +
numberToCount + ": " + occurrenceCount);
scanner.close(); }
private static int countOccurrences(int[] array, int number) { int count = 0;
for (int i = 0; i < array.length; i++) { if (array[i] ==
number) {
count++; } return
count; }} OUTPUT-
Q8.Program to reverse string without using inbuilt methods.
PROGRAM-
import java.util.Scanner; public class
ReverseString {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String reversedString = reverseString(inputString); System.out.println("Reversed String: " +
reversedString); scanner.close();
}
private static String reverseString(String input) { char[] charArray =
input.toCharArray();
int start = 0;
int end = charArray.length - 1; while (start <
end) {
char temp = charArray[start]; charArray[start] =
charArray[end]; charArray[end] = temp;
start++;
end--; }
return new String(charArray); }}
OUTPUT-
Q9. Program to remove duplicate characters from String
PROGRAM-
import java.util.Scanner;
public class RemoveDuplicatesFromString { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String resultString = removeDuplicates(inputString); System.out.println("String after removing
duplicates: " + resultString); scanner.close(); }
private static String removeDuplicates(String input) { char[] charArray =
input.toCharArray();
int length = charArray.length; for (int i = 0;
i < length; i++) {
for (int j = i + 1; j < length; j++) { if
(charArray[i] == charArray[j]) { charArray[j]
= '\0'; }}}
int newIndex = 0;
for (int i = 0; i < length; i++) { if
(charArray[i] != '\0') {
charArray[newIndex++] = charArray[i];}} return new
String(charArray, 0, newIndex); }} OUTPUT-
Q10. Program to toggle case each charatcer of every word of string.
PROGRAM-
import java.util.Scanner;
scanner.close();
}
private static String toggleCaseInWords(String input) { StringBuilder result = new
StringBuilder();
word : words) {
result.append(toggleCase(word)).append(" ");
}
return result.toString().trim();
}
private static String toggleCase(String word) { char[] characters =
word.toCharArray();
OUTPUT-
Q11. Write a program to demonstrate Arrays class any 10 methods with examples (hint: Java.util.Arrays).
PROGRAM -
import java.util.Arrays;
public class ArraysMethod10 {
public static void main(String[] args) { int[] array1 = {9,
10, 8, 5, 1, 2, 3, 6, 8, 11};
int[] array2 = {9, 10, 8, 5, 1, 2, 3, 6, 8, 11};
// 1. Sorting array Arrays.sort(array1);
System.out.println("1. Sorted array: " + Arrays.toString(array1));
// 2. Binary search int
searchKey = 4;
int index = Arrays.binarySearch(array1, searchKey); System.out.println("2. Index of " +
searchKey + ": " + index);
// 3. Comparing arrays
boolean areEqual = Arrays.equals(array1, array2); System.out.println("3. Arrays are equal: "
+ areEqual);
// 4. Filling array
int[] filledArray = new int[5];
Arrays.fill(filledArray, 42);
System.out.println("4. Filled array: " + Arrays.toString(filledArray));
// 5. Copying arrays
int[] copiedArray = Arrays.copyOf(array1, array1.length); System.out.println("5. Copied array: " +
Arrays.toString(copiedArray));
// 6. Copying a range of elements
int[] rangeCopiedArray = Arrays.copyOfRange(array1, 2, 7); System.out.println("6. Copied
range array: " + Arrays.toString(rangeCopiedArray));
// 7. Converting array to a string
String arrayAsString = Arrays.toString(array1); System.out.println("7. Array as string: " +
arrayAsString);
// 8. Finding the minimum value
int minValue = Arrays.stream(array1).min().orElse(0); System.out.println("8. Minimum
value: " + minValue);
// 9. Finding the maximum value
int maxValue = Arrays.stream(array1).max().orElse(0); System.out.println("9. Maximum
value: " + maxValue);
// 10. Checking if array contains a specific value
boolean containsValue = Arrays.asList(array1).contains(6); System.out.println("10. Array
contains value 6: " + containsValue);
}
}
OUTPUT-
Q12. Write java program to generate 10 terms of Fibonacci series using threads.
PROGRAM-
class FibonacciThread extends Thread { private int n;
public FibonacciThread(int n) { this.n = n;
}
public void run() { int a =
0, b = 1, c;
System.out.print("Fibonacci Series for " + n + " terms: "); for (int i = 1; i <= n;
++i) {
System.out.print(a + " "); c = a +
b;
a = b;
b = c;
}
System.out.println();
})
public class FibonacciSeriesWithThreads { public static void
main(String[] args) {
FibonacciThread thread1 = new FibonacciThread(10); FibonacciThread
thread2 = new FibonacciThread(10); thread1.start();
thread2.start();
}
}
OUTPUT-
Q13. Create a menu driven program for Bank account(acc_no, Name, amt) (Hint: use vector) 1. Add 2. Search 3.
Delete 4. Display
PROGRAM-
OUTPUT-
Q14. Write a program to store employee in TreeSet and employees should be in sorted order of their age.
PROGRAM-
import java.util.*;
@Override
public int compareTo(Employee other) { return
Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + '}';
}
}
public class EmployeeTreeSetExample { public static
void main(String[] args) {
TreeSet<Employee> employeeSet = new TreeSet<>();
employeeSet.add(new Employee("Pratham", 21));
employeeSet.add(new Employee("Dnayesh", 22));
employeeSet.add(new Employee("Tanvi", 22));
employeeSet.add(new Employee("Prashun", 22));
OUTPUT-
Q15.Write a program to write and read file by character Stream. Also count number of lines in the file.
PROGRAM-
PROGRAM-
OUTPUT-
Q17. Design GUI for Student Registration (Student ID, Name, Address, Gender, DOB, Course (C,C++,Java,
Python, Data Science, Hadoop, PowerBI, AWS. It should be in dropdown combo). Add the details in database.
(Use events for radio button, combobox )
PROGRAM-
PROGRAM-
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html> loginServlet
import java.io.IOException; import
java.io.PrintWriter;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet { private static
final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username"); String password =
request.getParameter("password");
if ("Scott".equals(username) && "tiger".equals(password)) { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>"); out.println("<h2>Welcome,
Scott!</h2>"); out.println("</body></html>");
} else { response.sendRedirect("http://localhost:8080/login.html");
}
}
}
OUTPUT-
Q19. Write a servlet to add a Cookie to clients machine that stores username, current date & time. Display the same.
PROGRAM-
OUTPUT-
Audyogik Tantra Shikshan Sansth’s
Certificate
This is to certify that Mr./Ms. PRATHAM VIKAS MEKHALE
is bonafide student of IICMR, studying in Master of Computer Application(MCA) Program (Batch 2023-2025).
Seat no 6812
Examiner 1. Examiner 2.
Date:
ATSS’s
INDEX
Teacher's
Sr. Course Page
Name of the Practical Sign with Remarks
No. Outcome No.
Date
Hybrid Inheritance - Class student should hold the
rollno,class test should hold marks scored in two
different subjects(m1,m2,m3), interface sports should
1 hold marks in sports and class Result should calculate CO1 5
the total marks. The program must print the rollno,
marks scored in individual subject marks, marks scored
in sports and the total marks.
PROGRAM-
interface Sports {
int getSportsMarks();
}
class Student { int
rollno;
public Test(int rollno, int m1, int m2, int m3) { super(rollno);
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}
public void displayTestMarks() {
System.out.println("Test Marks: " + m1 + ", " + m2 + ", " + m3);
}
}
class Result extends Test implements Sports { int sportsMarks;
public Result(int rollno, int m1, int m2, int m3, int sportsMarks) { super(rollno, m1, m2,
m3);
this.sportsMarks = sportsMarks;
}
@Override
public int getSportsMarks() { return
sportsMarks;
}
public void displayResult() { System.out.println("Roll No: "
+ rollno); displayTestMarks();
System.out.println("Sports Marks: " + sportsMarks); int totalMarks =
m1 + m2 + m3 + sportsMarks; System.out.println("Total Marks: " +
totalMarks);
}
}
public class HybridInheritance {
public static void main(String[] args) {
Result resultInstance = new Result(26, 90, 85, 95, 75); resultInstance.displayResult();
}
}
OUTPUT-
Q2. Design an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need
to write a class called MyCalculator which implements the interface. divisor_sum(int n) function takes an integer
as input and return the sum of all its divisors. Divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12.
(0<n<100).
PROGRAM-
int sum = 0;
for (int i = 1; i <= n; i++) { if (n % i
== 0) {
sum += i;
} }
return sum;
}}
public class AdvancedArithmeticDivSum { public static void
main(String[] args) {
MyCalculator myCalculator = new MyCalculator(); int result =
myCalculator.divisor_sum(6); System.out.println("Divisor Sum: " +
result);
}
}
OUTPUT-
‘
Q3. Design an interface Shape which contain method input() and area() to calculate area of cirlce,square and
rectangle.
PROGRAM-
OUTPUT-
Q4. Write an application which will throw OverwtProductException if Product weight is above 60kg. (Use User
defined exception).
PROGRAM-
overweightProduct.checkWeight();
} catch (OverweightProductException e) { System.out.println("Exception: " +
e.getMessage());
}
}
}
OUTPUT-
Q5. For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal diagonals.
PROGRAM-
import java.util.Scanner;
public class PrincipalDiagonalSum { public static
void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the size of the
square matrix (N): "); int N = scanner.nextInt();
int[][] matrix = new int[N][N]; System.out.println("Enter the elements of
the matrix:"); for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) { matrix[i][j] =
scanner.nextInt();
}
}
int principalDiagonalSum = calculatePrincipalDiagonalSum(matrix, N); System.out.println("Sum of elements in the
principal diagonal: " + principalDiagonalSum);
scanner.close();
}
private static int calculatePrincipalDiagonalSum(int[][] matrix, int N) { int sum = 0;
for (int i = 0; i < N; i++) { sum +=
matrix[i][i];
}
return sum;
}
}
OUTPUT-
Q6. Declare the integer array with 10 numbers. Generate 2 new arrays Prime and NonPrime with prime and non-
prime numbers from main array.
PROGRAM-
OUTPUT
Q7 Program to count occurance of given number in an integer array of size 10.
PROGRAM-
import java.util.Scanner;
public class NumberOccurrenceInArray { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); int[] array = new int[10];
System.out.println("Enter 10 numbers:"); for (int i = 0; i <
array.length; i++) { array[i] = scanner.nextInt(); }
System.out.print("Enter the number to count its occurrences: "); int numberToCount =
scanner.nextInt();
int occurrenceCount = countOccurrences(array, numberToCount); System.out.println("Number of occurrences of " +
numberToCount + ": " + occurrenceCount);
scanner.close(); }
private static int countOccurrences(int[] array, int number) { int count = 0;
for (int i = 0; i < array.length; i++) { if (array[i] ==
number) {
count++; } return
count; }} OUTPUT-
Q8.Program to reverse string without using inbuilt methods.
PROGRAM-
import java.util.Scanner; public class
ReverseString {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String reversedString = reverseString(inputString); System.out.println("Reversed String: " +
reversedString); scanner.close();
}
private static String reverseString(String input) { char[] charArray =
input.toCharArray();
int start = 0;
int end = charArray.length - 1; while (start <
end) {
char temp = charArray[start]; charArray[start] =
charArray[end]; charArray[end] = temp;
start++;
end--; }
return new String(charArray); }}
OUTPUT-
Q9. Program to remove duplicate characters from String
PROGRAM-
import java.util.Scanner;
public class RemoveDuplicatesFromString { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String resultString = removeDuplicates(inputString); System.out.println("String after removing
duplicates: " + resultString); scanner.close(); }
private static String removeDuplicates(String input) { char[] charArray =
input.toCharArray();
int length = charArray.length; for (int i = 0;
i < length; i++) {
for (int j = i + 1; j < length; j++) { if
(charArray[i] == charArray[j]) { charArray[j]
= '\0'; }}}
int newIndex = 0;
for (int i = 0; i < length; i++) { if
(charArray[i] != '\0') {
charArray[newIndex++] = charArray[i];}} return new
String(charArray, 0, newIndex); }} OUTPUT-
Q10. Program to toggle case each charatcer of every word of string.
PROGRAM-
import java.util.Scanner;
scanner.close();
}
private static String toggleCaseInWords(String input) { StringBuilder result = new
StringBuilder();
word : words) {
result.append(toggleCase(word)).append(" ");
}
return result.toString().trim();
}
private static String toggleCase(String word) { char[] characters =
word.toCharArray();
OUTPUT-
Q11. Write a program to demonstrate Arrays class any 10 methods with examples (hint: Java.util.Arrays).
PROGRAM -
import java.util.Arrays;
public class ArraysMethod10 {
public static void main(String[] args) { int[] array1 = {9,
10, 8, 5, 1, 2, 3, 6, 8, 11};
int[] array2 = {9, 10, 8, 5, 1, 2, 3, 6, 8, 11};
// 1. Sorting array Arrays.sort(array1);
System.out.println("1. Sorted array: " + Arrays.toString(array1));
// 2. Binary search int
searchKey = 4;
int index = Arrays.binarySearch(array1, searchKey); System.out.println("2. Index of " +
searchKey + ": " + index);
// 3. Comparing arrays
boolean areEqual = Arrays.equals(array1, array2); System.out.println("3. Arrays are equal: "
+ areEqual);
// 4. Filling array
int[] filledArray = new int[5];
Arrays.fill(filledArray, 42);
System.out.println("4. Filled array: " + Arrays.toString(filledArray));
// 5. Copying arrays
int[] copiedArray = Arrays.copyOf(array1, array1.length); System.out.println("5. Copied array: " +
Arrays.toString(copiedArray));
// 6. Copying a range of elements
int[] rangeCopiedArray = Arrays.copyOfRange(array1, 2, 7); System.out.println("6. Copied
range array: " + Arrays.toString(rangeCopiedArray));
// 7. Converting array to a string
String arrayAsString = Arrays.toString(array1); System.out.println("7. Array as string: " +
arrayAsString);
// 8. Finding the minimum value
int minValue = Arrays.stream(array1).min().orElse(0); System.out.println("8. Minimum
value: " + minValue);
// 9. Finding the maximum value
int maxValue = Arrays.stream(array1).max().orElse(0); System.out.println("9. Maximum
value: " + maxValue);
// 10. Checking if array contains a specific value
boolean containsValue = Arrays.asList(array1).contains(6); System.out.println("10. Array
contains value 6: " + containsValue);
}
}
OUTPUT-
Q12. Write java program to generate 10 terms of Fibonacci series using threads.
PROGRAM-
class FibonacciThread extends Thread { private int n;
public FibonacciThread(int n) { this.n = n;
}
public void run() { int a =
0, b = 1, c;
System.out.print("Fibonacci Series for " + n + " terms: "); for (int i = 1; i <= n;
++i) {
System.out.print(a + " "); c = a +
b;
a = b;
b = c;
}
System.out.println();
})
public class FibonacciSeriesWithThreads { public static void
main(String[] args) {
FibonacciThread thread1 = new FibonacciThread(10); FibonacciThread
thread2 = new FibonacciThread(10); thread1.start();
thread2.start();
}
}
OUTPUT-
Q13. Create a menu driven program for Bank account(acc_no, Name, amt) (Hint: use vector) 1. Add 2. Search 3.
Delete 4. Display
PROGRAM-
OUTPUT-
Q14. Write a program to store employee in TreeSet and employees should be in sorted order of their age.
PROGRAM-
import java.util.*;
@Override
public int compareTo(Employee other) { return
Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + '}';
}
}
public class EmployeeTreeSetExample { public static
void main(String[] args) {
TreeSet<Employee> employeeSet = new TreeSet<>();
employeeSet.add(new Employee("Pratham", 21));
employeeSet.add(new Employee("Dnayesh", 22));
employeeSet.add(new Employee("Tanvi", 22));
employeeSet.add(new Employee("Prashun", 22));
OUTPUT-
Q15.Write a program to write and read file by character Stream. Also count number of lines in the file.
PROGRAM-
PROGRAM-
OUTPUT-
Q17. Design GUI for Student Registration (Student ID, Name, Address, Gender, DOB, Course (C,C++,Java,
Python, Data Science, Hadoop, PowerBI, AWS. It should be in dropdown combo). Add the details in database.
(Use events for radio button, combobox )
PROGRAM-
PROGRAM-
login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html> loginServlet
import java.io.IOException; import
java.io.PrintWriter;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet { private static
final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username"); String password =
request.getParameter("password");
if ("Scott".equals(username) && "tiger".equals(password)) { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>"); out.println("<h2>Welcome,
Scott!</h2>"); out.println("</body></html>");
} else { response.sendRedirect("http://localhost:8080/login.html");
}
}
}
OUTPUT-
Q19. Write a servlet to add a Cookie to clients machine that stores username, current date & time. Display the same.
PROGRAM-
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
response.setContentType("text/html");
String username = "JohnDoe"; // Replace this with your actual username retrieval logic
// Create a cookie with the username and current date & time
out.println("<html><body>");
out.println("</body></html>");
out.close();
}
OUTPUT-