0% found this document useful (0 votes)
2 views43 pages

Binary Search and Sorting Algorithms

The document contains multiple experiments demonstrating various algorithms in C++, including iterative and recursive binary search, quick sort, merge sort, minimum cost spanning tree implementations using Kruskal's and Prim's algorithms, and the fractional knapsack problem. Each experiment includes source code, aims, and timing for execution. The document serves as a comprehensive guide for implementing these algorithms in C++.

Uploaded by

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

Binary Search and Sorting Algorithms

The document contains multiple experiments demonstrating various algorithms in C++, including iterative and recursive binary search, quick sort, merge sort, minimum cost spanning tree implementations using Kruskal's and Prim's algorithms, and the fractional knapsack problem. Each experiment includes source code, aims, and timing for execution. The document serves as a comprehensive guide for implementing these algorithms in C++.

Uploaded by

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

Experiment-1

Aim: Write a Program for iterative and recursive Binary Search.


Source code:
Iterative search
#include <iostream>
#include <ctime>
using namespace std;

// Linear Search Function


int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key)
return i;
}
return -1; // Not found
}

int main() {
int arr[] = {10, 23, 5, 89, 45, 12, 77, 30};
int size = sizeof(arr) / sizeof(arr[0]);
int key = 45;

clock_t start = clock(); // Start timing

int result = linearSearch(arr, size, key);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

if (result != -1)
cout << "Element " << key << " found at index " << result << endl;
else
cout << "Element " << key << " not found in the array" << endl;

cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:

Binary search
#include <iostream>
#include <ctime>
using namespace std;

// Iterative Binary Search Function


int binarySearch(int arr[], int size, int key) {
int low = 0, high = size - 1;

while (low <= high) {


int mid = low + (high - low) / 2;

if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}

return -1; // Not found


}

int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int size = sizeof(arr) / sizeof(arr[0]);
int key = 13;

clock_t start = clock(); // Start timing

int result = binarySearch(arr, size, key);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

if (result != -1)
cout << "Element " << key << " found at index " << result << endl;
else
cout << "Element " << key << " not found in the array" << endl;

cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:
Experiment-2
Aim: Write a program to sort a given set of elements using quick sort
Source Code:
#include <iostream>
#include <ctime>
using namespace std;

// Function to swap two elements


void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}

// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Pivot element
int i = low - 1; // Index of smaller element

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}

swap(arr[i + 1], arr[high]);


return i + 1;
}

// QuickSort function
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

// Function to print an array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {34, 7, 23, 32, 5, 62, 32, 13};
int size = sizeof(arr) / sizeof(arr[0]);

clock_t start = clock(); // Start timing

quickSort(arr, 0, size - 1);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Sorted array: ";


printArray(arr, size);
cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}
Output:
Experiment-3
Aim: Write a program to sort a given set of elements using merge sort
Source code:
#include <iostream>
#include <ctime>
using namespace std;

// Merges two subarrays of arr[]


void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

// Temp arrays
int* L = new int[n1];
int* R = new int[n2];

// Copy data to temp arrays


for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

// Merge the temp arrays back


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

while (i < n1 && j < n2) {


if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}

// Copy remaining elements


while (i < n1)
arr[k++] = L[i++];

while (j < n2)


arr[k++] = R[j++];

delete[] L;
delete[] R;
}

// Merge sort function


void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

// Function to print an array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

