Snippets Collections
Declare 
   a integer :=&a;
   i integer;
   
begin
  for i in 1 .. a
   loop
      if (mod(i,2)=0) then
         dbms_output.put_line('even '||i);
     -- else
     -- dbms_output.put_line('odd '||i);
    end if;
  end loop;
end;
/
create or replace procedure swap( num1 in out integer,num2 in out integer)Is 
	temp integer:=0;
begin 
    temp:=num1;
    num1:=num2;
    num2:=temp;  
end;
/
declare 
  a integer:=&a;
  b integer:=&b;
begin 
  dbms_output.put_line('Before swaping '||a||'  '||b);
  swap(a,b);
   dbms_output.put_line('After swaping '||a||'  '||b);

end;
/
  
DECLARE
	em t%rowtype;
	empno t.ename%type;
    
BEGIN
	update  t set ename=upper(ename);
	if sql%found then
   		 DBMS_OUTPUT.PUT_LINE(sql%rowcount||' values updated to uppercase.');
   	else 
   		 dbms_output.put_line('not found');
   end if;
END;
/
DECLARE
    a NUMBER;
BEGIN
    SELECT COUNT(*) INTO a
    FROM t;

    IF a > 0 THEN
        DBMS_OUTPUT.PUT_LINE('At least one row satisfies the condition::  '||a);
    ELSE
        DBMS_OUTPUT.PUT_LINE('No rows satisfy the condition.');
    END IF;
END;
/
declare
	cursor c1 is select * from employ ;
	e employ%rowtype;
begin
	 close c1;
exception 
    when invalid_cursor then
      dbms_output.put_line('invalid cursor');
end;
/
DECLARE
    a NUMBER := &a; -- You can change this value as needed
BEGIN
    UPDATE t SET sal = sal * 1.2 WHERE sal > a;
    DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated.');
END;
/
create or replace trigger setsalzero
before insert on t
for each row
begin
	if :new.sal<0 then
		:new.sal:=0;
	end if;
end;
/
create or replace procedure fibnoci(n in out integer)Is 
  temp integer;
  num1 integer:=0;
  num2 integer:=1;
begin 
   dbms_output.put_line(n);
   for i in 1 ..n
      loop
	dbms_output.put_line(num1||' ');
         temp:=num1;
         num1:=num2;
         num2:=temp+num2;
       
         
    end loop;
end;
/
declare 
  a integer:=&a;
begin 
  fibnoci(a);
end;
/
  
--sum of two numbers
DECLARE
    num1 NUMBER := 10;
    num2 NUMBER := 20;
    sums NUMBER;
BEGIN
    sums := num1 + num2;
    DBMS_OUTPUT.PUT_LINE(sums);
END;
/
CREATE OR REPLACE TRIGGER trg
--before insert ON t
before update of sal on t
 --after insert on t
FOR EACH ROW
BEGIN
    DBMS_OUTPUT.PUT_LINE('A new record is being inserted into the employee table:');
    DBMS_OUTPUT.PUT_LINE('Employee ID: ' || :New.empno);
    DBMS_OUTPUT.PUT_LINE('Employee Name: ' || :New.ename);
    --DBMS_OUTPUT.PUT_LINE('Hire Date: ' || TO_CHAR(:NEW.hiredate, 'YYYY-MM-DD'));
END;
/
CREATE OR REPLACE TRIGGER salary_trigger
BEFORE UPDATE OF sal ON e
FOR EACH ROW
BEGIN
    IF :OLD.sal <> 
	:NEW.sal THEN
        DBMS_OUTPUT.PUT_LINE('Salary changed for employee ' || :OLD.employee_id || ': ' || :OLD.sal || ' -> ' || :NEW.sal);
    END IF;
END;
/
CREATE OR REPLACE PROCEDURE square_cube (n IN NUMBER,square OUT NUMBER,cube OUT NUMBER) IS
BEGIN
    square := n * n;
    cube := n * n * n;
END square_cube;
/
DECLARE
    v_number NUMBER := 4;
    v_square NUMBER;      
    v_cube NUMBER;       
BEGIN
    square_cube(v_number, v_square, v_cube);
    DBMS_OUTPUT.PUT_LINE('Number: ' || v_number);
    DBMS_OUTPUT.PUT_LINE('Square: ' || v_square);
    DBMS_OUTPUT.PUT_LINE('Cube: ' || v_cube);
END;
/
 CREATE OR REPLACE FUNCTION calculate_square (input_number IN NUMBER,output_result OUT NUMBER) RETURN NUMBER IS
BEGIN
    output_result := input_number * input_number;
    RETURN output_result;
END calculate_square;
/
DECLARE
    input_number NUMBER := 5;
    output_result NUMBER;
BEGIN
    output_result := NULL;
    output_result := calculate_square(input_number, output_result);

    DBMS_OUTPUT.PUT_LINE('Input number: ' || input_number);
    DBMS_OUTPUT.PUT_LINE('Square of the input number: ' || output_result);
END;
/

CREATE OR REPLACE Procedure cs(num IN NUMBER,result OUT NUMBER) IS
BEGIN
    result := num * num;
END cs;
/
DECLARE
    input_number NUMBER := 5;
    output_result NUMBER;
BEGIN
    cs(input_number, output_result);
    DBMS_OUTPUT.PUT_LINE('Square of ' || input_number || ': ' || output_result);
END;
/
CREATE OR REPLACE FUNCTION rectangle_area (length IN NUMBER,width IN NUMBER) RETURN NUMBER IS
    area NUMBER;
BEGIN
    area := length * width;
    RETURN area;
END rectangle_area;
/
DECLARE
	length NUMBER := 5;
	width NUMBER := 4;
	area NUMBER;
BEGIN
      area := rectangle_area(length, width);      
      DBMS_OUTPUT.PUT_LINE('Length: ' || length);
      DBMS_OUTPUT.PUT_LINE('Width: ' || width);
      DBMS_OUTPUT.PUT_LINE('Area of the rectangle: ' || area);
  END;
/
DECLARE
    radius NUMBER := &radius;
    area NUMBER;
BEGIN
    area := 3.14159 * radius * radius;
    DBMS_OUTPUT.PUT_LINE('Radius: ' || radius);
    DBMS_OUTPUT.PUT_LINE('Area of the circle: ' || area);
END;
/
 
