College Coding Assinments

                                                     Programing Principles and Paradigms

1) Add Two Numbers.java

import java.util.Scanner;

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

        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();

        int sum = num1 + num2;
        System.out.println("Sum: " + sum);

        scanner.close();
    }
}

2)Functionalvedd.py

def add(a,b):
    return a+b

def sub(a,b):
    return a-b

def multi(a,b):
    return a*b

def div(a,b):
    if(b!=0):
        return a/b
    else:
        return "Undefined"
   
operations=[add,sub,multi,div]
a,b=68,89
name=["add","sub","multi","div"]
for name,operation in zip(name,operations):
    print(f"{name}:{operation(a,b)}")

3)Imperative.c

//write a c programme for imperative programming
#include <stdio.h>

int main() {
    float num1, num2, result;
    int choice;

    printf("Enter 1st number: ");
    scanf("%f", &num1);
    printf("Enter 2nd number: ");
    scanf("%f", &num2);

    printf("\n***************** Welcome to the Menu *******************\n");
    printf("Select Operation:\n");
    printf("1. Addition\n");
    printf("2. Subtraction\n");
    printf("3. Multiplication\n");
    printf("4. Division\n");
    printf("Enter your choice (1-4): ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            result = num1 + num2;
            printf("\nResult: %.2f + %.2f = %.2f\n", num1, num2, result);
            break;

        case 2:
            result = num1 - num2;
            printf("\nResult: %.2f - %.2f = %.2f\n", num1, num2, result);
            break;

        case 3:
            result = num1 * num2;
            printf("\nResult: %.2f * %.2f = %.2f\n", num1, num2, result);
            break;

        case 4:
            if (num2 != 0) {
                result = num1 / num2;
                printf("\nResult: %.2f / %.2f = %.2f\n", num1, num2, result);
            } else {
                printf("\nError: Division by zero is not allowed!\n");
            }
            break;

        default:
            printf("\nInvalid choice! Please select between 1 and 4.\n");
    }

    printf("\n***************** Thank You *******************\n");

    return 0;
}

4)logic.pl

add(A, B, Result):-
    Result is A+B.

subtract(A, B, Result):-
    Result is A-B.

multiply(A, B, Result):-
    Result is A*B.

division(A, B, Result):-
    B \= 0,
        Result is A/B.

5) Ass10:Finance.java

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

class Category {
    String name;
    boolean isExpense;

    public Category(String name, boolean isExpense) {
        this.name = name;
        this.isExpense = isExpense;
    }
}

class Transaction {
    double amount;
    Category category;
    LocalDate date;
    String description;

    public Transaction(double amount, Category category, LocalDate date, String description) {
        this.amount = amount;
        this.category = category;
        this.date = date;
        this.description = description;
    }
}

class Account {
    String name;
    double balance;
    List<Transaction> transactions;

    public Account(String name, double balance) {
        this.name = name;
        this.balance = balance;
        this.transactions = new ArrayList<>();
    }

    public void addTransaction(Transaction t) {
        transactions.add(t);
        if (t.category.isExpense) {
            balance -= t.amount;
        } else {
            balance += t.amount;
        }
    }
}

class User {
    String username;
    List<Account> accounts;

    public User(String username) {
        this.username = username;
        this.accounts = new ArrayList<>();
    }

    public void addAccount(Account account) {
        accounts.add(account);
    }

    public List<Transaction> getAllTransactions() {
        return accounts.stream()
                .flatMap(acc -> acc.transactions.stream())
                .collect(Collectors.toList());
    }
}

public class Finance {

    public static double calculateTotalSpent(List<Transaction> transactions) {
        return transactions.stream()
                .filter(t -> t.category.isExpense)
                .mapToDouble(t -> t.amount)
                .sum();
    }

    public static Map<String, Double> groupSpendingByCategory(List<Transaction> transactions) {
        return transactions.stream()
                .filter(t -> t.category.isExpense)
                .collect(Collectors.groupingBy(t -> t.category.name, Collectors.summingDouble(t -> t.amount)));
    }

    public static Map<String, Double> monthlySummary(List<Transaction> transactions, int year, int month) {
        return transactions.stream()
                .filter(t -> t.date.getYear() == year && t.date.getMonthValue() == month)
                .filter(t -> t.category.isExpense)
                .collect(Collectors.groupingBy(t -> t.category.name, Collectors.summingDouble(t -> t.amount)));
    }

    public static double projectFutureBalance(double currentBalance, double avgSaving, int months) {
        return currentBalance + avgSaving * months;
    }

    public static Map<String, Double> detectSpendingPattern(List<Transaction> transactions, int days) {
        LocalDate cutoffDate = LocalDate.now().minusDays(days);
        return transactions.stream()
                .filter(t -> t.category.isExpense)
                .filter(t -> !t.date.isBefore(cutoffDate))
                .collect(Collectors.groupingBy(t -> t.category.name, Collectors.summingDouble(t -> t.amount)));
    }

    public static void main(String[] args) {
        Category groceries = new Category("Groceries", true);
        Category salary = new Category("Salary", false);

        Account account = new Account("Checking", 1000);
        account.addTransaction(new Transaction(50, groceries, LocalDate.now().minusDays(1), "supermarket"));
        account.addTransaction(new Transaction(1000, salary, LocalDate.now().minusDays(10), "Monthly salary"));

        User user = new User("john_doe");
        user.addAccount(account);

        List<Transaction> allTransactions = user.getAllTransactions();

        System.out.println("Total Spent: " + calculateTotalSpent(allTransactions));
        System.out.println("Grouped Spending: " + groupSpendingByCategory(allTransactions));
        System.out.println("Monthly Summary: " + monthlySummary(allTransactions, LocalDate.now().getYear(), LocalDate.now().getMonthValue()));
        System.out.println("Spending Pattern Last 7 Days: " + detectSpendingPattern(allTransactions, 7));
        System.out.println("Projected Balance in 6 months: " + projectFutureBalance(account.balance, 200, 6));
    }
}

6)Ass2:Fibonacci.c

//fibo series programme in C language
#include<stdio.h>

int main()
{
 int n,first=0,second=1,next;
 printf("Enter the number of terms: ");
 scanf("%d",&n);
 
 printf("Fibonacci Series: ");
 for(int i =0;i<n;i++)
 {
  printf("%d\n",first);
  next=first+second;
  first=second;
  second=next;
  }
 return 0;
}

7)Ass3:parser.py

from lark import Lark, Transformer

# BNF-style grammar
grammar = """
    ?start: expr
    ?expr: expr "+" term   -> add
         | expr "-" term   -> sub
         | term
    ?term: term "*" factor -> mul
         | term "/" factor -> div
         | factor
    ?factor: NUMBER        -> number
           | "(" expr ")"

    %import common.NUMBER
    %import common.WS
    %ignore WS
"""

# Transformer to evaluate the parsed tree
class CalculateTree(Transformer):
    def number(self, n):
        return float(n[0])

    def add(self, items):
        return items[0] + items[1]

    def sub(self, items):
        return items[0] - items[1]

    def mul(self, items):
        return items[0] * items[1]

    def div(self, items):
        return items[0] / items[1]

# Create the parser
parser = Lark(grammar, parser='lalr', transformer=CalculateTree())

# Main loop
if __name__ == "__main__":
    while True:
        try:
            expr = input("Enter expression (or 'exit'): ")
            if expr.lower() == "exit":
                break
            result = parser.parse(expr)
            print("Result:", result)
        except Exception as e:
            print("Error:", e)

8)Ass4:IVehicle.java

interface IVehicle {
    void displayInfo();
    void startEngine();
}

// Base class
class Vehicle implements IVehicle {
    protected String brand;
    protected String model;
    protected int year;