int main() {
int arr[] = {34, 7, 23, 32, 5, 62, 32, 13};
int size = sizeof(arr) / sizeof(arr[0]);

clock_t start = clock(); // Start timing

mergeSort(arr, 0, size - 1);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Sorted array: ";


printArray(arr, size);
cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:
Experiment-4
Aim:write a program to implement the mcst that is minimum cost spanning tree.
Source code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;

// Structure to represent an edge


struct Edge {
int src, dest, weight;
};

// Comparator to sort edges by weight


bool compareEdge(const Edge &a, const Edge &b) {
return [Link] < [Link];
}

// Union-Find Data Structure


class DisjointSet {
vector<int> parent, rank;

public:
DisjointSet(int n) {
[Link](n);
[Link](n, 0);

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


parent[i] = i;
}

int find(int u) {
if (u != parent[u])
parent[u] = find(parent[u]); // Path compression
return parent[u];
}

void unite(int u, int v) {


int set_u = find(u);
int set_v = find(v);

if (set_u != set_v) {
if (rank[set_u] < rank[set_v])
parent[set_u] = set_v;
else if (rank[set_u] > rank[set_v])
parent[set_v] = set_u;
else {
parent[set_v] = set_u;
rank[set_u]++;
}
}
}
};

void kruskalMST(vector<Edge> &edges, int V) {


sort([Link](), [Link](), compareEdge);

DisjointSet ds(V);
vector<Edge> result;
int totalWeight = 0;

for (Edge &e : edges) {


int u_set = [Link]([Link]);
int v_set = [Link]([Link]);

if (u_set != v_set) {
result.push_back(e);
totalWeight += [Link];
[Link](u_set, v_set);
}
}

cout << "Edges in the Minimum Cost Spanning Tree:\n";


for (Edge &e : result)
cout << [Link] << " -- " << [Link] << " == " << [Link] << endl;

cout << "Total cost of MST: " << totalWeight << endl;
}

int main() {
int V = 6; // Number of vertices
vector<Edge> edges = {
{0, 1, 4}, {0, 2, 4}, {1, 2, 2}, {1, 0, 4},
{2, 0, 4}, {2, 1, 2}, {2, 3, 3}, {2, 5, 2},
{2, 4, 4}, {3, 2, 3}, {3, 4, 3}, {4, 2, 4},
{4, 3, 3}, {5, 2, 2}, {5, 4, 3}
};

clock_t start = clock(); // Start timing

kruskalMST(edges, V);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:
Experiment-5
Aim: Write a program to implement the Prim’s algorithm.
Source code:
#include <iostream>
#include <vector>
#include <climits>
#include <ctime>
using namespace std;

const int V = 5; // Number of vertices

// Find the vertex with the minimum key value from the set of vertices not yet included in MST
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, minIndex;

for (int v = 0; v < V; v++)


if (!mstSet[v] && key[v] < min)
min = key[v], minIndex = v;

return minIndex;
}

// Print the constructed MST


void printMST(int parent[], int graph[V][V]) {
int totalWeight = 0;
cout << "Edge \tWeight\n";
for (int i = 1; i < V; i++) {
cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << "\n";
totalWeight += graph[i][parent[i]];
}
cout << "Total cost of MST: " << totalWeight << endl;
}

void primMST(int graph[V][V]) {


int parent[V]; // Array to store constructed MST
int key[V]; // Key values used to pick minimum weight edge
bool mstSet[V]; // To represent set of vertices not yet included in MST

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

key[0] = 0; // Start from the first vertex


parent[0] = -1; // First node is always root of MST

for (int count = 0; count < V - 1; count++) {


int u = minKey(key, mstSet); // Pick the min key vertex
mstSet[u] = true;

for (int v = 0; v < V; v++) {


// Update key and parent if the edge u-v is smaller than key[v]
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
}

printMST(parent, graph);
}

int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};

clock_t start = clock(); // Start timing

primMST(graph);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:
Experiment-6
Aim: write a program to implement krushkal’s algorithm.
Source code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;

// Structure to represent an edge


struct Edge {
int src, dest, weight;
};

// Comparator to sort edges by increasing weight


bool compareEdge(const Edge &a, const Edge &b) {
return [Link] < [Link];
}

// Disjoint Set (Union-Find) for cycle detection


class DisjointSet {
vector<int> parent, rank;

public:
DisjointSet(int n) {
[Link](n);
[Link](n, 0);

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


parent[i] = i;
}

int find(int u) {
if (u != parent[u])
parent[u] = find(parent[u]); // Path compression
return parent[u];
}

void unite(int u, int v) {


int rootU = find(u);
int rootV = find(v);

if (rootU != rootV) {
if (rank[rootU] < rank[rootV])
parent[rootU] = rootV;
else if (rank[rootU] > rank[rootV])
parent[rootV] = rootU;
else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
};

// Kruskal's Algorithm
void kruskalMST(vector<Edge> &edges, int V) {
sort([Link](), [Link](), compareEdge); // Sort edges by weight
DisjointSet ds(V);

vector<Edge> result;
int totalWeight = 0;
for (const Edge &e : edges) {
int setU = [Link]([Link]);
int setV = [Link]([Link]);

if (setU != setV) {
result.push_back(e);
totalWeight += [Link];
[Link](setU, setV);
}
}

cout << "Edges in the Minimum Cost Spanning Tree:\n";


for (const Edge &e : result)
cout << [Link] << " -- " << [Link] << " == " << [Link] << endl;

cout << "Total cost of MST: " << totalWeight << endl;
}

int main() {
int V = 6; // Number of vertices
vector<Edge> edges = {
{0, 1, 4}, {0, 2, 4}, {1, 2, 2}, {1, 0, 4},
{2, 0, 4}, {2, 1, 2}, {2, 3, 3}, {2, 5, 2},
{2, 4, 4}, {3, 2, 3}, {3, 4, 3}, {4, 2, 4},
{4, 3, 3}, {5, 2, 2}, {5, 4, 3}
};

clock_t start = clock(); // Start timing

kruskalMST(edges, V);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:
Experiment-7
Aim: write a program to implement the fractional knapsack problem.
Source code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;

// Structure to store item properties


struct Item {
int weight;
int value;

// Constructor
Item(int v, int w) : value(v), weight(w) {}
};

// Comparator function to sort items by value/weight ratio


bool compare(Item a, Item b) {
double r1 = (double)[Link] / [Link];
double r2 = (double)[Link] / [Link];
return r1 > r2;
}

// Fractional Knapsack function


double fractionalKnapsack(int capacity, vector<Item> &items) {
sort([Link](), [Link](), compare); // Sort by value/weight ratio

double totalValue = 0.0;

for (Item &item : items) {


if (capacity >= [Link]) {
capacity -= [Link];
totalValue += [Link];
} else {
totalValue += [Link] * ((double)capacity / [Link]);
break; // Bag is full
}
}

return totalValue;
}

int main() {
int capacity = 50;
vector<Item> items = {
{60, 10}, {100, 20}, {120, 30}
};

clock_t start = clock(); // Start time

double maxValue = fractionalKnapsack(capacity, items);

clock_t end = clock(); // End time


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Maximum value in knapsack: " << maxValue << endl;
cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}
Output:
Experiment-8
Aim: write a program to implement the 0/1 knapsack problem.
Source code:
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

// Function to solve 0/1 Knapsack using Dynamic Programming


int knapsack(int W, vector<int> &weight, vector<int> &value, int n) {
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));

// Build the DP table


for (int i = 1; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (weight[i - 1] <= w)
dp[i][w] = max(dp[i - 1][w],
value[i - 1] + dp[i - 1][w - weight[i - 1]]);
else
dp[i][w] = dp[i - 1][w];
}
}

return dp[n][W]; // Maximum value in knapsack


}

int main() {
int capacity = 50;
vector<int> weight = {10, 20, 30};
vector<int> value = {60, 100, 120};
int n = [Link]();

clock_t start = clock(); // Start timing

int maxValue = knapsack(capacity, weight, value, n);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Maximum value in knapsack: " << maxValue << endl;
cout << "Time taken: " << time_taken << " seconds" << endl;

return 0;
}

Output:
Experiment-9
Aim: write a program to implement Dijkstra’s algorithm.
Source code:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <ctime>
using namespace std;

typedef pair<int, int> pii; // (distance, vertex)

void dijkstra(int V, vector<vector<pii>> &adj, int src) {


vector<int> dist(V, INT_MAX);
priority_queue<pii, vector<pii>, greater<pii>> pq;

dist[src] = 0;
[Link]({0, src});

while (![Link]()) {
int u = [Link]().second;
[Link]();

for (auto &[v, weight] : adj[u]) {


if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
[Link]({dist[v], v});
}
}
}

cout << "Vertex\tDistance from Source\n";


for (int i = 0; i < V; i++)
cout << i << "\t" << dist[i] << "\n";
}