vector<string> valid;
  void generate(string& s , int open,int close)
  {
    
    if(open==0 && close==0)
    {
        valid.push_back(s);
        return;
    }
    if(open>0)
    {
        s.push_back('(');
        generate(s,open-1,close);
        s.pop_back();
    }
    if(close>0 && open<close)
    {
        s.push_back(')');
        generate(s,open,close-1);
        s.pop_back();
    }
  }
package test;

import java.sql.*;

public class TesteConexao {
    public static void main(String[] args) {
        String url = "jdbc:mysql://root:VCIiGnIpVpAUCfAXxdaPSTvTvAJSNGuE@viaduct.proxy.rlwy.net:21894/railway";
        String usuario = "root";
        String senha = "VCIiGnIpVpAUCfAXxdaPSTvTvAJSNGuE";

        try (Connection conexao = DriverManager.getConnection(url, usuario, senha)) {
            String sql = "SELECT * FROM Funcionarios";
            Statement statement = conexao.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                int id = resultSet.getInt("idFuncionario");
                String nome = resultSet.getString("nomeFuncionario");
                String email = resultSet.getString("email");
                String senhaFuncionario = resultSet.getString("senha");
                String estadoLogin = resultSet.getString("estadoLogin");
                System.out.println("ID: " + id + ", Nome: " + nome + ", Email: " + email + ", Senha: " + senhaFuncionario + ", Estado de Login: " + estadoLogin);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

#include<bits/stdc++.h>
using namespace std;
int sum=0;
vector<int> rev(vector<int>& nums,int f,int r)
{
    if(f<=r)
    {
        swap(nums[f],nums[r]);
        rev(nums,f+1,r-1);
    }
    return nums;
}
int main()
{

    vector<int> v = {4,5,2,6,3,56,5};
    rev(v,0,6);
    for(int i=0;i<=6;++i)
    cout<<v[i]<<" ";
    
}
void f(int n)
{
    n--;
    if(n)
    f(n);
    cout<<"AYUSH"<<endl;
}

void f(int n)
{
    if(n)
    f(n-1);
    cout<<"AYUSH"<<endl;
}
-- Define the function
CREATE OR REPLACE FUNCTION PowerNN (x IN NUMBER, n IN NUMBER) 
RETURN NUMBER 
IS
   result NUMBER;
BEGIN
   result := POWER(x, n);
   RETURN result;
END;
/
-- Use the function
DECLARE
   x NUMBER := &x;  -- Base
   n NUMBER := &n;  -- Exponent
   result NUMBER;
BEGIN
   result := PowerNN(x, n);
   DBMS_OUTPUT.PUT_LINE(x || ' power ' || n || ' is ' || result);
END;
/
10) Online Medical Store ER Diagram:

                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Places    |   |     Product   |
                          |    Order      |   +---------------+
                          +---------------+   | product_id (PK)|
                          | order_id (PK) |   | name          |
                          | customer_id (FK)|  | price         |
                          | order_date    |   | description   |
                          | status        |   +---------------+
                          +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Contains    |   |    Sourced_from  |
                            +---------------+   +-------------------+
                            | order_id (FK) |   | product_id (FK)  |
                            | product_id (FK)|  | pharmacy_id (FK) |
                            | quantity      |   +-------------------+
                            +---------------+
9) Railway Reservation System ER Diagram:

                                    +-------------+
                                    |   Passenger |
                                    +-------------+
                                    | passenger_id (PK)
                                    | name
                                    | age
                                    | gender
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Books     |   |    Train      |
                          |     Ticket    |   +---------------+
                          +---------------+   | train_id (PK) |
                          | ticket_id (PK)|   | name          |
                          | passenger_id (FK)| | source        |
                          | train_id (FK) |   | destination   |
                          | booking_date  |   | departure_time|
                          | status        |   | arrival_time  |
                          +---------------+   | fare          |
                                              +---------------+
8) Flipkart ER Diagram:

                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |   Places      |   |     Product   |
                          |   Order       |   +---------------+
                          +---------------+   | product_id (PK)|
                          | order_id (PK) |   | name          |
                          | customer_id (FK)|  | price         |
                          | order_date    |   | description   |
                          | status        |   +---------------+
                          +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Contains    |   |    Sold_by       |
                            +---------------+   +-------------------+
                            | order_id (FK) |   | product_id (FK)  |
                            | product_id (FK)|  | seller_id (FK)   |
                            | quantity      |   | quantity_sold    |
                            +---------------+   | price            |
                                                +-------------------+
7) Hotel Management System ER Diagram:

                                    +-------------+
                                    |   Guest     |
                                    +-------------+
                                    | guest_id (PK)|
                                    | name        |
                                    | email       |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Books     |   |     Room      |
                          |     Room      |   +---------------+
                          +---------------+   | room_id (PK)  |
                          | booking_id (PK)|   | type          |
                          | guest_id (FK)  |   | capacity      |
                          | room_id (FK)   |   | status        |
                          | check_in_date  |   +---------------+
                          | check_out_date |
                          +---------------+
6) Hospital Management System ER Diagram (Duplicate):

                                    +-------------+
                                    |   Patient   |
                                    +-------------+
                                    | patient_id (PK)|
                                    | name        |
                                    | dob         |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |    Admits     |   |    Doctor     |
                          |               |   +---------------+
                          +---------------+   | doctor_id (PK)|
                          | admit_id (PK) |   | name          |
                          | patient_id (FK)|  | specialization|
                          | doctor_id (FK)|   +---------------+
                          | admit_date    |
                          | discharge_date|
                          +---------------+
5) Hospital Management System ER Diagram:

                                    +-------------+
                                    |   Patient   |
                                    +-------------+
                                    | patient_id (PK)|
                                    | name        |
                                    | dob         |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |    Admits     |   |    Doctor     |
                          |               |   +---------------+
                          +---------------+   | doctor_id (PK)|
                          | admit_id (PK) |   | name          |
                          | patient_id (FK)|  | specialization|
                          | doctor_id (FK)|   +---------------+
                          | admit_date    |
                          | discharge_date|
                          +---------------+
4) Library Management System ER Diagram:
plaintext
Copy code
                                    +-------------+
                                    |    Member   |
                                    +-------------+
                                    | member_id (PK)|
                                    | name        |
                                    | email       |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Borrows   |   |    Book       |
                          |               |   +---------------+
                          +---------------+   | book_id (PK)  |
                          | borrow_id (PK)|   | title         |
                          | member_id (FK)|   | author        |
                          | book_id (FK)  |   | available     |
                          | borrow_date   |   +---------------+
                          | return_date   |
                          +---------------+