    public Vehicle(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    @Override
    public void displayInfo() {
        System.out.println(brand + " " + model + " (" + year + ")");
    }

    @Override
    public void startEngine() {
        System.out.println(brand + " " + model + " engine started.");
    }
}

// Bike class
class Bike extends Vehicle {
    private boolean hasGear;

    public Bike(String brand, String model, int year, boolean hasGear) {
        super(brand, model, year);
        this.hasGear = hasGear;
    }

    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("Has Gear: " + hasGear);
    }
}

// Truck class
class Truck extends Vehicle {
    private double capacity;

    public Truck(String brand, String model, int year, double capacity) {
        super(brand, model, year);
        this.capacity = capacity;
    }

    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("Capacity: " + capacity + " tons");
    }
}

// Bus class
class Bus extends Vehicle {
    private int seats;

    public Bus(String brand, String model, int year, int seats) {
        super(brand, model, year);
        this.seats = seats;
    }

    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("Seats: " + seats);
    }
}

// Car class
class Car extends Vehicle {
    private int doors;

    public Car(String brand, String model, int year, int doors) {
        super(brand, model, year);
        this.doors = doors;
    }

    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("Doors: " + doors);
    }
}

// Main program
public class VehicleTest {
    public static void main(String[] args) {
        IVehicle[] vehicles = {
            new Car("Toyota", "Corolla", 2022, 4),
            new Bike("Yamaha", "MT-15", 2022, true),  
            new Truck("Volvo", "FH16", 2020, 25.0),
            new Bus("Mercedes", "Tourism", 2023, 50)
        };

        for (IVehicle v : vehicles) {  
            v.displayInfo();
            v.startEngine();
            System.out.println("-------------------");
        }
    }
}

9)Ass5:Contact-Management.pas

{$mode delphi} program ContactManagement; uses SysUtils; type contact = class private FName:string; FPhoneNumber:string; FEmail:string; FAddress:string; public procedure SetName(const AName:string); function GetName:string; procedure SetPhoneNumber(const APhone:string); function GetPhoneNumber:string; procedure SetEmail(const AEmail:string); function GetEmail:string; procedure SetAddress(const AAddress:string); function GetAddress:string; procedure DisplayContact; end; procedure Contact.SetName(const AName:string); begin FName:=Aname; end; function Contact.GetName:string; begin Result:=FName; end; procedure Contact.SetPhoneNumber(const APhone:string); begin FPhoneNumber:= APhone; end; function Contact.GetPhoneNumber:string; begin Result:=FPhoneNumber; end; procedure Contact.SetEmail(const AEmail:string); begin FEmail:=AEmail; end; function Contact.GetEmail:string; begin Result:=FEmail; end; procedure Contact.SetAddress(const AAddress:string); begin FAddress:=AAddress; end; function Contact.GetAddress:string; begin Result:=FAddress; end; procedure Contact.DisplayContact; begin writeln('Name:',FName); writeln('Phone No.',FPhoneNumber); writeln('Email:',FEmail); writeln('Address',FAddress); writeln('-----------------------------'); end; var MyContact:Contact; begin MyContact:=Contact.Create; MyContact.SetName('John Doe'); MyContact.SetPhoneNumber('123-456-7890'); MyContact.SetEmail('johndeo@gmail.com'); MyContact.SetAddress('123 main street, city, country'); writeln('Contact Details:'); MyContact.DisplayContact; MyContact.Free; readln; end.

10)Ass6:Contract_Checker.py

from typing import Dict, Any, List

# contract_checker.py

class ContractCheckResult:
    def __init__(self):
        self.passed = True
        self.details: List[str] = []

    def fail(self, reason: str):
        self.passed = False
        self.details.append("✗ " + reason)

    def ok(self, reason: str):
        self.details.append("☑ " + reason)


def check_offer(facts: Dict[str, Any], r: ContractCheckResult):
    if facts.get("offer") is True:
        r.ok("Offer is present.")
    else:
        r.fail("No offer found.")


def check_acceptance(facts: Dict[str, Any], r: ContractCheckResult):
    if facts.get("acceptance") is True:
        r.ok("Acceptance is present.")
    else:
        r.fail("No acceptance found.")


def check_consideration(facts: Dict[str, Any], r: ContractCheckResult):
    consideration = facts.get("consideration")
    if consideration:
        if isinstance(consideration, (int, float)):
            if consideration > 0:
                r.ok(f"Consideration is valid: {consideration}")
            else:
                r.fail("Consideration amount must be positive.")
        else:
            r.ok(f"Consideration exists: {consideration}")
    else:
        r.fail("Consideration is missing.")


def check_capacity(facts: Dict[str, Any], r: ContractCheckResult):
    parties = facts.get("parties", [])
    if not parties:
        r.fail("No parties listed in contract.")
        return

    for p in parties:
        if p.get("capacity") in ("adult", "corporate", "competent"):
            r.ok(f"Party {p.get('name', 'Unknown')} has legal capacity.")
        else:
            r.fail(f"Party {p.get('name', 'Unknown')} lacks capacity.")


def check_legality(facts: Dict[str, Any], r: ContractCheckResult):
    if facts.get("subject_matter_illegal"):
        r.fail("Contract subject matter is illegal.")
    else:
        r.ok("Contract subject matter is lawful.")


def check_consent(facts: Dict[str, Any], r: ContractCheckResult):
    if facts.get("duress") or facts.get("undue_influence") or facts.get("fraud"):
        issues = []
        if facts.get("duress"): issues.append("duress")
        if facts.get("undue_influence"): issues.append("undue influence")
        if facts.get("fraud"): issues.append("fraud")
        r.fail(f"Consent invalid due to: {', '.join(issues)}.")
    else:
        r.ok("Consent appears genuine and voluntary.")


def evaluate_contract(facts: Dict[str, Any]) -> ContractCheckResult:
    """Run all legal validity checks on a contract."""
    r = ContractCheckResult()
    check_offer(facts, r)
    check_acceptance(facts, r)
    check_consideration(facts, r)
    check_capacity(facts, r)
    check_legality(facts, r)
    check_consent(facts, r)
    return r


if __name__ == "__main__":
    # Example contract facts (structured data)
    facts_example = {
        "offer": True,
        "acceptance": True,
        "consideration": 5000,
        "parties": [
            {"name": "Alice", "capacity": "adult"},
            {"name": "Bob", "capacity": "adult"}
        ],
        "subject_matter_illegal": False,
        "duress": False,
        "undue_influence": False,
        "fraud": False
    }

    result = evaluate_contract(facts_example)
    print("-------------------------------------------------")
    print(" CONTRACT VALIDITY REPORT")
    print("-------------------------------------------------")
    for line in result.details:
        print(line)
    print("-------------------------------------------------")
    print(f" Contract Valid: {result.passed}")
    print("-------------------------------------------------")

11)Ass7:prog.lisp

(defun nth-element (n lst)

          "Returns the nth element from the list lst using iteration."

          (loop for item in lst

                   for i from 0

                   when (= i n) return item))

                  

;; Test example

(format t "Result: ~A~%" (nth-element 2 ' (10 20 30 40 50 60)))

12)Ass8:CheckDate.java

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Scanner;

/*
    Program: To throw an exception if a user enters
    an invalid date format or a non-existent date.

    Author: Nitesh Dipak Badgujar
*/

public class SimpleDateCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a date (dd/MM/yyyy): ");
        String dateInput = sc.nextLine();

        // Define date format
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false); // Do not allow invalid dates like 31/02/2025

        try {
            // Try to parse the date
            sdf.parse(dateInput);
            System.out.println("Valid date: " + dateInput);
        } catch (ParseException e) {
            // Handle invalid date or format
            System.out.println("Invalid date or format! Please enter in dd/MM/yyyy format.");
        }

        sc.close(); // Free up system resources
    }
}




==================Exit=========================





                                  Data Structures