int main() {
int V = 5;
vector<vector<pii>> adj(V);

// Graph edges: (u, v, weight)


adj[0].push_back({1, 10});
adj[0].push_back({4, 5});
adj[1].push_back({2, 1});
adj[1].push_back({4, 2});
adj[2].push_back({3, 4});
adj[3].push_back({2, 6});
adj[3].push_back({0, 7});
adj[4].push_back({1, 3});
adj[4].push_back({2, 9});
adj[4].push_back({3, 2});

int source = 0;

clock_t start = clock(); // Start timing

dijkstra(V, adj, source);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Time taken: " << time_taken << " seconds\n";
return 0;
}

Output:
Experiment-10
Aim: write a program to implement N-Queen (4 queen) problem.
Source code:
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

// Function to print the chessboard


void printBoard(const vector<vector<int>>& board) {
for (const auto& row : board) {
for (int cell : row) {
if (cell == 1)
cout << " Q ";
else
cout << " . ";
}
cout << endl;
}
}

// Check if a queen can be placed on board[row][col]


// This is called when "col" queens are already placed
bool isSafe(const vector<vector<int>>& board, int row, int col, int N) {
// Check this row on left side
for (int i = 0; i < col; i++) {
if (board[row][i] == 1)
return false;
}

// Check upper diagonal on left side


for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1)
return false;
}