3) Online Auction System ER Diagram:

                                    +-------------+
                                    |    User     |
                                    +-------------+
                                    | user_id (PK)|
                                    | username    |
                                    | email       |
                                    | address     |
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |    Places     |   |     Item      |
                          |   Bid         |   +---------------+
                          +---------------+   | item_id (PK)  |
                          | bid_id (PK)   |   | name          |
                          | user_id (FK)  |   | description   |
                          | item_id (FK)  |   | starting_price|
                          | amount        |   | current_price |
                          +---------------+   +---------------+
2) Online Banking System ER Diagram:

                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |   Owns Account |   |    Account    |
                          |               |   +---------------+
                          +---------------+   | account_id (PK)|
                          | account_id (PK)|   | balance       |
                          | customer_id (FK)|  | type          |
                          | balance        |   | status        |
                          +---------------+   +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Performs    |   |    Transaction    |
                            +---------------+   +-------------------+
                            | transaction_id(PK)| transaction_id (PK)|
                            | account_id (FK)|   | account_id (FK)   |
                            | date          |   | type              |
                            | amount        |   | amount            |
                            +---------------+   +-------------------+
                                    +-------------+
                                    |   Customer  |
                                    +-------------+
                                    | customer_id (PK)
                                    | name
                                    | email
                                    | address
                                    +-------------+
                                            |
                                            |
                                  +---------+---------+
                                  |                   |
                          +-------+-------+   +-------+-------+
                          |     Places    |   |     Book      |
                          |    Order      |   +---------------+
                          +---------------+   | book_id (PK)  |
                          | order_id (PK) |   | title         |
                          | customer_id (FK)|  | author        |
                          | order_date    |   | price         |
                          | status        |   | publication_date|
                          +---------------+   | genre         |
                                              +---------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                            +-------+-------+   +-----------+-------+
                            |   Contains    |   |    Written_by    |
                            +---------------+   +------------------+
                            | order_id (FK) |   | author_id (PK)   |
                            | book_id (FK)  |   | name             |
                            | quantity      |   | country          |
                            +---------------+   +------------------+
1. PL/SQL Program to demonstrate Strings:
DECLARE
    str1 VARCHAR2(50) := 'Hello';
    str2 VARCHAR2(50) := 'World';
    concatenated_str VARCHAR2(100);
BEGIN
    -- Concatenation
    concatenated_str := str1 || ' ' || str2;
    DBMS_OUTPUT.PUT_LINE('Concatenated String: ' || concatenated_str);

    -- Length
    DBMS_OUTPUT.PUT_LINE('Length of str1: ' || LENGTH(str1));

    -- Substring
    DBMS_OUTPUT.PUT_LINE('Substring of concatenated_str: ' || SUBSTR(concatenated_str, 4, 5));

    -- Uppercase
    DBMS_OUTPUT.PUT_LINE('Uppercase of str1: ' || UPPER(str1));

    -- Lowercase
    DBMS_OUTPUT.PUT_LINE('Lowercase of str2: ' || LOWER(str2));
END;

2. DML Commands:
//INSERT: Adds new records to a table.
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
//UPDATE: Modifies existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
//DELETE: Removes existing records from a table.
DELETE FROM table_name
WHERE condition;
//SELECT: Retrieves data from one or more tables.
SELECT column1, column2, ...
FROM table_name
WHERE condition;

3. Solutions for the provided relations and queries:

-- i. Create the given relations and insert at least 5 records into each relation
CREATE TABLE Employees (
    EmployeeID NUMBER PRIMARY KEY,
    FirstName VARCHAR2(50),
    LastName VARCHAR2(50),
    ProjectID NUMBER,
    Salary NUMBER,
    CONSTRAINT fk_projects FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID)
);

CREATE TABLE Projects (
    ProjectID NUMBER PRIMARY KEY,
    ProjectName VARCHAR2(50),
    StartDate DATE,
    EndDate DATE,
    ManagerID NUMBER,
    CONSTRAINT fk_employees FOREIGN KEY (ManagerID) REFERENCES Employees(EmployeeID)
);

-- ii. Find projects managed by employees in a specific department. (using nested queries)
SELECT * 
FROM Projects 
WHERE ManagerID IN (
    SELECT EmployeeID 
    FROM Employees 
    WHERE DepartmentID = 'specific_department_id'
);

-- iii. Find projects where the manager's salary is higher than the overall average salary.
SELECT * 
FROM Projects 
WHERE ManagerID IN (
    SELECT EmployeeID 
    FROM Employees 
    WHERE Salary > (SELECT AVG(Salary) FROM Employees)
);

-- iv. List all employees their names concatenating both FirstName & LastName
SELECT EmployeeID, FirstName || ' ' || LastName AS FullName
FROM Employees;

-- v. List employee First names contains at least 5 characters.
SELECT * 
FROM Employees 
WHERE LENGTH(FirstName) >= 5;

-- vi. Reallocate to another project whose salary is greater than 20K.
UPDATE Employees 
SET ProjectID = 'new_project_id' 
WHERE Salary > 20000;
1. PL/SQL Program to find if a given number is even or odd:
DECLARE
    num NUMBER := 10; -- Change the number here
BEGIN
    IF MOD(num, 2) = 0 THEN
        DBMS_OUTPUT.PUT_LINE(num || ' is even');
    ELSE
        DBMS_OUTPUT.PUT_LINE(num || ' is odd');
    END IF;
END;

2. Examples of creating a table with NULL, NOT NULL, CHECK constraints:

-- Table with NULL constraint
CREATE TABLE example_null (
    id NUMBER PRIMARY KEY,
    name VARCHAR2(50) NULL
);

-- Table with NOT NULL constraint
CREATE TABLE example_not_null (
    id NUMBER PRIMARY KEY,
    name VARCHAR2(50) NOT NULL
);

-- Table with CHECK constraint
CREATE TABLE example_check (
    id NUMBER PRIMARY KEY,
    age NUMBER CHECK (age >= 18)
);


3. Solutions for the provided relations and queries:
-- Create Employees table
CREATE TABLE Employees (
    Employee_ID NUMBER PRIMARY KEY,
    Emp_Name VARCHAR2(50),
    Skill_ID NUMBER,
    Salary NUMBER,
    CONSTRAINT fk_skills FOREIGN KEY (Skill_ID) REFERENCES Skills(SkillID)
);
-- Create Skills table
CREATE TABLE Skills (
    SkillID NUMBER PRIMARY KEY,
    SkillName VARCHAR2(50),
    Description VARCHAR2(100)
);
-- Insert sample records into Employees table
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (1, 'John', 1, 5000);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (2, 'Alice', 2, 6000);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (3, 'Bob', 1, 5500);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (4, 'Emma', 3, 7000);
INSERT INTO Employees (Employee_ID, Emp_Name, Skill_ID, Salary) VALUES (5, 'Mike', NULL, 4500);