1) Assignment no 1

Matrix:  Addition, Multiplication, Subtraction, Transpose Matrix code

#include <stdio.h>

#define MAX_DIM 3

void readMatrix(int m, int n, int matrix[m][n]) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            printf("Enter element [%d][%d]: ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
}

void printMatrix(int m, int n, int matrix[m][n]) {
    for (int i = 0; i < m; i++) {
        printf("\t");
        for (int j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

void addMatrices(int r, int c, int A[r][c], int B[r][c], int result[r][c]) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[i][j] = A[i][j] + B[i][j];
        }
    }
}

void subtractMatrices(int r, int c, int A[r][c], int B[r][c], int result[r][c]) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[i][j] = A[i][j] - B[i][j];
        }
    }
}

void multiplyMatrices(int rA, int cA, int rB, int cB, int A[rA][cA], int B[rB][cB], int result[rA][cB]) {
    for (int i = 0; i < rA; i++) {
        for (int j = 0; j < cB; j++) {
            result[i][j] = 0;
            for (int k = 0; k < cA; k++) {
                result[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

void transposeMatrix(int r, int c, int matrix[r][c], int result[c][r]) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[j][i] = matrix[i][j];
        }
    }
}

int main() {
    int mA, nA, mB, nB;

    printf("--- Enter dimensions for Matrix A ---\n");
    printf("Enter number of m (1-%d): ", MAX_DIM);
    scanf("%d", &mA);
    printf("Enter number of columns (1-%d): ", MAX_DIM);
    scanf("%d", &nA);

    printf("\n--- Enter dimensions for Matrix B ---\n");
    printf("Enter number of m (1-%d): ", MAX_DIM);
    scanf("%d", &mB);
    printf("Enter number of columns (1-%d): ", MAX_DIM);
    scanf("%d", &nB);

    if (mA <= 0 || mA > MAX_DIM || nA <= 0 || nA > MAX_DIM ||
        mB <= 0 || mB > MAX_DIM || nB <= 0 || nB > MAX_DIM) {
        printf("Error: Dimensions must be between 1 and %d.\n", MAX_DIM);
        return 1;
    }

    int matrixA[mA][nA];
    int matrixB[mB][nB];
   
    printf("\n--- Enter elements for Matrix A (%dx%d) ---\n", mA, nA);
    readMatrix(mA, nA, matrixA);

    printf("\n--- Enter elements for Matrix B (%dx%d) ---\n", mB, nB);
    readMatrix(mB, nB, matrixB);

    int choice;
    do {
        printf("\n--- Matrix Operation Menu ---\n");
        printf("Matrix A (%dx%d):\n", mA, nA);
        printMatrix(mA, nA, matrixA);
        printf("Matrix B (%dx%d):\n", mB, nB);
        printMatrix(mB, nB, matrixB);

        printf("\n1. Addition (A + B)\n");
        printf("2. Subtraction (A - B)\n");
        printf("3. Multiplication (A * B)\n");
        printf("4. Transpose Matrix A\n");
        printf("0. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                if (mA == mB && nA == nB) {
                    int result[mA][nA];
                    addMatrices(mA, nA, matrixA, matrixB, result);
                    printf("\nResult of A + B:\n");
                    printMatrix(mA, nA, result);
                } else {
                    printf("\nError: Addition requires matrices of the same dimensions.\n");
                }
                break;

            case 2:
                if (mA == mB && nA == nB) {
                    int result[mA][nA];
                    subtractMatrices(mA, nA, matrixA, matrixB, result);
                    printf("\nResult of A - B:\n");
                    printMatrix(mA, nA, result);
                } else {
                    printf("\nError: Subtraction requires matrices of the same dimensions.\n");
                }
                break;

            case 3:
                if (nA == mB) {
                    int result[mA][nB];
                    multiplyMatrices(mA, nA, mB, nB, matrixA, matrixB, result);
                    printf("\nResult of A * B:\n");
                    printMatrix(mA, nB, result);
                } else {
                    printf("\nError: Multiplication requires columns of A to be equal to m of B.\n");
                }
                break;

            case 4:
                {
                    int result[nA][mA];
                    transposeMatrix(mA, nA, matrixA, result);
                    printf("\nResult of Transpose(A):\n");
                    printMatrix(nA, mA, result);
                }
                break;

            case 0:
                printf("Exiting program. Goodbye! 👋\n");
                break;

            default:
                printf("Invalid choice! Please try again.\n");
        }
        printf("--------------------------------\n");
    } while (choice != 0);

    return 0;
}

with more advanced 



#include <stdio.h>

#define MAX_DIM 3

// Function to read matrix elements
void readMatrix(int m, int n, int matrix[m][n]) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            printf("Enter element [%d][%d]: ", i + 1, j + 1);
            scanf("%d", &matrix[i][j]);
        }
    }
}

// Function to print matrix
void printMatrix(int m, int n, int matrix[m][n]) {
    for (int i = 0; i < m; i++) {
        printf("\t");
        for (int j = 0; j < n; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

// Function for addition
void addMatrices(int r, int c, int A[r][c], int B[r][c], int result[r][c]) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[i][j] = A[i][j] + B[i][j];
        }
    }
}

// Function for subtraction
void subtractMatrices(int r, int c, int A[r][c], int B[r][c], int result[r][c]) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[i][j] = A[i][j] - B[i][j];
        }
    }
}