// Check lower diagonal on left side


for (int i = row, j = col; i < N && j >= 0; i++, j--) {
if (board[i][j] == 1)
return false;
}

return true;
}

// Solve the N-Queen problem using Backtracking


bool solveNQueenUtil(vector<vector<int>>& board, int col, int N) {
// Base case: If all queens are placed then return true
if (col >= N)
return true;

// Consider this column and try placing the queen in all rows one by one
for (int i = 0; i < N; i++) {
// Check if it is safe to place the queen in board[i][col]
if (isSafe(board, i, col, N)) {
// Place this queen in board[i][col]
board[i][col] = 1;

// Recur to place the rest of the queens


if (solveNQueenUtil(board, col + 1, N))
return true;

// If placing queen in board[i][col] doesn't lead to a solution


board[i][col] = 0; // Backtrack
}
}

// If the queen can not be placed in any row in this column col
return false;
}

// Function to solve the N-Queen problem


bool solveNQueen(int N) {
vector<vector<int>> board(N, vector<int>(N, 0));

clock_t start = clock(); // Start timing

if (solveNQueenUtil(board, 0, N)) {
printBoard(board); // Solution found, print the board
} else {
cout << "Solution does not exist." << endl;
}

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Time taken: " << time_taken << " seconds\n";
return true;
}

int main() {
int N = 4; // Solving the 4-Queen problem
solveNQueen(N);
return 0;
}

Output:
Experiment-11
Aim: write a program to implement the sum of subsets algorithm.
Source code:
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

// Function to find all subsets of the given set that sum to the target value
void sumOfSubsetsUtil(vector<int>& set, int target, vector<int>& subset, int index) {
// Base case: if target is 0, print the subset
if (target == 0) {
for (int num : subset)
cout << num << " ";
cout << endl;
return;
}

// If no elements left or target goes negative, return


if (index == [Link]() || target < 0)
return;

// Include the current element in the subset


subset.push_back(set[index]);
sumOfSubsetsUtil(set, target - set[index], subset, index + 1);

// Backtrack: exclude the current element from the subset


subset.pop_back();

// Move to the next element


sumOfSubsetsUtil(set, target, subset, index + 1);
}