-- Insert sample records into Skills table
INSERT INTO Skills (SkillID, SkillName, Description) VALUES (1, 'Java', 'Programming language');
INSERT INTO Skills (SkillID, SkillName, Description) VALUES (2, 'SQL', 'Database querying language');
INSERT INTO Skills (SkillID, SkillName, Description) VALUES (3, 'Python', 'High-level programming language');

-- ii. Find employees who have not acquired any skills
SELECT * FROM Employees WHERE Skill_ID IS NULL;

-- iii. Find employees with the highest salary
SELECT * FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);

-- iv. Find the average salary of employees in each department
-- Assuming there's a department_id column in the Employees table
SELECT department_id, AVG(Salary) AS Avg_Salary FROM Employees GROUP BY department_id;

-- v. Update the salary of an employee
UPDATE Employees SET Salary = 6000 WHERE Employee_ID = 1;

-- vi. Retrieve skills that are possessed by at least two employees
SELECT SkillID, SkillName FROM Skills WHERE SkillID IN (
    SELECT Skill_ID FROM Employees GROUP BY Skill_ID HAVING COUNT(*) >= 2
);
**Set-1:**
```
               +------------------+
               |      Nurse       |
               +------------------+
               | nurse_id (PK)    |
               | nurse_name       |
               | registered       |
               | department_id (FK)|
               +------------------+
                        |
                        |
                        | works in
                        |
                        v
               +------------------+
               |    Department    |
               +------------------+
               | department_id (PK)|
               | department_name  |
               +------------------+
```

**Set-2:**
```
               +------------------+
               |     Student      |
               +------------------+
               | student_id (PK)  |
               | student_name     |
               | course_id (FK)   |
               +------------------+
                        |
                        |
                        | enrolled in
                        |
                        v
               +------------------+
               |      Course      |
               +------------------+
               | course_id (PK)   |
               | course_name      |
               +------------------+
```

**Set-3:**
```
               +------------------+
               |    Physician     |
               +------------------+
               | physician_id (PK)|
               | physician_name   |
               | department_id (FK)|
               +------------------+
                        |
                        |
                        | works in
                        |
                        v
               +------------------+
               |    Department    |
               +------------------+
               | department_id (PK)|
               | department_name  |
               +------------------+
```

**Set-4:**
```
               +------------------+
               |     Supplier     |
               +------------------+
               | supplier_id (PK) |
               | supplier_name    |
               +------------------+
                        |
                        |
                        | supplies
                        |
                        v
               +------------------+
               |      Item        |
               +------------------+
               | item_id (PK)     |
               | item_name        |
               | supplier_id (FK) |
               +------------------+
```

**Set-5:**
```
               +------------------+
               |     User         |
               +------------------+
               | user_id (PK)     |
               | username         |
               +------------------+
                        |
                        |
                        | makes order
                        |
                        v
               +------------------+
               |     Order        |
               +------------------+
               | order_id (PK)    |
               | user_id (FK)     |
               +------------------+
```

**Set-6:**
```
               +------------------+
               |     Supplier     |
               +------------------+
               | supplier_id (PK) |
               | supplier_name    |
               +------------------+
                        |
                        |
                        | supplies
                        |
                        v
               +------------------+
               |      Item        |
               +------------------+
               | item_id (PK)     |
               | item_name        |
               | supplier_id (FK) |
               +------------------+
```

**Set-7:**
```
               +------------------+
               |     Student      |
               +------------------+
               | student_id (PK)  |
               | student_name     |
               | course_id (FK)   |
               +------------------+
                        |
                        |
                        | enrolled in
                        |
                        v
               +------------------+
               |      Course      |
               +------------------+
               | course_id (PK)   |
               | course_name      |
               +------------------+
```

**Set-8:**
```
               +------------------+
               |     Supplier     |
               +------------------+
               | supplier_id (PK) |
               | supplier_name    |
               +------------------+
                        |
                        |
                        | supplies
                        |
                        v
               +------------------+
               |      Item        |
               +------------------+
               | item_id (PK)     |
               | item_name        |
               | supplier_id (FK) |
               +------------------+
```

**Set-9:**
```
               +------------------+
               |     Employee     |
               +------------------+
               | emp_id (PK)      |
               | emp_name         |
               | job              |
               | hiredate         |
               | sal              |
               | comm             |
               | dept_no (FK)     |
               +------------------+
                        |
                        |
                        | works in
                        |
                        v
               +------------------+
               |    Department    |
               +------------------+
               | dept_no (PK)     |
               | dept_name        |
               | location         |
               +------------------+
```