// Function for multiplication
void multiplyMatrices(int rA, int cA, int rB, int cB, int A[rA][cA], int B[rB][cB], int result[rA][cB]) {
    for (int i = 0; i < rA; i++) {
        for (int j = 0; j < cB; j++) {
            result[i][j] = 0;
            for (int k = 0; k < cA; k++) {
                result[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

// Function for transpose
void transposeMatrix(int r, int c, int matrix[r][c], int result[c][r]) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            result[j][i] = matrix[i][j];
        }
    }
}

int main() {
    int mA, nA, mB, nB;

    printf("--- Enter dimensions for Matrix A ---\n");
    printf("Enter number of rows (1-%d): ", MAX_DIM);
    scanf("%d", &mA);
    printf("Enter number of columns (1-%d): ", MAX_DIM);
    scanf("%d", &nA);

    printf("\n--- Enter dimensions for Matrix B ---\n");
    printf("Enter number of rows (1-%d): ", MAX_DIM);
    scanf("%d", &mB);
    printf("Enter number of columns (1-%d): ", MAX_DIM);
    scanf("%d", &nB);

    // Validation
    if (mA <= 0 || mA > MAX_DIM || nA <= 0 || nA > MAX_DIM ||
        mB <= 0 || mB > MAX_DIM || nB <= 0 || nB > MAX_DIM) {
        printf("Error: Dimensions must be between 1 and %d.\n", MAX_DIM);
        return 1;
    }

    int matrixA[mA][nA];
    int matrixB[mB][nB];

    printf("\n--- Enter elements for Matrix A (%dx%d) ---\n", mA, nA);
    readMatrix(mA, nA, matrixA);

    printf("\n--- Enter elements for Matrix B (%dx%d) ---\n", mB, nB);
    readMatrix(mB, nB, matrixB);

    int choice;
    do {
        printf("\n--- Matrix Operation Menu ---\n");
        printf("Matrix A (%dx%d):\n", mA, nA);
        printMatrix(mA, nA, matrixA);
        printf("Matrix B (%dx%d):\n", mB, nB);
        printMatrix(mB, nB, matrixB);

        printf("\nChoose an operation:\n");
        printf("1. Addition (A + B)\n");
        printf("2. Subtraction (A - B)\n");
        printf("3. Multiplication (A * B)\n");
        printf("4. Transpose of Matrix A\n");
        printf("0. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                if (mA == mB && nA == nB) {
                    int result[mA][nA];
                    addMatrices(mA, nA, matrixA, matrixB, result);
                    printf("\n result of A + B:\n");
                    printMatrix(mA, nA, result);
                } else {
                    printf("\n Error: Matrices must have the same dimensions for addition.\n");
                }
                break;

            case 2:
                if (mA == mB && nA == nB) {
                    int result[mA][nA];
                    subtractMatrices(mA, nA, matrixA, matrixB, result);
                    printf("\n Result of A - B:\n");
                    printMatrix(mA, nA, result);
                } else {
                    printf("\n Error: Matrices must have the same dimensions for subtraction.\n");
                }
                break;

            case 3:
                if (nA == mB) {
                    int result[mA][nB];
                    multiplyMatrices(mA, nA, mB, nB, matrixA, matrixB, result);
                    printf("\n Result of A * B:\n");
                    printMatrix(mA, nB, result);
                } else {
                    printf("\n Error: For multiplication, columns of A must equal rows of B.\n");
                }
                break;

            case 4: {
                int result[nA][mA];
                transposeMatrix(mA, nA, matrixA, result);
                printf("\n Transpose of Matrix A:\n");
                printMatrix(nA, mA, result);
                break;
            }

            case 0:
                printf("\n Exiting program. Goodbye!\n");
                break;

            default:
                printf("\n Invalid choice! Please try again.\n");
        }
        printf("--------------------------------\n");
    } while (choice != 0);

    return 0;
}

2) Assignment no 2: Code with pointer and as union, intersection, defference, symetric ,difference, subset

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *set1, *set2;         // initializing pointers for dynamic memory allocation
    int size1, size2, choice; // Declare variables for sizes and choice
    // taking set inputs from user
    printf("Enter the number of elements in set 1: ");
    scanf("%d", &size1);
    set1 = (int *)malloc(size1 * sizeof(int));
    for (int i = 0; i < size1; i++)
    {
        printf("Enter element %d of set 1: ", i + 1);
        scanf("%d", set1 + i);
    }
    // Displaying set 1
    printf("Set 1: { ");
    for (int i = 0; i < size1; i++)
    {
        printf("%d ", *(set1 + i));
    }
    printf("}\n");
    // Taking second set input from user
    printf("Enter the number of elements in set 2: ");
    scanf("%d", &size2);
    set2 = (int *)malloc(size2 * sizeof(int));
    for (int i = 0; i < size2; i++)
    {
        printf("Enter element %d of set 2: ", i + 1);
        scanf("%d", (set2 + i));
    }
    // Displaying set 2
    printf("Set 2: { ");
    for (int i = 0; i < size2; i++)
    {
        printf("%d ", *(set2 + i));
    }
    printf("}\n");
    // Menu for set operations
    while (1)
    {
        printf("\nMenu:\n");
        printf("1.union\n");
        printf("2.intersection\n");
        printf("3.differancen");
        printf("4.symetric diff\n");
        printf("5.symetric diff\n");
        printf("6.subset\n");
        printf("0.exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            printf("Union: { ");
            for (int i = 0; i < size1; i++){
                printf("%d ", *(set1+i));}
            for (int i = 0; i <size2; i++)
            {
                int found = 1;
                for (int j = 0; j <size1; j++)
                {
                    if (*(set2+i) == *(set1 + j))
                    {
                        found = 0;
                        break;
                    }
                }
                if (!found){
                    printf("%d ", *(set2+i));}
            }
            printf("}\n");
            break;
           
        case 2:
            printf("Intersection: { ");
            for (int i = 0; i < size1; i++)
            {
                for (int j = 0; j < size2; j++)
                {
                    if (*(set1 + i) == *(set2 + j))
                    {
                        printf("%d ", *(set1 + i));
                        break;
                    }
                }
            break;
            case 3:
            printf("Difference: { ");
            for (int i = 0; i < size1; i++)
            {
                int found = 0;
                for (int j = 0; j < size2; j++)
                {
                    if (*(set1 + i) == *(set2 + j))
                    {
                        found = 1;
                        break;
                    }
                }
                if (!found)
                    printf("%d ", *(set1 + i));
            }
            printf("}\n");
            break;
        case 0:
            printf("Exiting...\n");
            return 0;
        default:
            break;
        }
    }
}
            }

3)Assignment No 3: Matrices With Switch Case

#include <stdio.h>
#include <stdlib.h>

#define SIZE 3

int mat1[SIZE][SIZE], mat2[SIZE][SIZE], result[SIZE][SIZE];

// Function prototypes
void create_mat();
void add_mat();
void sub_mat();
void mult_mat();
void transport_mat();

int main() {
    int ch;
    while (1) {
        printf("\n============ MENU ============\n");
        printf("1. Create the matrices\n");
        printf("2. Matrix addition\n");
        printf("3. Matrix subtraction\n");
        printf("4. Matrix multiplication\n");
        printf("5. Transpose of matrix\n");
        printf("6. Exit\n");
        printf("Choose the option: ");
        scanf("%d", &ch);
   
   
        switch (ch) {
            case 1: create_mat(); break;
            case 2: add_mat(); break;
            case 3: sub_mat(); break;
            case 4: mult_mat(); break;
            case 5: transport_mat(); break;
            case 6: exit(0);
            default: printf("Invalid choice. Try again.\n");
        }
    }
    return 0;
}

4) Assignment no 4: Song Playlist with Linked List using push pop Front Rear as Not working 

#include <stdio.h>
#include <stdlib.h>

struct playlist
{
    char song_name[20];
    char artist_name[20];
    int duration; // duration in seconds
    struct playlist *next, *prev;
};
struct playlist *head = NULL;
struct playlist *tail = NULL;
void add_song();
void display_playlist();
void Remove_song();

int main()
{
    int ch;
    while (1) // While Loop
    {
        printf("\n==========MENU===========\n");
        printf("\n1.Add song to playlist");
        printf("\n2.Display playlist");
        printf("\n3.Remove a song from playlist");
        printf("\n4.shuffel song");
        printf("\n5.Play next song");
        printf("\n6.Play previous song");
        printf("\n7.Exit");
        printf("\nEnter your choice: ");
        scanf("%d", &ch);
        switch (ch) // Switch Case
        {
        case 1:
            add_song();
            break;
        case 2:
            display_playlist();
            break;
        case 3:
            Remove_song();
            break;
            //   case 4:
            //         shuffel_song();
            //         break;
            //   case 5:next_song();
            //         break;
            //   case 6:previous_song();
            break;
        case 7:
            exit(0);
            break;
        default:
            printf("Enter wrong choice !!!");
            break;
        }
    }

    return 0;
}
void add_song()
{
    struct playlist *new_song = (struct playlist *)malloc(sizeof(struct playlist));
    getchar(); // clear buffer
    printf("Enter song name: ");
    scanf(" %[^\n]s", new_song->song_name);
    printf("Enter artist name: ");
    scanf(" %[^\n]s", new_song->artist_name);
    printf("Enter duration (in seconds): ");
    scanf("%d", &new_song->duration);
    if (head == NULL)
    {
        new_song->next = NULL;
        new_song->prev = NULL;
        head = new_song;
    }
    else
    {
        struct playlist *temp = head;
        while (temp->next != NULL)
        {
            temp = temp->next;
        }
        temp->next = new_song;
        new_song->prev = temp;
        new_song->next = NULL;
    }
}
void display_playlist()
{
    if (head == NULL)
    {
        printf("Playlist is empty!\n");
        return;
    }
    struct playlist *temp = head;
    int count = 1;
    printf("\nPlaylist:\n");
    while (temp != NULL)
    {
        printf("%d. %s by %s [%d sec]\n", count++, temp->song_name, temp->artist_name, temp->duration);
        temp = temp->next;
    }
    free(temp);
}

void Remove_song()
{
    if (head == NULL)
    {
        printf("Playlist is empty. Nothing to remove.\n");
        return;
    }

    struct playlist *temp = head;
    struct playlist *prev = NULL;
    char song[100];

    printf("Enter the song name you want to remove: ");
    scanf(" %[^\n]", song);

    while (temp != NULL && strcmp(temp->song_name, song) != 0)
    {
        prev = temp;
        temp = temp->next;
    }

    if (temp == NULL)
    {
        printf("Song '%s' not found in the playlist.\n", song);
        return;
    }

    if (temp == head)
    {
        head = temp->next;
    }
    else
    {
        prev->next = temp->next;
    }

    printf("Successfully removed '%s'.\n", temp->song_name);
    free(temp);
}

Advanced 



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct playlist
{
    char song_name[50];
    char artist_name[50];
    int duration; // duration in seconds
    struct playlist *next, *prev;
};

struct playlist *head = NULL;
struct playlist *tail = NULL;

void add_song();
void display_playlist();
void remove_song();

int main()
{
    int ch;

    while (1)
    {
        printf("\n========== PLAYLIST MENU ==========\n");
        printf("1. Add song to playlist\n");
        printf("2. Display playlist\n");
        printf("3. Remove a song from playlist\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &ch);

        switch (ch)
        {
        case 1:
            add_song();
            break;
        case 2:
            display_playlist();
            break;
        case 3:
            remove_song();
            break;
        case 4:
            printf("Exiting... 🎵 Goodbye!\n");
            exit(0);
        default:
            printf(" Invalid choice! Please try again.\n");
            break;
        }
    }

    return 0;
}

void add_song()
{
    struct playlist *new_song = (struct playlist *)malloc(sizeof(struct playlist));
    if (new_song == NULL)
    {
        printf("Memory allocation failed!\n");
        return;
    }

    getchar(); // clear input buffer
    printf("Enter song name: ");
    scanf(" %[^\n]", new_song->song_name);
    printf("Enter artist name: ");
    scanf(" %[^\n]", new_song->artist_name);
    printf("Enter duration (in seconds): ");
    scanf("%d", &new_song->duration);

    new_song->next = NULL;
    new_song->prev = NULL;

    if (head == NULL)
    {
        head = tail = new_song;
    }
    else
    {
        tail->next = new_song;
        new_song->prev = tail;
        tail = new_song;
    }

    printf("Song '%s' added successfully!\n", new_song->song_name);
}

void display_playlist()
{
    if (head == NULL)
    {
        printf("\n Playlist is empty!\n");
        return;
    }

    struct playlist *temp = head;
    int count = 1;

    printf("\n========== Your Playlist ==========\n");
    while (temp != NULL)
    {
        printf("%d. '%s' by %s [%d sec]\n", count++, temp->song_name, temp->artist_name, temp->duration);
        temp = temp->next;
    }
}

void remove_song()
{
    if (head == NULL)
    {
        printf("Playlist is empty. Nothing to remove.\n");
        return;
    }

    char song[50];
    getchar(); // clear buffer
    printf("Enter the song name to remove: ");
    scanf(" %[^\n]", song);

    struct playlist *temp = head;

    while (temp != NULL && strcmp(temp->song_name, song) != 0)
    {
        temp = temp->next;
    }

    if (temp == NULL)
    {
        printf(" Song '%s' not found in the playlist.\n", song);
        return;
    }

    // Case 1: Removing head
    if (temp == head)
    {
        head = temp->next;
        if (head != NULL)
            head->prev = NULL;
        else
            tail = NULL; // if list becomes empty
    }
    // Case 2: Removing tail
    else if (temp == tail)
    {
        tail = temp->prev;
        tail->next = NULL;
    }
    // Case 3: Middle node
    else
    {
        temp->prev->next = temp->next;
        temp->next->prev = temp->prev;
    }

    printf(" Successfully removed '%s'.\n", temp->song_name);
    free(temp);
}

5)Assignment no 5: Insertion, Deletion, Display using stack, Queue,  Head,  Tail,  push, pop 

#include<stdio.h>
#include<stdlib.h>

struct circuler_list
{
    int data;
    struct circuler_list *next;
};

struct circuler_list *head = NULL;
void insertion();
void deletion();
void display();

int main()
{
    int ch;
    while (1) // While Loop
    {
        printf("\n\n========MENU========\n");
        printf("\n1.Insertion");
        printf("\n2.deletion");
        printf("\n3.display");
        printf("\n4.Exit");
        printf("\n\nEnter your choice: ");
        scanf("%d", &ch);
        switch (ch)
        {
            case 1:
                insertion();
                break;
            case 2:
                deletion();
                break;
            case 3:
                display();
                break;
            case 4:
                exit(0);
        }
    }
}

void insertion()
{
    struct circuler_list *newnode;
    newnode = (struct circuler_list *)malloc(sizeof(struct circuler_list));
    printf("Enter data : ");
    scanf("%d", &newnode->data);
    if(head == NULL)
    {
        head = newnode;
        newnode->next = head;
    }
    else
    {
        struct circuler_list *temp = head;
        while (temp->next != head)
        {
            temp = temp->next;
        }
        temp->next = newnode;
        newnode->next = head;
    }
}

void display()
{
    if (head == NULL)
    {
        printf("List is empty\n");
        return;
    }
    struct circuler_list *temp = head;
    printf("Circular Linked List: ");
    do
    {
        printf("%d -> ", temp->data);
        temp = temp->next;
    } while (temp != head);
    printf("(head: %d)\n", head->data);
}

void deletion()
{
    int val;
    if (head == NULL)
    {
        printf("List is empty\n");
        return;
    }
    printf("Enter value to delete : ");
    scanf("%d", &val);
    struct circuler_list *temp = head, *prev = NULL;
    while (temp->data != val)
    {
        if (temp->next == head)
        {
            printf("Value not found in the list\n");
            return;
        }
        prev = temp;
        temp = temp->next;
    }
    if (temp == head)
    {
        if (head->next == head)
        {
            free(head);
            head = NULL;
        }
        else
        {
            struct circuler_list *last = head;
            while (last->next != head)
            {
                last = last->next;
            }
            last->next = head->next;
            free(head);
            head = last->next;
        }
    }
    else
    {
        prev->next = temp->next;
        free(temp);
    }
}

6)Assignment No 6: Decimal to Binary and Binary To Decimal Conversion using Push, Pop, Stack Top


//write a program for decimal to binary and binary to decimal coversion using stack
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int stack[MAX];
int top = -1;
int decimal_to_binary();
int binary_to_decimal();
void push(int val);
int pop();
int main(){
    int ch;
    while(1){
        printf("\n==========MENU===========\n");
        printf("\n1.Decimal to Binary");
        printf("\n2.Binary to Decimal");
        printf("\n3.Exit");
        printf("\nEnter your choice: ");
        scanf("%d",&ch);
        switch(ch){
            case 1: decimal_to_binary();
                    break;
            case 2: binary_to_decimal();
                    break;
            case 3: exit(0);
            default: printf("Enter wrong choice !!!");  

    }

}
}
int decimal_to_binary(){
    int n,rem;
    printf("Enter a decimal number: ");
    scanf("%d",&n);
    while(n>0){
        rem=n%2;
        push(rem);
        n=n/2;
    }
    printf("Binary representation: ");
    while(top!=-1){
        printf("%d",pop());
    }
    printf("\n");
}
int binary_to_decimal(){
    int n,rem,decimal=0,i=0;
    printf("Enter a binary number: ");
    scanf("%d",&n);
    while(n>0){
        rem=n%10;
        decimal=decimal+rem*(1<<i);
        n=n/10;
        i++;
    }
    printf("Decimal representation: %d\n",decimal);
}
void push(int val){
    if(top==MAX-1){
        printf("Stack overflow\n");
    }
    else{
        top++;
        stack[top]=val;
    }
}
int pop(){
    if(top==-1){
        printf("Stack underflow\n");
        return -1;
    }
    else{
        int val=stack[top];
        top--;
        return val;
    }
}

7)Assignment no 7: 

// Question...Implemnent stack as a abtarct data type and use ADT for conersion of

// 1. inficx to postfix expression
// 2. infix to prefix expression
// 3. evolution of post fix exprssion
// 4.  evolution of prefix exprssion
// Question...Implemnent stack as a abtarct data type and use ADT for conersion of
// 1. inficx to postfix expression
// 2. infix to prefix expression
// 3. evolution of post fix exprssion
// 4.  evolution of prefix exprssion

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX 100

typedef struct {
    int top;
    char items[MAX];
} Stack;

void push(Stack* s, char c) {
    if (s->top < MAX - 1)
        s->items[++(s->top)] = c;
}

char pop(Stack* s) {
    if (s->top == -1) return '\0';
    return s->items[(s->top)--];
}

char peek(Stack* s) {
    if (s->top == -1) return '\0';
    return s->items[s->top];
}

int Empty(Stack* s) {
    return s->top == -1;
}

int precedence(char c) {
    switch (c) {
        case '+':
        case '-': return 1;
        case '*':
        case '/': return 2;
        case '^': return 3;
    }
    return -1;
}
int isOperator(char c) {
    return (c=='+' || c=='-' || c=='*' || c=='/' || c=='^');
}

void infixToPostfix(char* infix, char* postfix) {
    Stack s; s.top = -1;
    int i=0, j=0;
    char c;
    while ((c = infix[i++]) != '\0') {
        if (isalnum(c))
            postfix[j++] = c;
        else if (c == '(')
            push(&s, c);
        else if (c == ')') {
            while (!Empty(&s) && peek(&s) != '(')
                postfix[j++] = pop(&s);
            pop(&s);
        }
        else if (isOperator(c)) {
            while (!Empty(&s) && precedence(peek(&s)) >= precedence(c))
                postfix[j++] = pop(&s);
            push(&s, c);
        }
    }
    while (!Empty(&s))
        postfix[j++] = pop(&s);
    postfix[j] = '\0';
}

void reverseString(char* str) {
    int len = strlen(str);
    for (int i=0; i<len/2; i++) {
        char temp = str[i];
        str[i] = str[len-1 - i];
        str[len-1 - i] = temp;
    }
}

void infixToPrefix(char* infix, char* prefix) {
    char temp[MAX];
    strcpy(temp, infix);
    reverseString(temp);

    // Change brackets
    for (int i=0; temp[i]; i++) {
        if (temp[i] == '(') temp[i] = ')';
        else if (temp[i] == ')') temp[i] = '(';
    }

    char postfix[MAX];
    infixToPostfix(temp, postfix);
    reverseString(postfix);
    strcpy(prefix, postfix);
}

int main() {
    int choice;
    char infix[MAX], postfix[MAX], prefix[MAX];

    while (1) {
        printf("\nMENU:\n");
        printf("1. Infix to Postfix\n");
        printf("2. Infix to Prefix\n");
        printf("3. Evaluate Postfix\n");
        printf("4. Evaluate Prefix\n");
        printf("5. Exit\n");
        printf("Enter choice: ");
        scanf("%d", &choice);

        switch(choice) {
            case 1:
                printf("Enter infix expr: ");
                scanf("%s", infix);
                infixToPostfix(infix, postfix);
                printf("Postfix: %s\n", postfix);
                break;
            case 2:
                printf("Enter infix expr: ");
                scanf("%s", infix);
                infixToPrefix(infix, prefix);
                printf("Prefix: %s\n", prefix);
                break;
            case 3:
               
            case 4:
               
            case 5:
                printf("exit\n");
                exit(0);
            default:
                printf("Invalid choice, try again.\n");
        }
    }

    return 0;
}

Advanced:   Stack ADT for Expression Conversion & Evaluation 




#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX 100

// Stack structure (can hold both chars and ints)
typedef struct {
    int top;
    char items[MAX];
} Stack;

// Integer Stack for evaluation
typedef struct {
    int top;
    int items[MAX];
} IntStack;

// ===== Stack ADT (for characters) =====
void push(Stack *s, char c) {
    if (s->top < MAX - 1)
        s->items[++(s->top)] = c;
}

char pop(Stack *s) {
    if (s->top == -1)
        return '\0';
    return s->items[(s->top)--];
}

char peek(Stack *s) {
    if (s->top == -1)
        return '\0';
    return s->items[s->top];
}

int Empty(Stack *s) {
    return s->top == -1;
}

// ===== Integer Stack for evaluation =====
void pushInt(IntStack *s, int val) {
    if (s->top < MAX - 1)
        s->items[++(s->top)] = val;
}

int popInt(IntStack *s) {
    if (s->top == -1)
        return 0;
    return s->items[(s->top)--];
}

int isEmptyInt(IntStack *s) {
    return s->top == -1;
}

// ===== Operator Functions =====
int precedence(char c) {
    switch (c) {
        case '+':
        case '-': return 1;
        case '*':
        case '/': return 2;
        case '^': return 3;
    }
    return -1;
}

int isOperator(char c) {
    return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}

// ===== Conversion Functions =====
void infixToPostfix(char *infix, char *postfix) {
    Stack s;
    s.top = -1;
    int i = 0, j = 0;
    char c;

    while ((c = infix[i++]) != '\0') {
        if (isalnum(c))
            postfix[j++] = c;
        else if (c == '(')
            push(&s, c);
        else if (c == ')') {
            while (!Empty(&s) && peek(&s) != '(')
                postfix[j++] = pop(&s);
            pop(&s);
        } else if (isOperator(c)) {
            while (!Empty(&s) && precedence(peek(&s)) >= precedence(c))
                postfix[j++] = pop(&s);
            push(&s, c);
        }
    }
    while (!Empty(&s))
        postfix[j++] = pop(&s);
    postfix[j] = '\0';
}

void reverseString(char *str) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        char temp = str[i];
        str[i] = str[len - 1 - i];
        str[len - 1 - i] = temp;
    }
}

void infixToPrefix(char *infix, char *prefix) {
    char temp[MAX];
    strcpy(temp, infix);
    reverseString(temp);

    for (int i = 0; temp[i]; i++) {
        if (temp[i] == '(')
            temp[i] = ')';
        else if (temp[i] == ')')
            temp[i] = '(';
    }

    char postfix[MAX];
    infixToPostfix(temp, postfix);
    reverseString(postfix);
    strcpy(prefix, postfix);
}

// ===== Evaluation Functions =====
int evaluatePostfix(char *postfix) {
    IntStack s;
    s.top = -1;

    for (int i = 0; postfix[i] != '\0'; i++) {
        char c = postfix[i];

        if (isdigit(c))
            pushInt(&s, c - '0');
        else if (isOperator(c)) {
            int val2 = popInt(&s);
            int val1 = popInt(&s);
            switch (c) {
                case '+': pushInt(&s, val1 + val2); break;
                case '-': pushInt(&s, val1 - val2); break;
                case '*': pushInt(&s, val1 * val2); break;
                case '/': pushInt(&s, val1 / val2); break;
                case '^': {
                    int result = 1;
                    for (int j = 0; j < val2; j++)
                        result *= val1;
                    pushInt(&s, result);
                    break;
                }
            }
        }
    }
    return popInt(&s);
}

int evaluatePrefix(char *prefix) {
    IntStack s;
    s.top = -1;

    int len = strlen(prefix);
    for (int i = len - 1; i >= 0; i--) {
        char c = prefix[i];

        if (isdigit(c))
            pushInt(&s, c - '0');
        else if (isOperator(c)) {
            int val1 = popInt(&s);
            int val2 = popInt(&s);
            switch (c) {
                case '+': pushInt(&s, val1 + val2); break;
                case '-': pushInt(&s, val1 - val2); break;
                case '*': pushInt(&s, val1 * val2); break;
                case '/': pushInt(&s, val1 / val2); break;
                case '^': {
                    int result = 1;
                    for (int j = 0; j < val2; j++)
                        result *= val1;
                    pushInt(&s, result);
                    break;
                }
            }
        }
    }
    return popInt(&s);
}

// ===== Main Program =====
int main() {
    int choice;
    char infix[MAX], postfix[MAX], prefix[MAX];

    while (1) {
        printf("\n===== MENU =====\n");
        printf("1. Infix to Postfix\n");
        printf("2. Infix to Prefix\n");
        printf("3. Evaluate Postfix\n");
        printf("4. Evaluate Prefix\n");
        printf("5. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter infix expression: ");
                scanf("%s", infix);
                infixToPostfix(infix, postfix);
                printf(" Postfix: %s\n", postfix);
                break;

            case 2:
                printf("Enter infix expression: ");
                scanf("%s", infix);
                infixToPrefix(infix, prefix);
                printf(" Prefix: %s\n", prefix);
                break;

            case 3:
                printf("Enter postfix expression: ");
                scanf("%s", postfix);
                printf(" Result = %d\n", evaluatePostfix(postfix));
                break;

            case 4:
                printf("Enter prefix expression: ");
                scanf("%s", prefix);
                printf(" Result = %d\n", evaluatePrefix(prefix));
                break;

            case 5:
                printf(" Exiting program.\n");
                exit(0);

            default:
                printf(" Invalid choice! Try again.\n");
        }
    }

    return 0;
}

8)Assignment no 8: 

write a  program to simulate a customer service desk using a queue to manage customer tickets.
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

typedef struct {
    int tickets[MAX];
    int front;
    int rear;
} Queue;

void initQueue(Queue *q) {
    q->front = -1;
    q->rear = -1;
}

int isEmpty(Queue *q) {
    return (q->front == -1);
}

int isFull(Queue *q) {
    return (q->rear == MAX - 1);
}

void enqueue(Queue *q, int ticket) {
    if (isFull(q)) {
        printf("Queue is full! Cannot add more customers.\n");
        return;
    }
    if (isEmpty(q)) {
        q->front = 0;
    }
    q->rear++;
    q->tickets[q->rear] = ticket;
    printf("Customer with ticket %d added to the queue.\n", ticket);
}

int dequeue(Queue *q) {
    if (isEmpty(q)) {
       //Write a program to simulate imergancy room where peshant are given diffenet priority levels base on the saviority of there condition use priority queue to manage the paitiont, where the most critical peshitiont  printf("Queue is empty! No customers to serve.\n");
        return -1;
    }
    int ticket = q->tickets[q->front];
    if (q->front == q->rear) {
        // Queue is now empty after serving this customer
        q->front = q->rear = -1;
    } else {
        q->front++;
    }
    return ticket;
}

void displayQueue(Queue *q) {
    if (isEmpty(q)) {
        printf("Queue is empty.\n");
        return;
    }
    printf("Current queue: ");
    for (int i = q->front; i <= q->rear; i++) {
        printf("%d ", q->tickets[i]);
    }
    printf("\n");
}

int main() {
    Queue q;
    initQueue(&q);
    int choice;
    int ticketNumber = 1;

    while (1) {
        printf("\nCustomer Service Desk Menu:\n");
        printf("1. Add customer to queue\n");
        printf("2. Serve customer\n");
        printf("3. Display queue\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                enqueue(&q, ticketNumber++);
                break;
            case 2: {
                int servedTicket = dequeue(&q);
                if (servedTicket != -1)
                    printf("Serving customer with ticket %d.\n", servedTicket);
                break;
            }
            case 3:
                displayQueue(&q);
                break;
            case 4:
                printf("Exiting program.\n");
                exit(0);
            default:
                printf("Invalid choice! Please try again.\n");
        }
    }
    return 0;
}

Advanced as Front rear condition on Queue


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

typedef struct {
    char name[50];
    int severity; // Higher number = more critical
} Patient;

typedef struct {
    Patient patients[MAX];
    int size;
} PriorityQueue;

void initQueue(PriorityQueue *q) {
    q->size = 0;
}

int isEmpty(PriorityQueue *q) {
    return q->size == 0;
}

int isFull(PriorityQueue *q) {
    return q->size == MAX;
}

void enqueue(PriorityQueue *q, char name[], int severity) {
    if (isFull(q)) {
        printf("Emergency room is full! Cannot add more patients.\n");
        return;
    }

    // Insert in priority order (highest severity first)
    int i = q->size - 1;
    while (i >= 0 && q->patients[i].severity < severity) {
        q->patients[i + 1] = q->patients[i];
        i--;
    }

    strcpy(q->patients[i + 1].name, name);
    q->patients[i + 1].severity = severity;
    q->size++;

    printf("Patient '%s' (severity %d) added to emergency room.\n", name, severity);
}

void dequeue(PriorityQueue *q) {
    if (isEmpty(q)) {
        printf("No patients to serve.\n");
        return;
    }

    Patient p = q->patients[0];
    for (int i = 1; i < q->size; i++) {
        q->patients[i - 1] = q->patients[i];
    }
    q->size--;

    printf("Serving patient '%s' (severity %d).\n", p.name, p.severity);
}

void displayQueue(PriorityQueue *q) {
    if (isEmpty(q)) {
        printf("No patients in the emergency room.\n");
        return;
    }

    printf("\nCurrent Patients (in priority order):\n");
    for (int i = 0; i < q->size; i++) {
        printf("%d. %s (Severity: %d)\n", i + 1, q->patients[i].name, q->patients[i].severity);
    }
}

int main() {
    PriorityQueue q;
    initQueue(&q);

    int choice;
    char name[50];
    int severity;

    while (1) {
        printf("\n=== Emergency Room Menu ===\n");
        printf("1. Add patient\n");
        printf("2. Serve next patient\n");
        printf("3. Display waiting patients\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter patient name: ");
                scanf("%s", name);
                printf("Enter severity level (1-10): ");
                scanf("%d", &severity);
                enqueue(&q, name, severity);
                break;
            case 2:
                dequeue(&q);
                break;
            case 3:
                displayQueue(&q);
                break;
            case 4:
                printf("Exiting...\n");
                exit(0);
            default:
                printf("Invalid choice. Try again.\n");
        }
    }

    return 0;
}

9)Assignment no 9: 

//Write a program to simulate imergancy room where peshitiont are given diffenet
priority levels base on the saviority of there condition use priority queue to
manage the paitiont, where the most critical peshitiont are pritate first

#include<stdio.h>
#include<stdlib.h>

#define MAX 100

typedef struct {
    char name[50];
    int priority;
}Patient;

Patient pq[MAX];
int size = 0;
void insert(char name[], int priority){
    Patient p;
    strcpy(p.name, name);
    p.priority= priority;
    int i = size -1;
    while(i>=0 && pq[i].priority<priority)
    {
     pq[i+1]=pq[i];
    }
    pq[i+1]=p;
    size++;
    printf("");

}

advanced for Priority Queue


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

struct Patient {
    char name[50];
    int severity; // Higher value means more critical
};

struct PriorityQueue {
    struct Patient patients[MAX];
    int size;
};

void initQueue(struct PriorityQueue *q) {
    q->size = 0;
}

int isEmpty(struct PriorityQueue *q) {
    return q->size == 0;
}

int isFull(struct PriorityQueue *q) {
    return q->size == MAX;
}

void addPatient(struct PriorityQueue *q, char name[], int severity) {
    if (isFull(q)) {
        printf("Emergency room is full. Cannot add more patients.\n");
        return;
    }

    int i = q->size - 1;
    while (i >= 0 && q->patients[i].severity < severity) {
        q->patients[i + 1] = q->patients[i];
        i--;
    }

    strcpy(q->patients[i + 1].name, name);
    q->patients[i + 1].severity = severity;
    q->size++;

    printf("Patient '%s' with severity %d added to the emergency room.\n", name, severity);
}

void servePatient(struct PriorityQueue *q) {
    if (isEmpty(q)) {
        printf("No patients to serve.\n");
        return;
    }

    struct Patient p = q->patients[0];
    for (int i = 1; i < q->size; i++) {
        q->patients[i - 1] = q->patients[i];
    }
    q->size--;

    printf("Serving patient '%s' (severity %d).\n", p.name, p.severity);
}

void displayPatients(struct PriorityQueue *q) {
    if (isEmpty(q)) {
        printf("No patients in the emergency room.\n");
        return;
    }

    printf("\nCurrent patients waiting (in order of priority):\n");
    for (int i = 0; i < q->size; i++) {
        printf("%d. %s (Severity: %d)\n", i + 1, q->patients[i].name, q->patients[i].severity);
    }
}

int main() {
    struct PriorityQueue queue;
    initQueue(&queue);

    int choice;
    char name[50];
    int severity;

    while (1) {
        printf("\n=== Emergency Room Menu ===\n");
        printf("1. Add patient\n");
        printf("2. Serve next patient\n");
        printf("3. Display waiting patients\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter patient name: ");
                scanf("%s", name);
                printf("Enter severity level (1-10): ");
                scanf("%d", &severity);
                addPatient(&queue, name, severity);
                break;

            case 2:
                servePatient(&queue);
                break;

            case 3:
                displayPatients(&queue);
                break;

            case 4:
                printf("Exiting program.\n");
                exit(0);

            default:
                printf("Invalid choice. Please try again.\n");
        }
    }

    return 0;
}

10)Assignment no 10: Priority Queue using Push and POP example as Patient 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
struct Patient
{
    char name[50];
    int priority;
};
struct Patient queue[MAX];
int size = 0;
void addPatient(char name[], int priority);
void treatPatient();
void showPatients();
int main()
{
    int choice;
    while (1)
    {
        printf("\nEmergency Room Management System\n");
        printf("1. Add Patient\n");
        printf("2. Treat Patient\n");
        printf("3. Show Patients\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            char name[50];
            int priority;
            printf("Enter patient name: ");
            scanf("%s", name);
            printf("Enter patient priority (higher number = higher priority): ");
            scanf("%d", &priority);
            addPatient(name, priority);
            break;
        case 2:
            treatPatient();
            break;
        case 3:
            showPatients();
            break;
        case 4:
            exit(0);
        default:
            printf("Invalid choice! Please try again.\n");
        }
    }
    return 0;
}
void addPatient(char name[], int priority)
{
    if (size == MAX)
    {
        printf("Queue is full!\n");
        return;
    }
    int i = size - 1;
    while (i >= 0 && queue[i].priority > priority)
    {
        queue[i + 1] = queue[i];
        i--;
    }
    queue[i + 1].priority = priority;
    strcpy(queue[i + 1].name, name);
    size++;
    printf("Patient %s added with priority %d.\n", name, priority);
}
void treatPatient()
{
    if (size == 0)
    {
        printf("No patients to treat!\n");
        return;
    }
    printf("Treating patient %s with priority %d.\n", queue[0].name, queue[0].priority);
    for (int i = 1; i < size; i++)
    {
        queue[i - 1] = queue[i];
    }
    size--;
}
void showPatients()
{
    if (size == 0)
    {
        printf("No patients in the queue!\n");
        return;
    }
    printf("Patients in the queue:\n");
    for (int i = 0; i < size; i++)
    {
        printf("%d. %s (Priority: %d)\n", i + 1, queue[i].name, queue[i].priority);
    }
}

11)Assignment no 11: Linear and Binary Search using Array Searching and Sorting 

#include <stdio.h>

int linearSearch(int arr[], int n, int key);
int binarySearch(int arr[], int n, int key);
void sortArray(int arr[], int n);

int main()
{
    int n, key, choice, pos;
    printf("Enter number of students who attended training: ");
    scanf("%d", &n);

    int roll[n];
    printf("Enter roll numbers of students (in random order):\n");
    for (int i = 0; i < n; i++)
        scanf("%d", &roll[i]);

    printf("\nEnter roll number to search: ");
    scanf("%d", &key);

    printf("\n1. Linear Search\n2. Binary Search\nEnter your choice: ");
    scanf("%d", &choice);

    switch (choice)
    {
    case 1:
        pos = linearSearch(roll, n, key);
        if (pos != -1)
            printf("Student attended training (found at position %d)\n", pos + 1);
        else
            printf("Student did NOT attend training\n");
        break;

    case 2:
        sortArray(roll, n);
        pos = binarySearch(roll, n, key);
        if (pos != -1)
            printf("Student attended training (found at sorted position %d)\n", pos + 1);
        else
            printf("Student did NOT attend training\n");
        break;

    default:
        printf("Invalid choice!\n");
    }

    return 0;
}
// Function for Linear Search
int linearSearch(int arr[], int n, int key)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == key)
            return i; // found
    }
    return -1; // not found
}

// Function for Binary Search (array must be sorted)
int binarySearch(int arr[], int n, int key)
{
    int low = 0, high = n - 1, mid;

    while (low <= high)
    {
        mid = (low + high) / 2;

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

// Function to sort array for Binary Search
void sortArray(int arr[], int n)
{
    int temp;
    for (int i = 0; i < n - 1; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (arr[i] > arr[j])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}


12) Assignment no 12: Selection and Bubble Sort Insertion Sort using Sorted Array 

#include <stdio.h>
void display(float arr[], int n);
void selectionSort(float arr[], int n);
void bubbleSort(float arr[], int n);
void insertionSort(float arr[], int n);
void main()
{
    float percent[100];
    int i, n, choice;
   
    printf("Enter number of students: ");
    scanf("%d", &n);
   
    printf("Enter percentage of %d students:\n", n);
    for (i = 0; i < n; i++)
    {
        scanf("%f", &percent[i]);
    }
   
    printf("\nChoose Sorting Method:\n");
    printf("1. Selection Sort\n");
    printf("2. Bubble Sort\n");
    printf("3. Insertion Sort\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);
   
    switch (choice)
    {
        case 1:
            selectionSort(percent, n);
            printf("\nArray sorted using Selection Sort.");
            display(percent, n);
            break;
        case 2:
            bubbleSort(percent, n);
            printf("\nArray sorted using Bubble Sort.");
            display(percent, n);
            break;
        case 3:
            insertionSort(percent, n);
            printf("\nArray sorted using Insertion Sort.");
            display(percent, n);
            break;
        default:
            printf("\nInvalid choice!");
    }
   
}
// Function to display array
void display(float arr[], int n)
{
     int i;
    printf("\nSorted Percentages in Ascending Order:\n");
    for (i = 0; i < n; i++)
    {
        printf("%.2f ", arr[i]);
    }
    printf("\n");
}

// Selection Sort Function
void selectionSort(float arr[], int n)
{
    int i, j, min;
    float temp;
    for (i = 0; i < n - 1; i++)
     {
        min = i;
        for (j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[min])
                min = j;
        }
        temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
    }
}

// Bubble Sort Function
void bubbleSort(float arr[], int n)
{
    int i, j;
    float temp;
    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

// Insertion Sort Function
void insertionSort(float arr[], int n)
 {
    int i, j;
    float key;
    for (i = 1; i < n; i++)
    {
        key = arr[i];
        j = i - 1;
        while (j >= 0 && arr[j] > key)
         {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}



--------------------------------------------END-------------------------------------

Post a Comment

0 Comments