// Function to start finding subsets with a target sum


void sumOfSubsets(vector<int>& set, int target) {
vector<int> subset; // To store current subset
clock_t start = clock(); // Start timing

sumOfSubsetsUtil(set, target, subset, 0);

clock_t end = clock(); // End timing


double time_taken = double(end - start) / CLOCKS_PER_SEC;

cout << "Time taken: " << time_taken << " seconds\n";
}

int main() {
vector<int> set = {3, 34, 4, 12, 5, 2};
int target = 9;

cout << "Subsets of the given set with sum = " << target << " are:\n";
sumOfSubsets(set, target);

return 0;
}
Output:
ST. ANDREWS INSTITUTE
OF TECHNOLOGY & MANAGEMENT

Gurgaon Delhi (NCR)


Approved by AICTE, Govt. of India, New DelhiAffiliated
to Maharshi Dayanand University
‘A’ Grade State University, accredited by NAAC

Session: 2025 – 2026

Bachelor of Technology

Data Science

A Practical File

Design and Analysis of Algorithms

Subject Code: PCC-CSE-307G

Submitted To : Submitted by:

[Link] sharma Name: Niket


Sem & Sec : 5th & A
RollNo.23DS016
St. Andrews Institute of Technology & Management,
Gurugram
Department of Computer Science & Engineering
Practical Lab Evaluation Sheet

Practical Viva-
Program Date Attendance Practical Overall
No.
Practical CO Performed Voce
(10) File (10) (50)
(20) (10)

1 Write a Program for iterative and


recursive Binary Search.
:Write a program to sort a given
2 set of elements using quick sort

Write a program to sort a given


3 set of elements using merge sort

write a program to implement


4 the mcst that is minimum cost
spanning tree.
Write a program to implement
5 the Prim’s algorithm.
write a program to implement
6 krushkal’s algorithm.
write a program to implement
7
the fractional knapsack problem.
write a program to implement
8
the 0/1 knapsack problem.
write a program to implement
9 Dijkstra’s algorithm

write a program to implement N-


10
Queen (4 queen) problem.
write a program to implement
11
the sum of subsets algorithm.
Average Marks

Approved & verified by (Faculty Name) (Faculty Sign.)


ST. ANDREWS INSTITUTE
OF TECHNOLOGY & MANAGEMENT
Gurgaon Delhi (NCR)
Approved by AICTE, Govt. of India, New Delhi Affiliated to Maharshi
Dayanand University
‘A’ Grade State University, accredited by NAAC

Session: 2025-2026

Bachelor of Technology (Data Science)

PRACTICAL FILE

ADVANCE JAVA PROGRAMMINGLAB

COURSE CODE: PCC-DS-311G

Submitted To : Submitted by:


DR. Shweta
Name : Niket
Sem : Vth
Roll No. :23DS016
St. Andrews Institute of Technology &
Management, Gurugram
Department of……………………………

Practical Lab Evaluation Sheet

Practical Viva- Attendance Practical Overall Remarks