**Set-10:**
```
               +------------------+
               |     Employee     |
               +------------------+
               | emp_no (PK)      |
               | emp_name         |
               | job              |
               | hiredate         |
               | sal              |
               | comm             |
              


/////SET-10
                                        +--------------+
                                        |   Customer   |
                                        +--------------+
                                        | customer_id (PK)
                                        | name
                                        | email
                                        | address
                                        +--------------+
                                                |
                                                |
                                    +-----------+-----------+
                                    |                       |
                        +-----------+-----------+   +-------+-------+
                        |      Makes Purchase     |   |   Manages    |
                        |    +--------------+    |   |    Payment   |
                        +----|     Order    |<---+   +-------+-------+
                             +--------------+            |    
                             | order_id (PK)             |    
                             | customer_id (FK)          |    
                             | order_date                |
                             +--------------+            |
                                                 +--------+---------+
                                                 |                  |
                                       +---------+---------+   +----v----+
                                       |     Contains     |   | Payment |
                                       +-----------------+   +---------+
                                       | order_id (FK)  |   
                                       | product_id (FK)|
                                       | quantity        |
                                       +-----------------+
                                                      
                           +-------------+             +----------------+
                           |   Product   |             |    Pharmacy    |
                           +-------------+             +----------------+
                           | product_id (PK)|         | pharmacy_id (PK)|
                           | name          |         | name           |
                           | price         |         | location       |
                           | manufacturer_id (FK)|    +----------------+
                           +-------------+    
                                   |
                                   |
                           +-------+--------+
                           |  Manufactures  |
                           +----------------+
                           | manufacturer_id (PK)|
                           | name               |
                           | country            |
                           +-------------------+
A. List the details of the employees in ascending order of the Department numbers and descending order of Jobs:
SELECT *
FROM emp_details
ORDER BY dept_no ASC, job DESC;

B. Query for adding a new column called PF:
ALTER TABLE emp_details ADD PF NUMBER;

C. List the employees who joined before 1981:
SELECT *
FROM emp_details
WHERE hiredate < TO_DATE('1981-01-01', 'YYYY-MM-DD');
D. Display employees whose salary is between 10,000 and 20,000:
SELECT *
FROM emp_details
WHERE sal BETWEEN 10000 AND 20000;

E. Display employees whose name starts with 'S':
SELECT *
FROM emp_details
WHERE emp_name LIKE 'S%';

F. Display employees who were born between January 1st, 1970, and January 1st, 1990:
SELECT *
FROM emp_details
WHERE EXTRACT(YEAR FROM hiredate) BETWEEN 1970 AND 1990;
G. Syntax of DDL Commands:
//CREATE: Used to create a new database object like a table, view, or index.
CREATE TABLE table_name (column1 datatype, column2 datatype, ...);
//ALTER: Used to modify an existing database object like adding, modifying, or dropping columns.
ALTER TABLE table_name ADD column_name datatype;
//DROP: Used to delete an existing database object like a table, view, or index.
DROP TABLE table_name;
H. PL/SQL Program to find the maximum number among three numbers:
DECLARE
    num1 NUMBER := 10;
    num2 NUMBER := 20;
    num3 NUMBER := 30;
    max_num NUMBER;
BEGIN
    max_num := GREATEST(num1, num2, num3);
    DBMS_OUTPUT.PUT_LINE('Maximum number: ' || max_num);
END;

I. PL/SQL Program to print the salary changes when the salary is changed using a Trigger:
CREATE OR REPLACE TRIGGER salary_change_trigger
BEFORE UPDATE OF sal ON emp_details
FOR EACH ROW
BEGIN
    DBMS_OUTPUT.PUT_LINE('Old Salary: ' || :OLD.sal);
    DBMS_OUTPUT.PUT_LINE('New Salary: ' || :NEW.sal);
END;

J. Find the maximum average salary drawn for each job except for 'President':
SELECT job, MAX(AVG(sal)) AS max_avg_salary
FROM emp_details
WHERE job != 'President'
GROUP BY job;

Entities:

Employee (emp_no, emp_name, job, hiredate, mgr, sal, comm, dept_no)
Department (dept_no, dept_name, location)
Relationships:

Employee works in Department (many-to-one)
Employee (mgr) manages other Employees (one-to-many)

            +------------------+
            |     Employee     |
            +------------------+
            | emp_no (PK)      |
            | emp_name         |
            | job              |
            | hiredate         |
            | sal              |
            | comm             |
            | dept_no (FK)     |
            +------------------+
                    |
                    |
                    | works in
                    |
                    v
            +------------------+
            |   Department     |
            +------------------+
            | dept_no (PK)     |
            | dept_name        |
            | location         |
            +------------------+
1. Retrieve all the names and their respective salaries:
SELECT Emp_Name, Salary FROM Employee;

2. Retrieve the names of employees whose salary is greater than 5000:
SELECT Emp_Name FROM Employee WHERE Salary > 5000;
3. Display the names and locations of all departments:
SELECT Dname, Location FROM Department;

4. Display the names of employees who work in the sales department:
SELECT e.Emp_Name 
FROM Employee e 
JOIN Department d ON e.Dept_no = d.Dept_No 
WHERE d.Dname = 'Sales';

5. Display the total number of employees in each department:
SELECT d.Dname, COUNT(e.Emp_id) AS Total_Employees
FROM Department d
LEFT JOIN Employee e ON d.Dept_No = e.Dept_no
GROUP BY d.Dname;

6. Update the salary of employee with empid 3 to 8000:
UPDATE Employee SET Salary = 8000 WHERE Emp_id = 3;

7. Delete the employee with empid=4:
DELETE FROM Employee WHERE Emp_id = 4;

8. Display the highest salary in each department:
SELECT d.Dname, MAX(e.Salary) AS Highest_Salary
FROM Department d
LEFT JOIN Employee e ON d.Dept_No = e.Dept_no
GROUP BY d.Dname;

9. Create a view to list the employees in ascending order of their Salaries:
CREATE VIEW Employee_Salary_View AS
SELECT * FROM Employee ORDER BY Salary ASC;

10. Create a trigger before insert on emp table to make salary zero if less than zero:
CREATE OR REPLACE TRIGGER check_salary
BEFORE INSERT ON Employee
FOR EACH ROW
BEGIN
    IF :NEW.Salary < 0 THEN
        :NEW.Salary := 0;
    END IF;
END;

11. Aggregate Functions:
//SUM: Calculates the sum of values in a column.
SELECT SUM(Salary) FROM Employee;
//AVG: Calculates the average of values in a column.
SELECT AVG(Salary) FROM Employee;
//COUNT: Counts the number of rows in a result set or the number of non-null values in a column.
SELECT COUNT(*) FROM Employee;
//MAX: Returns the maximum value in a column.
SELECT MAX(Salary) FROM Employee;
//MIN: Returns the minimum value in a column.
SELECT MIN(Salary) FROM Employee;

12. E-R Diagram for Mobile Billing System:
Entities:

Customer (Customer_ID, Name, Address, Phone_Number)
Billing Details (Bill_ID, Customer_ID, Bill_Amount, Bill_Date)
Plan Details (Plan_ID, Plan_Name, Plan_Type, Monthly_Price)
Cities of Service (City_ID, City_Name, Service_Area)
Relationships:

Customer makes Billing Details (one-to-many)
Customer subscribes to Plan (many-to-one)
Plan is available in Cities of Service (many-to-many)
1) ER Diagram for Online Medical Store:
Entities: User, Product, Order, Prescription, Pharmacy, Payment, Review
Relationships:

User places Order (one-to-many)
Order contains Product (many-to-many)
Prescription is related to User (many-to-one)
Product is sold by Pharmacy (many-to-one)
Payment is related to Order (one-to-one)
User writes Review for Product (one-to-many)

2) Trigger to Update Project Budget When Employee Salary is Increased:

CREATE OR REPLACE TRIGGER update_project_budget
AFTER UPDATE OF salary ON Employees
FOR EACH ROW
BEGIN
    UPDATE Projects
    SET budget = budget + (:new.salary - :old.salary)
    WHERE manager_id = :new.employee_id;
END;


3) SQL Queries:
A)
SELECT Department, MAX(Budget) AS Highest_Budget
FROM Projects
GROUP BY Department;
B)
SELECT SUM(Budget) AS Total_Budget FROM Projects;
C)
CREATE VIEW HighSalaryEmployees AS
SELECT * FROM Employees WHERE Salary > 80000;
D)
SELECT * FROM Employees WHERE Salary BETWEEN 60000 AND 80000;
E)
DELETE FROM Employees WHERE Salary < 60000;
F)
SELECT * FROM Projects WHERE Budget > (SELECT AVG(Budget) FROM Projects);
G)
SELECT * FROM Projects WHERE ProjectName LIKE 'Web%' ORDER BY Budget;
H)
SELECT Department, SUM(Budget) AS Total_Budget
FROM Projects
GROUP BY Department
ORDER BY Total_Budget;
1) ER Diagram for Railway Reservation System:
Entities: Train, Passenger, Ticket, Route, Station, Reservation, Payment
Relationships:

Passenger books Ticket (one-to-many)
Ticket is for Train (many-to-one)
Ticket is for Passenger (many-to-one)
Train travels on Route (many-to-many)
Route includes Station (one-to-many)
Reservation is related to Ticket (one-to-one)
Payment is related to Ticket (one-to-one)

2) PL/SQL Program to Calculate Sum of Digits of any Number:

CREATE OR REPLACE PROCEDURE calculate_digit_sum(
    num IN NUMBER,
    sum OUT NUMBER
) AS
    total_sum NUMBER := 0;
BEGIN
    WHILE num != 0 LOOP
        total_sum := total_sum + MOD(num, 10);
        num := num / 10;
    END LOOP;
    sum := total_sum;
END;


3) SQL Queries:
A
SELECT * FROM Employees WHERE Department = 'IT';
B)
UPDATE Employees SET Salary = NEW_SALARY WHERE EmployeeID = 3;
C)
SELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);
D)
SELECT * FROM Employees WHERE Department = 'IT' AND Salary > 70000;
E)
SELECT SUM(Budget) AS Total_Budget FROM Projects WHERE Department = 'Marketing';
F)
SELECT * FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees);
G)
SELECT E.EmployeeID, E.EmployeeName, P.ProjectName
FROM Employees E
JOIN Project_Assignment PA ON E.EmployeeID = PA.EmployeeID
JOIN Projects P ON PA.ProjectID = P.ProjectID;
H)
SELECT Department, COUNT(EmployeeID) AS Total_Employees
FROM Employees
GROUP BY Department;
1) ER Diagram for Flipkart:
Entities: User, Product, Order, Payment, Cart, Review
Relationships:

User places Order (one-to-many)
User adds Product to Cart (one-to-many)
Order contains Product (many-to-many)
Payment is related to Order (one-to-one)
User writes Review for Product (one-to-many)


2) Trigger to Update Instructor's Name in Courses Table:

CREATE OR REPLACE TRIGGER update_instructor_name
AFTER UPDATE OF instructor_name ON Students
FOR EACH ROW
BEGIN
    UPDATE Courses
    SET instructor_name = :new.instructor_name
    WHERE instructor_id = :new.student_id;
END;


3) SQL Queries:
A)
ALTER TABLE Students
ADD Email VARCHAR2(100);
B)
UPDATE Students
SET Email = 'example@email.com'
WHERE StudentID = 12345;
C)
SELECT CourseID, CourseName
FROM Courses
WHERE CourseID IN (
    SELECT CourseID
    FROM Enrollments
    WHERE StudentID IN (
        SELECT StudentID
        FROM Students
        WHERE GPA < 2.5
    )
);
D)
SELECT CourseID, CourseName
FROM Courses
WHERE CreditHours > (
    SELECT AVG(CreditHours)
    FROM Courses
);
E)
SELECT *
FROM Students
WHERE LastName LIKE '%son';
F)
SELECT BirthDate, COUNT(*)
FROM Students
GROUP BY BirthDate;
G)
SELECT BirthDate
FROM Students
GROUP BY BirthDate
HAVING COUNT(*) > 1;
H)
UPDATE Courses
SET Instructor = 'New Instructor'
WHERE CourseID = 'SpecificCourseID';
1.ER Diagram for Online Food Order System:
Entities: Customer, Restaurant, Order, Food Item, Delivery, Payment, Review
Relationships:

Customer places Order (one-to-many)
Order contains Food Item (many-to-many)
Order is delivered by Delivery (one-to-one)
Payment is related to Order (one-to-one)
Customer writes Review for Restaurant (one-to-many)


2.PL/SQL Procedure to Calculate Square of a Number:

CREATE OR REPLACE PROCEDURE calculate_square(
    num IN NUMBER,
    square OUT NUMBER
) AS
BEGIN
    square := num * num;
END;


3.SQL Queries:
A)
SELECT supplier_number, supplier_name 
FROM Suppliers 
WHERE supplier_name LIKE 'R%';
B)
SELECT supplier_name 
FROM Suppliers 
WHERE item_supplied = 'Processor' AND city = 'Delhi';
C)
SELECT DISTINCT S.supplier_name 
FROM Suppliers S 
JOIN Suppliers R ON S.item_supplied = R.item_supplied 
WHERE R.supplier_name = 'Ramesh';
D)
UPDATE Items 
SET item_price = item_price + 200 
WHERE item_name = 'Keyboard';
E)
SELECT supplier_number, supplier_name, item_price 
FROM Suppliers 
WHERE city = 'Delhi' 
ORDER BY item_price ASC;
F)
ALTER TABLE Suppliers 
ADD contact_no VARCHAR2(20);
G)
DELETE FROM Items 
WHERE item_price = (SELECT MIN(item_price) FROM Items);
H)
CREATE VIEW SupplierDetails AS
SELECT supplier_number, supplier_name 
FROM Suppliers;
1) ER Diagram for Online Food Order System:

Entities: Customer, Restaurant, Order, Food Item, Delivery, Payment, Review
Relationships:
Customer places Order (one-to-many)
Order contains Food Item (many-to-many)
Order is delivered by Delivery (one-to-one)
Payment is related to Order (one-to-one)
Customer writes Review for Restaurant (one-to-many)

2) PL/SQL Procedure to Calculate Square of a Number:

CREATE OR REPLACE PROCEDURE calculate_square(
    num IN NUMBER,
    square OUT NUMBER
) AS
BEGIN
    square := num * num;
END;
3) SQL Queries:
A) SELECT supplier_number, supplier_name FROM Suppliers WHERE supplier_name LIKE 'R%';
B)
SELECT supplier_name 
FROM Suppliers 
WHERE item_supplied = 'Processor' AND city = 'Delhi';
C)
SELECT DISTINCT S.supplier_name 
FROM Suppliers S 
JOIN Suppliers R ON S.item_supplied = R.item_supplied 
WHERE R.supplier_name = 'Ramesh';
D) UPDATE Items SET item_price = item_price + 200 WHERE item_name = 'Keyboard';
E)
SELECT supplier_number, supplier_name, item_price 
FROM Suppliers 
WHERE city = 'Delhi' 
ORDER BY item_price ASC;
F) ALTER TABLE Suppliers ADD contact_no VARCHAR2(20);
G)
DELETE FROM Items 
WHERE item_price = (SELECT MIN(item_price) FROM Items);
H)
CREATE VIEW SupplierDetails AS
SELECT supplier_number, supplier_name 
FROM Suppliers;
1) ER Diagram for Hospital Management System:

Entities: Patient, Doctor, Nurse, Department, Appointment, Prescription, Procedure
Relationships:
Doctor treats Patient (many-to-many)
Nurse cares for Patient (many-to-many)
Department employs Doctor/Nurse (one-to-many)
Appointment scheduled between Doctor and Patient (one-to-many)


2) PL/SQL Function Program to Use IN, OUT:

//CREATE OR REPLACE FUNCTION 
CREATE OR REPLACE FUNCTION calculate_area_length_width(
    length_val IN NUMBER,
    width_val IN NUMBER,
    area_val OUT NUMBER
) RETURN NUMBER
IS
BEGIN
    area_val := length_val * width_val;
    RETURN area_val;
END;
/

3) SQL Queries:
A)
DESCRIBE nurse;
DESCRIBE physician;
B) SELECT name FROM physician WHERE position = 'Senior Attending';
C) SELECT name FROM physician WHERE department_id IS NULL;
D) SELECT name FROM physician WHERE position LIKE 'Surgical%';
E)
SELECT P.name 
FROM physician P 
JOIN nurse N ON P.position = N.position 
WHERE N.name = 'Carla Espinosa';
F) ALTER TABLE physician MODIFY ssn VARCHAR2(20);
G) DELETE FROM department WHERE departmentid = 1;
H)
CREATE VIEW AttendingPhysicians AS
SELECT name, ssn 
FROM physician 
WHERE position = 'Attending Physician';
1) ER Diagram for Library Management System:

Entities: Book, Author, Publisher, Member, Loan, Reservation, Genre
Relationships:
Member borrows Book (many-to-many)
Book is written by Author (many-to-many)
Book is published by Publisher (many-to-one)
Reservation is placed by Member (one-to-many)

2) PL/SQL Function to Calculate Area of Rectangle:
CREATE OR REPLACE FUNCTION calculate_rectangle_area(
    length IN NUMBER,
    width IN NUMBER
) RETURN NUMBER IS
    area NUMBER;
BEGIN
    area := length * width;
    RETURN area;
END;

3) SQL Queries:
A) SELECT * FROM Employees;
B) SELECT salary FROM Employees;
C) SELECT DISTINCT designation FROM Employees;
D) SELECT emp_name, salary * 1.15 AS increased_salary FROM Employees;
E) SELECT emp_id, salary, dept_id FROM Employees;
F) SELECT * FROM Employees WHERE YEAR(join_date) < 1991;
G) SELECT AVG(salary) AS average_salary FROM Employees WHERE designation = 'ANALYST';
H)CREATE VIEW EmployeesWithThirdLetterA AS
  SELECT * FROM Employees 
  WHERE SUBSTRING(name, 3, 1) = 'A' AND salary BETWEEN 2600 AND 3200;
1) ER Diagram for Online Auction System:

Entities: User, Item, Bid, Auction, Payment, Category
Relationships:
User places Bid (one-to-many)
Item is listed in Auction (many-to-one)
User makes Payment (one-to-one)
Item belongs to Category (many-to-many)

2) PL/SQL Program to Find Area of Circle:

CREATE OR REPLACE PROCEDURE calculate_circle_area(
    radius IN NUMBER,
    area OUT NUMBER
) AS
BEGIN
    area := 3.14 * radius * radius;
END;


3) SQL Queries:
a) UPDATE Physicians SET position = 'Senior Staff Internist' WHERE name = 'John Dorian';

b) CREATE VIEW NonInternPhysicians AS SELECT name, position FROM Physicians WHERE position <> 'Intern';

c) SELECT * FROM Physicians WHERE position = 'Attending Physician';

d) SELECT P.name AS physician_name, D.name AS department_name FROM Physicians P JOIN Departments D ON P.department_id = D.id;

e) SELECT name FROM Physicians WHERE position LIKE '%Physician%';

f) SELECT N.name FROM Nurses N JOIN Departments D ON N.department_id = D.id WHERE N.registered = 'Y' AND D.name = 'Surgery';

g) SELECT D.name AS department_name, COUNT(*) AS total_physicians FROM Physicians P JOIN Departments D ON P.department_id = D.id GROUP BY D.name;
                                           
h) DELETE FROM Nurses WHERE registered = 'N';
SET-2

ER Diagram for Online Banking:

Entities: Customer, Account, Transaction, Bank, Branch, Loan
Relationships:
Customer owns Account (one-to-many)
Account has Transaction (one-to-many)
Bank has Branches (one-to-many)
Customer takes Loan (one-to-many)

2.PL/SQL Procedure with OUT Parameter to Calculate Square and Cube:
CREATE OR REPLACE PROCEDURE calculate_square_cube(
    num IN NUMBER,
    square OUT NUMBER,
    cube OUT NUMBER
) AS
BEGIN
    square := num * num;
    cube := num * num * num;
END;

3.SQL Queries:
A. SELECT * FROM Students WHERE state NOT IN ('Telangana', 'AndhraPradesh');

B. CREATE VIEW TelanganaStudents AS SELECT Sid, Sname FROM Students WHERE state = 'Telangana';

C. SELECT * FROM Students WHERE gender = 'female' AND course = 'Compcourse' AND category = 'OBC';

D. SELECT Sid, Sname, (marks_obtained / total_marks) * 100 AS percentage FROM Results;

E. SELECT * FROM Students ORDER BY Sname, course ASC;

F. DELETE FROM Students WHERE course = 'Compcourse' AND YEAROFBIRTH > 2002;

G. ALTER TABLE Students MODIFY (state VARCHAR2(40));

H. SELECT Sname FROM Students WHERE LENGTH(Sname) = 5;
SET-1

1.ER Diagram for Online Book Store:

	Entities: User, Book, Author, Publisher, Order, Payment, Review
	Relationships:
	User buys Book (one-to-many)
	Book is written by Author (many-to-many)
	Book is published by Publisher (many-to-one)
	Order contains Book (one-to-many)
	Payment is related to Order (one-to-one)
	User writes Review for Book (one-to-many)
2.PL/SQL Function to Calculate Factorial:


CREATE OR REPLACE FUNCTION factorial(n IN NUMBER) RETURN NUMBER IS
    result NUMBER := 1;
BEGIN
    FOR i IN 1..n LOOP
        result := result * i;
    END LOOP;
    RETURN result;
END;
3.SQL Queries:
A. SELECT * FROM Nurses WHERE registered = 'Y';

B. ALTER TABLE Nurses ADD phone VARCHAR2(20);

C. UPDATE Nurses SET registered = 'N' WHERE name = 'Laverne Roberts';

D. CREATE VIEW NursePositions AS SELECT name, position FROM Nurses;

E. SELECT name, position FROM Nurses UNION ALL SELECT name, position FROM Physicians;

F. SELECT D.name AS department_name, E.name AS department_head FROM Departments D JOIN Employees E ON D.head_id = E.id;

G. SELECT N.name AS nurse_name, D.name AS department_name FROM Nurses N JOIN Departments D ON N.department_id = D.id;

H. DELETE FROM Departments WHERE id = 2;
class ArrayStack<T> {
    private T[] stackArray;
    private int top;
    private int maxSize;

    @SuppressWarnings("unchecked")
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stackArray = (T[]) new Object[maxSize];
        this.top = -1;
    }

    public void push(T item) {
        if (isFull()) {
            System.out.println("Stack overflow");
            return;
        }
        stackArray[++top] = item;
    }

    public T pop() {
        if (isEmpty()) {
            System.out.println("Stack underflow");
            return null;
        }
        return stackArray[top--];
    }

    public T peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty");
            return null;
        }
        return stackArray[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

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

public class GenericStackDemo {
    public static void main(String[] args) {
        // Using ArrayStack
        ArrayStack<Integer> integerStack = new ArrayStack<>(5);
        integerStack.push(10);
        integerStack.push(20);
        System.out.println("Popped integer: " + integerStack.pop());
        System.out.println("Peek integer: " + integerStack.peek());

        ArrayStack<Double> doubleStack = new ArrayStack<>(5);
        doubleStack.push(3.14);
        doubleStack.push(6.28);
        System.out.println("Popped double: " + doubleStack.pop());
        System.out.println("Peek double: " + doubleStack.peek());

        ArrayStack<String> stringStack = new ArrayStack<>(5);
        stringStack.push("Hello");
        stringStack.push("World");
        System.out.println("Popped string: " + stringStack.pop());
        System.out.println("Peek string: " + stringStack.peek());
    }
}
 import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Product {
    private int id;
    private String name;
    private double price;
    private String type;
    private double rating;

    public Product(int id, String name, double price, String type, double rating) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.type = type;
        this.rating = rating;
    }

    public double getRating() {
        return rating;
    }

    public double getPrice() {
        return price;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", type='" + type + '\'' +
                ", rating=" + rating +
                '}';
    }
}

public class ProductStreamExample {
    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
                new Product(1, "Laptop", 1500.0, "Electronics", 4.5),
                new Product(2, "Smartphone", 800.0, "Electronics", 4.2),
                new Product(3, "Watch", 300.0, "Fashion", 3.8),
                new Product(4, "Headphones", 100.0, "Electronics", 4.8),
                new Product(5, "Shoes", 50.0, "Fashion", 3.5),
                new Product(6, "Camera", 2000.0, "Electronics", 4.7)
        );

        // i) Find all the products having rating between 4 and 5
        List<Product> productsRatingBetween4And5 = products.stream()
                .filter(p -> p.getRating() >= 4 && p.getRating() <= 5)
                .collect(Collectors.toList());
        System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5);
		System.out.println();
        
        // ii) Find first n products having price > 10000
        int n = 2;
        List<Product> firstNProductsPriceGreaterThan1000 = products.stream()
                .filter(p -> p.getPrice() > 1000)
                .limit(n)
                .collect(Collectors.toList());
        System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000);
		System.out.println();
        
        // iii) Find the number of products under each type (map containing type and count)
        Map<String, Long> productCountByType = products.stream()
		.collect(Collectors.groupingBy(Product::getType, Collectors.counting()));
        System.out.println("Number of products under each type: " + productCountByType);
		System.out.println();
        
        // iv) Find average rating of products with type = "Electronics"
        double averageRatingElectronics = products.stream()
                .filter(p -> p.getType().equals("Electronics"))
                .mapToDouble(Product::getRating)
                .average()
                .orElse(0.0);
        System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics);
    }
}
star

Sat Jun 08 2024 02:27:01 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:24:12 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:23:20 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:22:13 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:21:35 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:20:46 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:19:26 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:14:53 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:13:52 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:12:25 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:09:43 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:07:15 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:06:02 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:05:08 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:03:06 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 02:00:56 GMT+0000 (Coordinated Universal Time)

@signup

star

Sat Jun 08 2024 00:45:15 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sat Jun 08 2024 00:37:29 GMT+0000 (Coordinated Universal Time)

@gabriellesoares

star

Fri Jun 07 2024 22:54:08 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 21:53:11 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 07 2024 20:10:48 GMT+0000 (Coordinated Universal Time) https://python.land/virtual-environments/virtualenv

@vladk

star

Fri Jun 07 2024 19:38:55 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jun 07 2024 19:26:47 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:26:21 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:26:01 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:25:37 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:25:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:24:44 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:24:19 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:23:48 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:23:26 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 19:15:27 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:58:26 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:56:03 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:51:52 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:45:27 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:42:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:37:36 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:35:46 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:32:44 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:31:23 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:29:13 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:27:23 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:25:33 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:24:02 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:22:15 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:20:23 GMT+0000 (Coordinated Universal Time)

@exam123

star

Fri Jun 07 2024 18:02:10 GMT+0000 (Coordinated Universal Time) https://gramentheme.com/html/odor/index.html?storefront

@jagdish575 #html #css #javascript

star

Fri Jun 07 2024 15:10:04 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Fri Jun 07 2024 14:43:19 GMT+0000 (Coordinated Universal Time)

@exam

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension