Skip to main content

Posts

krushnaaa

  import java . awt .* ; import java . awt . event .* ; public class SimpleAWTExample {     public static void main ( String [] args ) {         // Create a Frame         Frame frame = new Frame ( "Simple AWT Example" );         // Create a Button         Button button = new Button ( "Click Me!" );         // Set layout for the Frame         frame . setLayout ( new FlowLayout ());         // Add the Button to the Frame         frame . add ( button );         // Set size of the Frame         frame . setSize ( 300 , 200 ); // Width: 300 pixels, Height: 200 pixels         // Make the Frame visible         frame . setVisible ( true );         // Add a WindowListener to handle closing event     ...

Create simple application of Java AWT in which show an awt component button by setting its placement and window frame size..

 CODE: https://drive.google.com/drive/folders/1upbNSvtYhlb-g7MztOMmSCkqGrtI2wEm882TbUeIslFqyvW9WMJkr11klrYgCQsU8FD8uILi import java.awt.Button; import java.awt.Frame; public class AWTButtonExample {     public static void main(String[] args) {         // Create a frame         Frame frame = new Frame("AWT Button Example");         // Create a button         Button button = new Button("Click Me");         // Set the size and position of the button         button.setBounds(100, 100, 80, 30);         // Add the button to the frame         frame.add(button);         // Set the frame size         frame.setSize(300, 200);         // Set frame layout to null (absolute positioning)         frame.setLayout(null);         // M...

Write a java program to create a calculator which performs addition, subtraction and multiplication of numbers for different types like integer, float and complex numbers using single function add(),sub() and multi().

 CODE: class Calculator {     // Addition for integers     public int add(int a, int b) {         return a + b;     }     // Addition for floats     public float add(float a, float b) {         return a + b;     }     // Addition for complex numbers     public ComplexNumber add(ComplexNumber a, ComplexNumber b) {         return new ComplexNumber(a.getReal() + b.getReal(), a.getImaginary() + b.getImaginary());     }     // Subtraction for integers     public int sub(int a, int b) {         return a - b;     }     // Subtraction for floats     public float sub(float a, float b) {         return a - b;     }     // Subtraction for complex numbers     public ComplexNumber sub(ComplexNumber a, ComplexNumber b) {   ...

Write a java program to create an abstract class named Shape that contains two integers and an empty method named print Area (). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape

 CODE: abstract class Shape {     protected int dimension1;     protected int dimension2;     public Shape(int dimension1, int dimension2) {         this.dimension1 = dimension1;         this.dimension2 = dimension2;     }     public abstract void printArea(); } class Rectangle extends Shape {     public Rectangle(int length, int width) {         super(length, width);     }     @Override     public void printArea() {         System.out.println("Area of Rectangle: " + (dimension1 * dimension2));     } } class Triangle extends Shape {     public Triangle(int base, int height) {         super(base, height);     }     @Override     public void printArea() {         System.out.println("Area of Triangle: " + (0.5 * dimension1 * dime...

Write a java program that implements a multi-thread application that has three threads. First thread generates a random integer every 1 second and if the value is even, the second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of the cube of the number.

 CODE: import java.util.Random; class RandomNumberGenerator implements Runnable {     public void run() {         Random random = new Random();         while (true) {             try {                 Thread.sleep(1000); // Sleep for 1 second                 int number = random.nextInt(100); // Generate a random integer between 0 and 99                 System.out.println("Generated number: " + number);                 if (number % 2 == 0) {                     Thread thread = new Thread(new SquareCalculator(number));                     thread.start();                 } else {         ...

Write a java program to create a class Student with data name, city and age along with method addData and printData to input and display the data. Create the two objects s1, s2 to declare and access the values.

 CODE: import java.util.Scanner; class Student {     private String name;     private String city;     private int age;     // Method to input data     public void addData(String name, String city, int age) {         this.name = name;         this.city = city;         this.age = age;     }     // Method to display data     public void printData() {         System.out.println("Name: " + name);         System.out.println("City: " + city);         System.out.println("Age: " + age);     } } public class StudentTest {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         // Creating objects of Student class         Student s1 = new Student();       ...

Write a java program to create class car, truck and motorcycle which extends the vehicle class (attribute registration number, color, type of vehicle) with their own attribute like make, CC and fuel type. Input data from the user and print all the details.

 CODE: import java.util.Scanner; class Vehicle {     private String registrationNumber;     private String color;     private String type;     // Constructor     public Vehicle(String registrationNumber, String color, String type) {         this.registrationNumber = registrationNumber;         this.color = color;         this.type = type;     }     // Getters     public String getRegistrationNumber() {         return registrationNumber;     }     public String getColor() {         return color;     }     public String getType() {         return type;     } } class Car extends Vehicle {     private String make;     private int CC;     private String fuelType;     // Constructor     public...

Write a program to create a class Student2 along with two method getData (), printData () to get the value through argument and display the data in printData. Create the two objects s1, s2 to declare and access the values from class STtest.

 CODE: import java.util.Scanner; class Student2 {     private String name;     private int age;          // Method to set data     public void getData(String name, int age) {         this.name = name;         this.age = age;     }          // Method to print data     public void printData() {         System.out.println("Name: " + name);         System.out.println("Age: " + age);     } } public class STtest {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);                  // Creating objects of Student2 class         Student2 s1 = new Student2();         Student2 s2 = new Student2();              ...

Write a Java program that accepts four integers from the user and prints equal if all four are equal, and not equal otherwise.

 CODE: import java.util.Scanner; public class Main {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);                  // Accepting four integers from the user         System.out.println("Enter the first integer:");         int num1 = scanner.nextInt();                  System.out.println("Enter the second integer:");         int num2 = scanner.nextInt();                  System.out.println("Enter the third integer:");         int num3 = scanner.nextInt();                  System.out.println("Enter the fourth integer:");         int num4 = scanner.nextInt();                  // Checking i...

Develop a program to model a graph using an adjacency list and employ Kruskal's algorithm to find the minimum spanning tree

 Code: #include <iostream> #include <vector> #include <algorithm> using namespace std; // Structure to represent an edge in the graph struct Edge {     int src, dest, weight; }; // Structure to represent a subset for union-find struct Subset {     int parent, rank; }; // Class to represent a graph and perform Kruskal's algorithm class Graph {     int V; // Number of vertices     vector<Edge> edges; // Vector to store graph edges public:     // Constructor     Graph(int V) {         this->V = V;     }     // Function to add an edge to the graph     void addEdge(int src, int dest, int weight) {         Edge edge = {src, dest, weight};         edges.push_back(edge);     }     // Function to find the subset of an element 'i'     int find(vector<Subset>& subsets, int i) { ...

Heap Sort Algorithm / Heapify Function

CODE:   #include <iostream> using namespace std; // A function to heapify the array. void MaxHeapify(int a[], int i, int n) { int j, temp; temp = a[i]; j = 2*i;   //(left child)   while (j <= n)                   { if (j < n && a[j+1] > a[j]) j = j+1; // Break if parent value is already greater than child value. if (temp > a[j]) break; // Switching value with the parent node if temp < a[j]. else if (temp <= a[j]) { a[j/2] = a[j]; j = 2*j; } }; a[j/2] = temp; return; } void HeapSort(int a[], int n) { int i, temp; for (i = n; i >= 2; i--) { // Storing maximum value at the end. temp = a[i]; a[i] = a[1]; a[1] = temp; // Building max heap of remaining element. MaxHeapify(a, 1, i - 1); } } void Build_MaxHeap(int a[], int n) { int i; for(i = n/2; i >= 1; i--) MaxHeapify(a, i, n); } int main() { int n, ...

File Handling Code

Code:  #include<fstream> #include<iostream> using namespace std; int main() { char data[100]; ofstream outfile; outfile.open("file.dat"); cout<<"writing to the file\n"; cout<<"Enter the name:\n "; cin.getline(data,100); outfile<<data<<"\n"; cout<<"\nEnter the age:\n"; cin.getline(data,100); cin.ignore(); outfile<<data<<"\n"; outfile.close(); ifstream infile; infile.open("file.dat"); cout<<"Reading from file\n"; infile>>data; cout<<data<<"\n"; infile>>data; cout<<data<<"\n"; infile.close(); return 0; }

Create a hash table and handle the collisions using Separate Chaining.

CODE:  #include <iostream> #include <list> #include <vector> using namespace std; class HashTable { private:     int size;     vector<list<int>> table; public:     HashTable(int s) : size(s) {         table.resize(size);     }     // Hash function to map values to keys     int hash(int key) {         return key % size;     }     // Function to insert key into hash table     void insert(int key) {         int index = hash(key);         table[index].push_back(key);     }     // Function to search for a key in the hash table     bool search(int key) {         int index = hash(key);         for (auto it = table[index].begin(); it != table[index].end(); ++it) {             if (*it == key) ...

Create a hash table and handle the collisions using linear probing with replacement.

CODE:  #include <iostream> #include <vector> #include <string> using namespace std; // Define a class for the hash table class HashTable { private:     vector<pair<string, int>> table;     int capacity;     int size;     // Hash function     int hash(const string& key) {         int hash = 0;         for (char c : key) {             hash += c;         }         return hash % capacity;     }     // Helper function to find the next available slot using linear probing     int findNextAvailable(int index) {         int i = index + 1;         while (table[i].first != "") {             i = (i + 1) % capacity;         }         return i;     } public:...

Create a program to represent a graph using an adjacency Matrix and perform Depth-First Search (DFS) to systematically visit all vertices.

CODE:  #include <iostream> #include <vector> #include <stack> using namespace std; class Graph { private:     int numVertices;     vector<vector<int>> adjacencyMatrix; public:     Graph(int n) : numVertices(n) {         adjacencyMatrix.resize(numVertices, vector<int>(numVertices, 0));     }     void addEdge(int u, int v) {         adjacencyMatrix[u][v] = 1;         adjacencyMatrix[v][u] = 1; // Assuming undirected graph     }     void DFS(int startVertex) {         vector<bool> visited(numVertices, false);         stack<int> stack;         visited[startVertex] = true;         stack.push(startVertex);         cout << "Depth First Search starting from vertex " << startVertex << ": ";   ...

Create a program to represent a graph using an adjacency list and perform Breadth-First Search (BFS) to systematically visit all vertices.

CODE:  #include <iostream> #include <list> #include <queue> using namespace std; // Class representing a graph class Graph {     int V; // Number of vertices     // Pointer to an array containing adjacency lists     list<int> *adj; public:     Graph(int V); // Constructor     // Function to add an edge to the graph     void addEdge(int v, int w);     // BFS traversal starting from a given vertex     void BFS(int s); }; Graph::Graph(int V) {     this->V = V;     adj = new list<int>[V]; } void Graph::addEdge(int v, int w) {     adj[v].push_back(w); // Add w to v's list. } void Graph::BFS(int s) {     // Mark all the vertices as not visited     bool *visited = new bool[V];     for (int i = 0; i < V; i++)         visited[i] = false;     // Create a queue for BFS     queue...

Create a program to represent a graph using an adjacency Matrix and perform Breadth-First Search (BFS) to systematically visit all vertices.

CODE:  #include <iostream> #include <queue> #include <vector> using namespace std; class Graph { private:     int numVertices;     vector<vector<int>> adjacencyMatrix; public:     Graph(int numVertices) {         this->numVertices = numVertices;         adjacencyMatrix.resize(numVertices, vector<int>(numVertices, 0));     }     void addEdge(int source, int destination) {         adjacencyMatrix[source][destination] = 1;         // For undirected graph, add this line as well:         // adjacencyMatrix[destination][source] = 1;     }     void BFS(int startVertex) {         vector<bool> visited(numVertices, false);         queue<int> q;         visited[startVertex] = true;         q.push(...

Represent a graph using adjacency matrix / Represent a graph using adjacency list.

CODE:  //Graph using adjacency matrix #include<iostream> using namespace std; int vertArr[20][20]; int count = 0; void displayMatrix(int v) { int i, j; for(i = 0; i < v; i++) { for(j = 0; j < v; j++) { cout<<vertArr[i][j]<<" "; } cout<<endl; } } void add_edge(int u, int v) { vertArr[u][v] = 1; vertArr[v][u] = 1; } main(int argc, char* argv[]) { int v = 6; add_edge(0, 4); add_edge(0, 3); add_edge(1, 2); add_edge(1, 4); add_edge(1, 5); add_edge(2, 3); add_edge(2, 5); add_edge(5, 3); add_edge(5, 4); displayMatrix(v); }

Create a threaded binary search tree with insert, search and delete leaf node operations.

 CODE: #include <iostream> using namespace std; // Node structure for the threaded binary search tree struct Node {     int key;     Node* left;     Node* right;     bool isThreaded; // Indicates if right pointer is a thread }; // Function to create a new node Node* createNode(int key) {     Node* newNode = new Node;     newNode->key = key;     newNode->left = nullptr;     newNode->right = nullptr;     newNode->isThreaded = false;     return newNode; } // Function to insert a key into the threaded binary search tree Node* insert(Node* root, int key) {     // If tree is empty, create a new node     if (root == nullptr) {         return createNode(key);     }          // Traverse the tree to find the appropriate position     Node* curr = root;     Node* prev = nullptr; ...

Create an in-order threaded binary search tree and perform the traversals.(Double Thread)

 CODE: #include <iostream> using namespace std; struct Node {     int data;     Node* left;     Node* right;     bool leftThread;     bool rightThread; }; Node* createThreadedBST(int arr[], int n) {     Node* root = nullptr;     for (int i = 0; i < n; ++i) {         Node* newNode = new Node;         newNode->data = arr[i];         newNode->left = newNode->right = nullptr;         newNode->leftThread = newNode->rightThread = true;         if (root == nullptr) {             root = newNode;         } else {             Node* current = root;             Node* parent = nullptr;             while (true) {                ...

Create an in-order threaded binary search tree and perform the traversals.(Single thread)

CODE:  #include <iostream> using namespace std; // Node structure for the threaded binary search tree struct Node {     int data;     Node* left;     Node* right;     bool rightThread; // Indicates if the right pointer is a thread }; // Function to create a new node Node* createNode(int data) {     Node* newNode = new Node();     newNode->data = data;     newNode->left = newNode->right = nullptr;     newNode->rightThread = false;     return newNode; } // Function to insert a node into the threaded binary search tree void insert(Node*& root, int data) {     Node* newNode = createNode(data);     Node* curr = root;     Node* prev = nullptr;     while (curr != nullptr) {         prev = curr;         if (data < curr->data) {             if (curr->left != nullp...

Create a BST and find inorder successor and inorder predecessor of specific node.

CODE: #include <iostream> using namespace std; // Node definition struct Node {     int data;     Node* left;     Node* right;     Node(int val) {         data = val;         left = nullptr;         right = nullptr;     } }; // Insertion in BST Node* insert(Node* root, int val) {     if (root == nullptr) {         return new Node(val);     }     if (val < root->data) {         root->left = insert(root->left, val);     } else {         root->right = insert(root->right, val);     }     return root; } // Finding inorder successor Node* findInorderSuccessor(Node* root, Node* target) {     if (target->right != nullptr) {         Node* current = target->right;         while (current->l...

Create Binary Search Tree(BST).Find height of the tree and print leaf nodes. Find mirror image, print original and mirror image using level-wise printing.

CODE:  #include <iostream> #include <queue> using namespace std; // Define the structure for a tree node struct TreeNode {     int data;     TreeNode* left;     TreeNode* right; }; // Function to create a new node TreeNode* createNode(int value) {     TreeNode* newNode = new TreeNode();     newNode->data = value;     newNode->left = nullptr;     newNode->right = nullptr;     return newNode; } // Function to insert a node into the BST TreeNode* insert(TreeNode* root, int value) {     if (root == nullptr) {         return createNode(value);     }     if (value < root->data) {         root->left = insert(root->left, value);     } else if (value > root->data) {         root->right = insert(root->right, value);     }     return root; } // Functio...

Construct Binary Search Tree and find the min and max value of BST.

Code: #include <iostream> using namespace std; // Define the structure for the nodes of the BST struct Node {     int data;     Node* left;     Node* right; }; // Function to create a new node Node* createNode(int value) {     Node* newNode = new Node();     newNode->data = value;     newNode->left = nullptr;     newNode->right = nullptr;     return newNode; } // Function to insert a new node into the BST Node* insertNode(Node* root, int value) {     if (root == nullptr) {         return createNode(value);     }     if (value < root->data) {         root->left = insertNode(root->left, value);     } else if (value > root->data) {         root->right = insertNode(root->right, value);     }     return root; } // Function to find the minimum value in the B...

Accept prefix expressions, and construct a Binary tree and perform recursive and non-recursive traversal.

CODE: #include <iostream> #include <stack> #include <cctype> using namespace std; struct Node { char data; Node* left; Node* right; Node(char value) : data(value), left(nullptr), right(nullptr) {} }; bool isOperand(char c) { return isalnum(c); } Node* constructTree(string prefix) { stack<Node*> st; for (int i = prefix.length() - 1; i >= 0; i--) { char c = prefix[i]; if (isOperand(c)) { st.push(new Node(c)); } else { Node* operand1 = st.top(); st.pop(); Node* operand2 = st.top(); st.pop(); Node* newNode = new Node(c); newNode->left = operand1; newNode->right = operand2; st.push(newNode); } } return st.top(); } void inorderTraversal(Node* root) { if (root) { inorderTraversal(root->left); cout << root->data << " "; inorderTraversal(root->right); } } int main() { string prefixExpression; cout << "Enter the prefix expression: "; cin >> prefixExpression; Node* root = constructTree(prefixExpression); cout ...