[Link]. Program Date CO Performed Voice (05 File (05) (25) &
(10) (05) Signature

1 Write a Program to CO 1
import package to
calculate marks and
print grade of student.
2 Write a Program to set CO 1
prority of thread in
multi threading.

3 Write a Program to CO 1
implement multiple
interface
4 D Write a Program to CO 2
implement Abstract
Class.
5 Eclipse IDE CO 2
Installation.

6 Apache Tomcat Server CO 3


Installation.

7 Servlet Program to CO 3
print Hello world.
8 Servlet Program to CO 3
print request details.

9 Servlet Program to CO 3
print Hello world.

10 Servlet Program to CO 3
Create a Cookie

11 Servlet Program to CO 3
display a Cookie
12 Servlet Program to do a CO4
session tracking.

13 JSP Program to print CO4


Hello World

14 Write a Enterprise Java CO4


Bean Program for sum
Method.
15 JSP Program to perform CO4
to demonstrate
[Link] action tag.
16 Write a JSTL program CO4
to demonstrate core
tags.

Average Marks

Approved & Verified by (Faculty Name)

(Faculty Sign.)
PROGRAM NO. - 1
AIM: Write a Program to import package to calculate marks and print grade of student.

SOURCE CODE:

package Marks;

public class GradeCalculator {


public String getGrade(int marks) {
if (marks >= 90) return "A";
else if (marks >= 75) return "B";
else if (marks >= 60) return "C";
else if (marks >= 40) return "D";
else return "Fail";
}
}
import [Link];
import [Link].*;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
GradeCalculator g = new GradeCalculator();

[Link]("Enter Marks: ");


int m = [Link]();

[Link]("Grade = " + [Link](m));


}
}
OUTPUT:
PROGRAM NO. - 2
AIM: Write a Program to set prority of thread in multi threading.

SOURCE CODE:

class MyThread extends Thread {


public void run() {
[Link]("Running Thread: " + [Link]().getName() +
" Priority: " + [Link]().getPriority());
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

[Link](Thread.MAX_PRIORITY); // 10
[Link](Thread.MIN_PRIORITY); // 1

[Link]();
[Link]();
}
}
OUTPUT:
PROGRAM NO-3

AIM: Write a Program to implement multiple interfaceSOURCE CODE:

interface A {
void showA();
}

interface B {
void showB();
}

class MultipleDemo implements A, B {


public void showA() { [Link]("Interface A method"); }
public void showB() { [Link]("Interface B method"); }
}

public class Main {


public static void main(String[] args) {
MultipleDemo obj = new MultipleDemo();
[Link]();
[Link]();
}
}
OUTPUT:
PROGRAM NO-4

AIM: Write a Program to implement Abstract Class.

SOURCE CODE:

abstract class Shape {


abstract void draw();
}

class Circle extends Shape {


void draw() {
[Link]("Drawing Circle");
}
}

public class AbstractDemo {


public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}
OUTPUT:
PROGRAM NO-5
AIM: Eclipse IDE Installation.

SOURCE CODE:

1. Open any web browser like Chrome or Edge.


2. Search for “Eclipse IDE Download”.
3. Click the official site:
[Link]
4. Press the Download x86_64 Installer button.
5. Wait for the file [Link] to
download.
6. Go to your Downloads folder.
7. Double-click the Eclipse installer to open it.
8. Choose Eclipse IDE for Java Developers
from the options.
9. Select your preferred installation directory.
10. Click Install and accept the terms &
conditions.
11. Wait for installation to complete.
12. Click Launch to open the Eclipse IDE.
13. Choose a workspace folder for your project
files.
14. Go to File → New → Java Project.
15. Create a Java class and run the program to
verify installation.
OUTPUT:
PROGRAM NO-6

AIM: Apache Tomcat Server Installation.

SOURCE CODE:

1. Open any web browser like Chrome.


2. Visit the official site:
[Link]
3. Click Tomcat 10 or Tomcat 9 (depending on
requirement).
4. Scroll to Binary Distributions section.
5. Under “Core”, click Windows 64-bit ZIP
download link.
6. Let the ZIP file download completely.
7. Go to the Downloads folder.
8. Right-click the ZIP file → select Extract All.
9. Extract it to C:\Tomcat folder.
10. Set JAVA_HOME environment variable from
System Settings.
11. Open the extracted Tomcat/bin directory.
12. Double-click [Link] to start Tomcat
server.
13. A command prompt window will appear
showing server startup logs.
14. Open a browser and enter
[Link]
15. The Apache Tomcat Welcome Page will
appear, confirming installation.
OUTPUT:
PROGRAM NO-7
AIM : Servlet Program to print Hello world.

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloWorldServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Hello World from Servlet</h2>");
}
}
OUTPUT :
PROGRAM NO-8
AIM: Servlet Program to print request details.

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link].*;

public class RequestDetails extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
[Link]("text/html");
PrintWriter out = [Link]();

[Link]("Method: " + [Link]() + "<br>");


[Link]("URI: " + [Link]() + "<br>");
[Link]("IP Address: " + [Link]());
}
}

OUTPUT:
PROGRAM NO-9

AIM : Servlet Program to print Hello world.


SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link].*;

public class PrintServlet extends HttpServlet {


public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException {
[Link]("text/html");
[Link]().println("<h3>Hello World
Servlet</h3>");
}
}
OUTPUT:
PROGRAM NO-10
AIM: Servlet Program to Create a Cookie.

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link].*;

public class CreateCookieServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
Cookie cookie = new Cookie("user", "Niket");
[Link](cookie);

[Link]("text/html");
[Link]().println("Cookie Created!");
}
}
OUTPUT:
PROGRAM NO-11
AIM : Servlet Program to display a Cookie

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link].*;

public class DisplayCookieServlet extends HttpServlet


{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException {
Cookie[] cookies = [Link]();
[Link]("text/html");
PrintWriter out = [Link]();

if (cookies != null) {
for (Cookie c : cookies) {
[Link]([Link]() + " = " + [Link]()
+ "<br>");
}
} else {
[Link]("No cookies found.");
}
}
}
OUTPUT:
PROGRAM NO-12

AIM: Servlet Program to do a session tracking.

SOURCE CODE:

import [Link].*;
import [Link].*;
import [Link].*;

public class SessionTrackingServlet extends HttpServlet


{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException {
[Link]("text/html");
PrintWriter out = [Link]();

HttpSession session = [Link]();


Integer count = (Integer)
[Link]("visit");

if (count == null) count = 1;


else count++;

[Link]("visit", count);

[Link]("Session ID: " + [Link]() +


"<br>");
[Link]("Visit Count: " + count);
}
}

OUTPUT:
PROGRAM NO-13

AIM: JSP Program to print Hello World.

SOURCE CODE:

<%@ page language="java" %>


<h2>Hello World from JSP</h2>
OUTPUT:
PROGRAM NO-14

AIM: JSP Program to perform to demonstrate [Link] action tag.

SOURCE CODE:
[Link] :

import [Link];

@Stateless
public class SumBean {
public int sum(int a, int b) {
return a + b;
}
}

Client Program:

import [Link];

public class SumClient {


public static void main(String[] args) throws Exception {
InitialContext ctx = new InitialContext();
SumBean bean = (SumBean) [Link]("java:global/SumBean");

[Link]("Sum = " + [Link](50, 20));


}
}

OUTPUT:
PROGRAM NO-15

AIM : Write a JSTL program to demonstrate core tags.

SOURCE CODE:
[Link]:

<jsp:forward page="[Link]">
<jsp:param name="msg" value="Forwarded Successfully" />
</jsp:forward>

[Link]:

<h3>Forwarded Page</h3>
Message: ${[Link]}

OUTPUT:
PROGRAM NO-16
AIM : Genetic algorithms search via population evolution: selection, crossover, mutation. We'll
optimize a simple function using a tiny GA.

SOURCE CODE:

<%@ taglib uri="[Link] prefix="c" %>

<c:set var="name" value="Niket" />


<p>Name: <c:out value="${name}" /></p>

<c:if test="${name == 'Niket'}">


<p>Welcome, Niket!</p>
</c:if>

<c:forEach var="i" begin="1" end="5">


<p>Count: ${i}</p>
</c:forEach>

OUTPUT:

You might also like