Programming with C++ - Day5 || Wong Edition || B.Tech Diaries

Lab #5 - Inheritance and Over-Riding

Question 1 - Company Hierarchy

In a Company Hierarchy consisting of Clerk, Manager and Director, the invoice approval limits are as follows:-

  • Clerk - $100
  • Manager - $500
  • Director - $1000

The UML Class Diagram for the Clerk is as shown.

Clerk
- name : String
- designation: String
* getName : String
* getDesignation : String
* introduce() : String
* approveInvoice(in invoiceAmount:double) : boolean
  • Depict the Company Hierarchy in a UML Class Diagram.
  • Implement the Company Hierarchy. Over-Ride the approveInvoice function to ensure the approval limits are adhered to. [Hint: create the main() loop in the Director class and create instances of Clerk, Manager and Director]

Solution:


#include <iostream>

/**
    * @brief Class Clerk
*/
class Clerk
{
private:
    std::string name, designation;

public:
    Clerk(std::string);
    Clerk(std::string, std::string);
    ~Clerk();
    std::string getName();
    std::string getDesignation();
    std::string introduce();
    bool approveInvoice(double);
};

Clerk::Clerk(std::string name)
{
    this->name = name;
    this->designation = "Clerk";
}

Clerk::Clerk(std::string name, std::string designation)
{
    this->name = name;
    this->designation = designation;
}

Clerk::~Clerk()
{
}

std::string Clerk::getName()
{
    return this->name;
}

std::string Clerk::getDesignation()
{
    return this->designation;
}

std::string Clerk::introduce()
{
    return "My name is " + this->name + " and I am a " + this->designation;
}

bool Clerk::approveInvoice(double amount)
{
    if (amount <= 100)
        return true;
    else
        return false;
}

/**
    * @brief Class Manager
*/

class Manager : public Clerk
{
private:
public:
    Manager(std::string);
    Manager(std::string, std::string);
    ~Manager();
    bool approveInvoice(double);
};

Manager::Manager(std::string name) : Clerk(name, "Manager")
{
}

Manager::Manager(std::string name, std::string designation) : Clerk(name, designation)
{
}

Manager::~Manager()
{
}

bool Manager::approveInvoice(double amount)
{
    if (amount <= 500)
        return true;
    else
        return false;
}

/**
    * @brief Class Manager
*/

class Director : public Manager
{
private:
public:
    Director(std::string);
    ~Director();
    bool approveInvoice(double);
};

Director::Director(std::string name) : Manager(name, "Director")
{
}

Director::~Director()
{
}

bool Director::approveInvoice(double amount)
{
    if (amount <= 1000)
        return true;
    else
        return false;
}

// program 1
int main(int argc, char const *argv[])
{
    Clerk clerk("John");
    Manager manager("Jane");
    Director director("Jack");

    std::cout << clerk.introduce() << std::endl;
    std::cout << manager.introduce() << std::endl;
    std::cout << director.introduce() << std::endl;

    std::cout << (clerk.approveInvoice(77) ? "True" : "False") << std::endl;
    std::cout << (clerk.approveInvoice(100) ? "True" : "False") << std::endl;
    std::cout << (clerk.approveInvoice(124) ? "True" : "False") << std::endl;

    std::cout << (manager.approveInvoice(427) ? "True" : "False") << std::endl;
    std::cout << (manager.approveInvoice(500) ? "True" : "False") << std::endl;
    std::cout << (manager.approveInvoice(584) ? "True" : "False") << std::endl;

    std::cout << (director.approveInvoice(927) ? "True" : "False") << std::endl;
    std::cout << (director.approveInvoice(1000) ? "True" : "False") << std::endl;
    std::cout << (director.approveInvoice(1084) ? "True" : "False") << std::endl;
    return 0;
}    

Output:


My name is John and I am a Clerk
My name is Jane and I am a Manager
My name is Jack and I am a Director
True
True
False
True
True
False
True
True
False

Question 2 - Company Hierarchy with Outsourcing

To cut costs, the Company decided to take on Contractors.

A Contractor has a Name in the company records, but has no formal designation. A Contractor cannot approveInvoice (but of course!).

Suppose that at a Company function, everyone has to introduce himself / herself:-

    Hello, my name is xxx.  My designation is XXX.
                          or
    Hello, my name is yyy.  I am a Contractor.
  • Design the new Company Hierarchy in a UML Class Diagram, to accommodate the Contractor. [Hint: pull up the common attributes / properties and behaviour into an Abstract Class.]
  • Implement the new Company Hierarchy. Keep the main() loop in the Director class.

Solution:


...
// program 2

class Contractor : protected Clerk
{
private:

public:
    Contractor(std::string);
    ~Contractor();
    std::string introduce();
    std::string getName();
};

Contractor::Contractor(std::string name) : Clerk(name)
{
}

Contractor::~Contractor()
{
}

std::string Contractor::introduce()
{
    return "My name is " + this->getName() + " and I am a Contractor";
}

std::string Contractor::getName()
{
    return Clerk::getName();
}

int main(int argc, char const *argv[])
{
    Contractor contractor("John");
    std::cout << contractor.introduce() << std::endl;
    std::cout << contractor.getName() << std::endl;

    return 0;
}


My name is John and I am a Contractor
John

Question 3 - Fraud!

Suppose a Director in the Company tries to impersonate his Clerk at the Company function by introducing himself as a Clerk. By using casting, show how that this is possible.


Clerk* cPtr = new Manager(...);
cPtr->introduce();   

Suppose a Clerk in the Company tries to impersonate his Manager at the Company function. Explain why this is not possible.


Manager* mPtr = new Clerk(...);
mPtr->introduce();

Solution:


...
// program 3
int main(int argc, char const *argv[])
{
    Clerk *cPtr = new Manager("John");
    std::cout << cPtr->introduce() << std::endl;

    try
    {
        Manager *mPtr = new Clerk("Jane");
        mPtr->introduce();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << 'n';
    }

    return 0;
}


My name is John and I am a Manager

Share:

Programming with C++ - Day4 || Wong Edition || B.Tech Diaries

Lab #4 - Overloading

Question 1 - Employee

Create an Employee class according to the given Class Diagram.


Employee
- name: String
- gender: int
- colour : string
- Employee()
* Employee(in_name:String, in_gender:boolean)
- getName(): String
- getGender(): boolean
- print(): String

The default constructor is declared private to prevent its use. boolean getGender() returns FALSE if male and TRUE if female. The print() function gives the following sample output:

    Hello, my name is Arif. I am male.

From 2014, India officially recognises a third gender. Modify your design (i.e. give a new UML Class Diagram) to provide

    an overloaded constructor to take in gender information as an integer,
    an overloaded getGender() function that returns 0 if male, 1 if female and -1 if transgender, and
    an overloaded print() function that handles the third gender. 

In your main() loop, create

    2 Employee instances, hired before 2014, and
    3 Employee instances, hired after 2014.

Solution:


#include <iostream>
#include <sstream>

class Employee
{
private:
    std::string name;
    int gender;
    Employee();

public:
    Employee(std::string, bool);
    Employee(std::string, int);
    ~Employee();
    std::string getName();
    bool getGender();
    int getGender(int);
    std::string print();
    std::string print(int);
};

Employee::Employee()
{
}

Employee::~Employee()
{
}

Employee::Employee(std::string name, bool gender)
{
    this->name = name;
    this->gender = gender;
}

std::string Employee::getName()
{
    return name;
}

bool Employee::getGender()
{
    return gender;
}

std::string Employee::print()
{
    std::stringstream ps;
    ps << "Hello, my name is " << name << ". I am " << (gender == 0 ? "male" : "female") << "." << std::endl;
    return ps.str();
}

/*
    After 2014 changes
*/

Employee::Employee(std::string name, int gender)
{
    this->name = name;
    this->gender = gender;
}

int Employee::getGender(int i)
{
    if (i)
        return this->getGender();
    return gender;
}

std::string Employee::print(int i)
{
    if (i)
        this->print();

    std::stringstream ps;
    ps << "Hello, my name is " << name << ". I am " << (gender == 0 ? "male" : (gender == 1 ? "female" : "transgender")) << "." << std::endl;
    return ps.str();
}

int main(int argc, char const *argv[])
{
    Employee e1("Alpha", false), e2("Beta", true);
    std::cout << e1.print(0);
    std::cout << e2.print(0);
    Employee em1("Delta", 1), em2("Gamma", 0), em3("Epsilon", -1);
    std::cout << em1.print(0);
    std::cout << em2.print(0);
    std::cout << em3.print(0);
    return 0;
}    

Output:


Hello, my name is Alpha. I am male.
Hello, my name is Beta. I am female.
Hello, my name is Delta. I am female.
Hello, my name is Gamma. I am male.
Hello, my name is Epsilon. I am transgender.

Question 2 - Operator Overloading

Implement a class named RealTime with representation HH:MM:SS. Design and implement appropriate constructors.

Overload the following operators:

    +	 Addition e.g. myRealTime + yourRealTime
    ++	 Post-Increment e.g. myRealTime++
    ++	 Pre-Increment e.g. ++RealTime 

Provide comments in your code and proper indentation, so that it is easy to read.

Solution:


#include <iostream>
#include <iomanip>

class RealTime
{
private:
    int hr, min, sec;

public:
    RealTime();
    RealTime(int, int, int);
    ~RealTime();
    RealTime operator+(RealTime const &);
    RealTime operator++();
    RealTime operator++(int);
    friend std::ostream &operator<<(std::ostream &, RealTime const &);
};

RealTime::RealTime()
{
    hr = min = sec = 0;
}

RealTime::RealTime(int hr, int min, int sec)
{
    this->hr = hr;
    this->min = min;
    this->sec = sec;
}

RealTime::~RealTime()
{
}

RealTime RealTime::operator+(RealTime const &rt)
{
    RealTime temp;
    temp.sec = this->sec + rt.sec;
    temp.min = this->min + rt.min + temp.sec / 60;
    temp.sec %= 60;
    temp.hr = this->hr + rt.hr + temp.min / 60;
    temp.min %= 60;
    return temp;
}

RealTime RealTime::operator++()
{
    ++sec;
    min = min + sec / 60;
    sec %= 60;
    hr = hr + min / 60;
    min %= 60;
    return *this;
}

RealTime RealTime::operator++(int)
{
    RealTime temp(hr, min, sec);
    sec++;
    min = min + sec / 60;
    sec %= 60;
    hr = hr + min / 60;
    min %= 60;
    return temp;
}

std::ostream &operator<<(std::ostream &os, RealTime const &rt)
{
    return os << std::setfill('0') << std::setw(2) << rt.hr << ":"
                << std::setfill('0') << std::setw(2) << rt.min << ":"
                << std::setfill('0') << std::setw(2) << rt.sec;
}

int main(int argc, char const *argv[])
{
    RealTime myRealTime(7, 2, 5), yourRealTime(12, 34, 56);
    RealTime resRealTime = myRealTime + yourRealTime;
    std::cout << "My Real Time = " << myRealTime << std::endl;
    std::cout << "Your Real Time = " << yourRealTime << std::endl;
    std::cout << "Total Real Time = " << resRealTime << std::endl;
    std::cout << "Prefix Add Real Time = " << ++myRealTime << std::endl;
    std::cout << "Postfix Add Real Time = " << yourRealTime++ << std::endl;
    std::cout << yourRealTime << std::endl;
    return 0;
}    

Output:


My Real Time = 07:02:05
Your Real Time = 12:34:56
Total Real Time = 19:37:01
Prefix Add Real Time = 07:02:06
Postfix Add Real Time = 12:34:56
12:34:57

Share:

Programming with C++ - Day3 || Wong Edition || B.Tech Diaries

Lab #3 - Classes

Question 1 - Rectangle

Implement the Rectangle class according to the given Class Diagram.

Rectangle
- length : int
- width: int
- colour : string
+ getArea() : int
+ print() : string
+ compare(Rectangle r1) : int

Write a constructor which takes as input the length and width of a Rectangle instance. In the default constructor, initalise the length and width to 0;

The function compare returns

    0, if the Rectangle instances are of the same size,
    1, if r1 is larger
    -1, if r1 is smaller 

The function print gives the dimensions, colour and area of the Rectangle instance.

In the main function of Rectangle, obtain and validate user input for the Rectangle's dimensions and colour. Create 2 Rectangle instances and compare their area. [Hint: check for type and negative numbers]

Solution:


    #include <iostream>
    #include <sstream>

    class Rectangle
    {
    private:
        int length, breadth;
        std::string colour;

    public:
        Rectangle();
        Rectangle(int, int, std::string);
        ~Rectangle();
        int getArea();
        std::string print();
        int compare(Rectangle);
    };

    Rectangle::Rectangle()
    {
        length = 0;
        breadth = 0;
        colour = "";
    }

    Rectangle::Rectangle(int length, int breadth, std::string colour)
    {
        this->length = length;
        this->breadth = breadth;
        this->colour = colour;
    }

    Rectangle::~Rectangle()
    {
    }

    int Rectangle::getArea()
    {
        return this->length * this->breadth;
    }

    std::string Rectangle::print()
    {
        std::stringstream ps;
        ps << "nLength: " << this->length
        << "nBreadth: " << this->breadth
        << "nColour: " << this->colour
        << "nArea: " << this->getArea() << std::endl;
        return ps.str();
    }

    int Rectangle::compare(Rectangle rect)
    {
        if (this->getArea() > rect.getArea())
            return 1;
        else if (this->getArea() < rect.getArea())
            return -1;
        return 0;
    }

    int main(int argc, char const *argv[])
    {
        int len, br;
        std::string col;

        // std::cout << "Enter dimensions for Rectangle 1:n"
        //           << "Length:";
        while (std::cin >> len)
        {
            if (len > 0)
                break;
            if (len <= 0)
                std::cout << "Length should be greater than 0n";
        }
        // std::cout << "Breadth:";
        while (std::cin >> br)
        {
            if (br > 0)
                break;
            if (br <= 0)
                std::cout << "Breadth should be greater than 0" << std::endl;
        }
        // std::cout << "Color:";
        std::cin.ignore();
        std::cin >> col;
        Rectangle rect1(len, br, col);

        // std::cout << "Enter dimensions for Rectangle 2:n"
        //           << "Length:";
        while (std::cin >> len)
        {
            if (len > 0)
                break;
        }
        // std::cout << "Breadth:";
        while (std::cin >> br)
        {
            if (br > 0)
                break;
        }
        // std::cout << "Color:";
        std::cin.ignore();
        std::cin >> col;
        Rectangle rect2(len, br, col);

        std::cout << "Rectangle 1n"
                << rect1.print() << std::endl;
        std::cout << "Rectangle 2n"
                << rect2.print() << std::endl;

        if (rect1.compare(rect2) == 1)
            std::cout << "Rectangle 1 is bigger than Rectangle 2" << std::endl;
        else if (rect1.compare(rect2) == -1)
            std::cout << "Rectangle 2 is bigger than Rectangle 1" << std::endl;
        else
            std::cout << "Rectangle 1 and Rectangle 2 are equal" << std::endl;

        return 0;
    }  

Output:


    12
    54
    Red
    24
    32
    Green
  
    Rectangle 1
    
    Length: 12
    Breadth: 54
    Colour: Red
    Area: 648
    
    Rectangle 2
    
    Length: 24
    Breadth: 32
    Colour: Green
    Area: 768
    
    Rectangle 2 is bigger than Rectangle 1

Question 2 - Student Records

In a UML Diagram, design a Student class with the following attributes:-

    name (max 30 characters)
    rollNumber (between 1 and 260)
    mobileNumber (10 digits)
    emailAddress (must contain '@' and then '.')
    attendance (between 0 and 1, where 1 is 100% attendance)

Provide the following functions:-

    getName, getRollNumber, ...
    setName, setRollNumber, ...
    print, which outputs the Student details in a comma-delimited string

    e.g. Donald Duck, 123, 1234567890, donald@duck.com, 0.00

The Student records are managed by the StudentManager class, which holds the main() loop.

StudentManager
- studentList:Student[10]
* getStudentInput:Student
* sortByRollNumber:Student[]
* sortByAttendance:Student[]
* printAttendanceReport(filename, sortBy:bool) : bool

The function printAttendanceReport outputs the list of students to a user-specified filename. If sortBy is true, the student list will be sorted by roll number, else the student list will be sorted by attendance (followed by roll number).

Provide the following user menu:

  1. Enter Student Details
  2. Update Student Mobile Number
  3. Update Student Email Address
  4. Print Attendance Report by Roll Number
  5. Print Attendance Report by Attendance
  6. Exit

Solution:


#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>

class Student
{
private:
    std::string name;
    int rollNumber;

public:
    long mobileNumber;
    std::string emailAddress;
    double attendance;

    Student();
    ~Student();
    std::string getName();
    int getRollNumber();
    void setName(std::string);
    void setRollNumber(int);
    std::string print();
};

Student::Student()
{
    this->name = "";
    this->rollNumber = 0;
    this->mobileNumber = 0;
    this->emailAddress = "";
    this->attendance = 0;
}

Student::~Student()
{
}

std::string Student::getName()
{
    return name;
}

int Student::getRollNumber()
{
    return rollNumber;
}

void Student::setName(std::string name)
{
    this->name = name;
}

void Student::setRollNumber(int rollNumber)
{
    this->rollNumber = rollNumber;
}

std::string Student::print()
{
    std::stringstream ps;
    ps << name << "," << rollNumber << "," << mobileNumber << "," << emailAddress << "," << attendance;
    return ps.str();
}

class StudentManager
{
private:
    std::vector<Student> studentList;

public:
    StudentManager();
    ~StudentManager();
    Student getStudentInput();
    void addStudent(Student);
    bool isEmpty();
    Student getStudent(int);
    bool setStudent(int, Student);
    std::vector<Student> sortByRollNumber();
    std::vector<Student> sortByAttendance();
    bool printAttendanceReport(std::string, bool);
};

StudentManager::StudentManager()
{
}

StudentManager::~StudentManager()
{
}

void StudentManager::addStudent(Student student)
{
    studentList.push_back(student);
}

Student StudentManager::getStudent(int rollno)
{
    for (int i = 0; i < studentList.size(); i++)
    {
        if (studentList[i].getRollNumber() == rollno)
        {
            return studentList[i];
        }
    }
    return Student();
}

bool StudentManager::setStudent(int rollno, Student student)
{
    for (int i = 0; i < studentList.size(); i++)
    {
        if (studentList[i].getRollNumber() == rollno)
        {
            studentList[i] = student;
            return true;
        }
    }
    return false;
}

bool StudentManager::isEmpty()
{
    return studentList.empty();
}

Student StudentManager::getStudentInput()
{
    Student student;
    std::string name;
    int rollNumber;
    long mobileNumber;
    std::string emailAddress;
    double attendance;
    std::cout << "Enter name: ";
    std::cin.ignore();
    std::getline(std::cin, name);
    std::cout << "Enter roll number: ";
    std::cin >> rollNumber;
    std::cout << "Enter mobile number: ";
    std::cin >> mobileNumber;
    std::cout << "Enter email address: ";
    std::cin.ignore();
    std::cin >> emailAddress;
    std::cout << "Enter attendance: ";
    std::cin >> attendance;
    student.setName(name);
    student.setRollNumber(rollNumber);
    student.mobileNumber = mobileNumber;
    student.emailAddress = emailAddress;
    student.attendance = attendance;
    return student;
}

std::vector<Student> StudentManager::sortByRollNumber()
{
    int N = this->studentList.size();
    std::vector<Student> studentList(N);
    for (int i = 0; i < N; i++)
    {
        studentList[i] = this->studentList[i];
    }
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N - i - 1; j++)
        {
            if (studentList[j].getRollNumber() > studentList[j + 1].getRollNumber())
            {
                std::swap(studentList[j], studentList[j + 1]);
            }
        }
    }
    return studentList;
}

std::vector<Student> StudentManager::sortByAttendance()
{
    int N = this->studentList.size();
    std::vector<Student> studentList(N);
    for (int i = 0; i < N; i++)
    {
        studentList[i] = this->studentList[i];
    }
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N - i - 1; j++)
        {
            if (studentList[j].attendance > studentList[j + 1].attendance)
            {
                std::swap(studentList[j], studentList[j + 1]);
            }
            else if ((studentList[j].attendance == studentList[j + 1].attendance) && (studentList[j].getRollNumber() > studentList[j + 1].getRollNumber()))
            {
                std::swap(studentList[j], studentList[j + 1]);
            }
        }
    }
    return studentList;
}

bool StudentManager::printAttendanceReport(std::string filename, bool sortBy)
{
    std::ofstream report;
    report.open(filename);

    std::vector<Student> studentList;

    if (sortBy)
    {
        studentList = sortByRollNumber();
    }
    else
    {
        studentList = sortByAttendance();
    }

    for (Student stud : studentList)
    {
        report << stud.print() << std::endl;
    }

    report.close();

    return true;
}

int main(int argc, char const *argv[])
{
    StudentManager mngr;
    int ch = 0;
    int rollNumber;
    Student stud;
    std::string filename;

    while (ch != 5)
    {
        std::cout << "n======Student Manager======" << std::endl;
        std::cout << "0.  Enter Student Detailsn"
                  << "1.  Update Student Mobile Numbern"
                  << "2.  Update Student Email Addressn"
                  << "3.  Print Attendance Report by Roll Numbern"
                  << "4.  Print Attendance Report by Attendancen"
                  << "5.  Exitn"
                  << std::endl;
        std::cout << "Enter your choice: ";
        std::cin >> ch;

        switch (ch)
        {
        case 0:
            mngr.addStudent(mngr.getStudentInput());
            break;
        case 1:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }
            std::cout << "Enter roll number: ";
            std::cin >> rollNumber;
            stud = mngr.getStudent(rollNumber);
            if (stud.getRollNumber() == 0)
            {
                std::cout << "Student not found"
                          << std::endl;
                break;
            }
            std::cout << "Enter Mobile number: ";
            std::cin >> stud.mobileNumber;
            mngr.setStudent(rollNumber, stud);
            break;
        case 2:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }
            std::cout << "Enter roll number: ";
            std::cin >> rollNumber;
            stud = mngr.getStudent(rollNumber);
            if (stud.getRollNumber() == 0)
            {
                std::cout << "Student not found"
                          << std::endl;
                break;
            }
            std::cout << "Enter Email address: ";
            std::cin.ignore();
            std::cin >> stud.emailAddress;
            mngr.setStudent(rollNumber, stud);
            break;

        case 3:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }

            std::cout << "Enter filename: ";
            std::cin.ignore();
            std::getline(std::cin, filename);
            mngr.printAttendanceReport(filename, true);
            break;

        case 4:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }

            std::cout << "Enter filename: ";
            std::cin.ignore();
            std::getline(std::cin, filename);
            mngr.printAttendanceReport(filename, false);
            break;

        case 5:
            std::cout << "Exiting..." << std::endl;
            break;

        default:
            std::cout << "Invalid choice" << std::endl;
            break;
        }
    }

    return 0;
}

Output:


    ======Student Manager======
    0.  Enter Student Details
    1.  Update Student Mobile Number
    2.  Update Student Email Address
    3.  Print Attendance Report by Roll Number
    4.  Print Attendance Report by Attendance
    5.  Exit
    
    Enter your choice: 0
    Enter name: Bhola
    Enter roll number: 45
    Enter mobile number: 32
    Enter email address: bholaeatschola@gmail.com
    Enter attendance: 78
    
    ======Student Manager======
    0.  Enter Student Details
    1.  Update Student Mobile Number
    2.  Update Student Email Address
    3.  Print Attendance Report by Roll Number
    4.  Print Attendance Report by Attendance
    5.  Exit
    
    Enter your choice: 3
    Enter filename: report
    
    ======Student Manager======
    0.  Enter Student Details
    1.  Update Student Mobile Number
    2.  Update Student Email Address
    3.  Print Attendance Report by Roll Number
    4.  Print Attendance Report by Attendance
    5.  Exit
    
    Enter your choice: 5
    Exiting...

File Contents:

Bhola,45,32,bholaeatschola@gmail.com,78
Share:

Programming with C++ - Day2 || Wong Edition || B.Tech Diaries

Lab #2 - C++ Basics (Pointers, FileIO)

Question 1 - Outlet Sales Report

Modify Lab 1 Question 2 to use the following functions:-


    /*********************************************************************/
    /* getSales obtains user input for the outlets                       */
    /* aptr - pointer to an array of double                              */
    /* size - size of array                                              */
    /*********************************************************************/
    void getSales(double * aptr, int size);


    **********************************************************************/
    /* calcTotalSales calculates the total sales for all outlets         */
    /* aptr - pointer to an array of double                              */
    /* size - size of array                                              */
    /* returns total as double                                           */
    /*********************************************************************/
    double calcTotalSales(const double * aptr, int size);

Save your sales report by using the following code snippet:-

    #include <fstream>
    ...
    
        ofstream outfile;
    
        outfile.open("report.txt");
        outfile << ... << endl;
        ....
        outfile.close();
    
        cout << "File written successfully" << endl;

Solution:


    #include <iostream>
    #include <iomanip>
    #include <fstream>
    
    void printbar(std::string store, double sales, double sales_max, std::ofstream &outfile)
    {
        outfile << std::setw(12) << std::left << store << ": \t";
        for (int j = 0; j < int(sales * 50.0 / sales_max); j++)
        {
            outfile << "*";
        }
        outfile << std::endl;
    }
    
    void getSales(double *aptr, int size)
    {
        for (int i = 0; i < size; i++)
        {
            // std::cout << "Enter sales for day " << i + 1 << ": ";
            std::cin >> aptr[i];
        }
    }
    
    double calcTotalSales(const double *aptr, int size)
    {
        double total = 0;
        for (int i = 0; i < size; i++)
        {
            total += aptr[i];
        }
        return total;
    }
    
    int main(int argc, char const *argv[])
    {
        std::string date = "July 22, 2019", manager = "Tutu Pal";
        std::string store_names[5] = {"City Centre", "Park Street", "Rajarhat", "South City", "Dum Dum"};
    
        std::ofstream outfile;
    
        int size = 5, max = 0;
        double *aptr = new double[size];
    
        getSales(aptr, size);
    
        for (int i = 0; i < size; i++)
        {
            if (aptr[i] > aptr[max])
            {
                max = i;
            }
        }
    
        outfile.open("report.txt");
    
        outfile << "\nDate:\t" << date << "\nName of Sales Manager:\t" << manager << "\n"
                << std::endl;
    
        for (int i = 0; i < size; i++)
        {
            printbar(store_names[i], aptr[i], aptr[max], outfile);
        }
    
        outfile << "\nThe store with the top sales on " << date << " is " << store_names[max] << std::endl;
    
        outfile << "\nThe total sales is $";
        outfile << std::setprecision(2) << std::fixed << calcTotalSales(aptr, size)
                << ".\n"
                << std::endl;
    
        outfile.close();
    
        std::cout << "File written successfully" << std::endl;
        return 0;
    }   

Input:


456
652 
64
12
35
File written successfully

Output:


Date:	July 22, 2019
Name of Sales Manager:	Tutu Pal

City Centre : 	**********************************
Park Street : 	**************************************************
Rajarhat    : 	****
South City  : 	
Dum Dum     : 	**

The store with the top sales on July 22, 2019 is Park Street

The total sales is $1219.00.

Question 2 - Country List

Read a list of countries from the file countries.txt, and sort them in reverse alphabetical order, i.e. Zambia first and Australia last.


    #include <fstream>
    ...

        ifstream infile;
        int number;

        infile.open("numbers.txt");
        while (!infile.eof()) {
            infile >> number;
            cout << number << endl;
        }

        infile.close();

Handle the situation where the stipulated filename cannot be found.

Solution:


    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <algorithm>
    
    int main(int argc, char const *argv[])
    {
        std::ifstream infile;
        std::vector<std::string> countries;
        std::string country;
    
        int i, j;
    
        infile.open("countries.txt");
    
        if (infile.fail())
        {
            std::cout << "Error opening file" << std::endl;
            return 1;
        }
    
        while (std::getline(infile, country))
        {
            countries.push_back(country);
        }
        infile.close();
    
        for (int i = 0; i < countries.size(); i++)
        {
            for (int j = 0; j < countries.size() - i - 1; j++)
            {
                if (std::lexicographical_compare(countries[j].begin(), countries[j].end(), countries[j + 1].begin(), countries[j + 1].end()))
                {
                    std::swap(countries[j], countries[j + 1]);
                }
            }
        }
    
        for (std::string country : countries)
        {
            std::cout << country << std::endl;
        }
    
        return 0;
    }    

Input:


United Kingdom
Italy
Brazil
Russia
South Africa
Chile
Portugal
Greece
Kenya
Egypt
Zambia
Malaysia
Japan
Australia

Output:


Zambia
United Kingdom
South Africa
Russia
Portugal
Malaysia
Kenya
Japan
Italy
Greece
Egypt
Chile
Brazil
Australia    

Question 3 - Vowels & Consonants

Write a function that returns the number of vowels in a given string. Write another function that returns the number of consonants in a given string.

Use the 2 functions to perform the following:-

  1. The user is asked to enter a string.
  2. The program displays the following menu:
    • Count the number of vowels in the string
    • Count the number of consonants in the string
    • Count both the vowels and consonants in the string
    • Enter another string
    • Exit the program
  3. The program performs the operation selected by the user and repeats until the user selects E to exit the program.

Solution:


    #include <iostream>

    int no_of_vowels(std::string str)
    {
        int count = 0;
        for (char c : str)
        {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                count++;
        }
        return count;
    }
    int no_of_consonants(std::string str)
    {
        int count = 0;
        for (char c : str)
        {
            if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'))
                count++;
        }
        return count;
    }
    
    int main(int argc, char const *argv[])
    {
        std::string s;
        std::cout << "Enter a string:" << std::endl;
        std::getline(std::cin, s);
        char ch = '';
        while (ch != 'E')
        {
            std::cout << "nOptions:"
                      << "nA) Count the number of vowels in the string"
                      << "nB) Count the number of consonants in the stringnC) Count both the vowels and consonants in the string"
                      << "nD) Enter another string"
                      << "nE) Exit the program"
                      << "nEnter your choice: ";
            std::cin >> ch;
            switch (ch)
            {
            case 'A':
                std::cout << "The number of vowels in the string is: " << no_of_vowels(s) << std::endl;
                break;
            case 'B':
                std::cout << "The number of consonants in the string is: " << no_of_consonants(s) << std::endl;
                break;
            case 'C':
                std::cout << "The number of vowels in the string is: " << no_of_vowels(s) << std::endl;
                std::cout << "The number of consonants in the string is: " << no_of_consonants(s) << std::endl;
                break;
            case 'D':
                std::cout << "Enter a string:" << std::endl;
                std::cin.ignore();
                std::getline(std::cin, s);
                break;
            case 'E':
                std::cout << "Exiting the program..." << std::endl;
                break;
            default:
                std::cout << "Invalid choice. Please try again." << std::endl;
                break;
            }
        }
        return 0;
    }

Output:


Enter a string:
React component that displays a spinner via spin.js until your component is loaded.

Options:
A) Count the number of vowels in the string
B) Count the number of consonants in the string
C) Count both the vowels and consonants in the string
D) Enter another string
E) Exit the program
Enter your choice: A
The number of vowels in the string is: 25

Options:
A) Count the number of vowels in the string
B) Count the number of consonants in the string
C) Count both the vowels and consonants in the string
D) Enter another string
E) Exit the program
Enter your choice: E
Exiting the program...

Share:

OS Lab Assignment || Das Edition || B. Tech Diaries

OS Lab

Assignment #1

Perform the following operations

  1. Create three directories named letter, report and assignment.
    
    mkdir letter
    mkdir report
    mkdir assignment
  2. Move to directory letter.
    
    cd letter
  3. Create two directories named friendly and formal under letter directory.
    
    mkdir friendly formal
  4. Move to directory report using only one command (from directory letter)
    
    cd ../report
  5. Create three directories called personal, business, school under directory report (Using one command).
    
    mkdir ../assignment/unit
  6. Create a directory called unit under the assignment directory without moving from the directory report (Using one command).
    
    mkdir personal business school
  7. Move to your HOME directory.
    
    cd ~
  8. Recursively list all the directories you have created and draw the directory structure.
    
    ls -LR

Assignment #2

Perform the following operations

  1. Change the working directory to friendly and use pluma from the command line to create A1.text with the following personal information.
    Name: <student_name>
    Email: <email_id>
    Id: <student_id>
    Date: <date>
    
    cd friendly
    pluma A1.text
    
    Name:   Purbayan Chowdhury
    Email:  pur.cho.99@gmail.com
    Id:     90
    Date:   01/02/2020
  2. Exit pluma and copy the new file A1.txt to B1.txt. Verify that both files exist by listing the directory.
    
    cp A1.txt B1.txt
    ls
    # A1.txt B1.txt
  3. Rename the B1.txt file to A.txt, then list the directory, and remove the A1.txt file, and list the directory again.
    
    mv B1.txt A.txt
    rm A1.txt
    ls
    # A.txt
  4. Set A.txt to have read and write permission for the owner, but keep file private from others.
    
    chmod 600 A.txt
  5. Now check the file permissions for A.txt.
    
    ls -l
    # total 4
    # -rw------- 1 pur.cho.99 pur.cho.99 0 Jan  2  2020 A.txt
  6. Move to your HOME directory.
    
    cd ~
  7. Recursively list all the directories you have created and draw the directory structure.
    
    ls -LR

Assignment #3

Perform the following operations using date and cal command.

  1. Display 3 months from now
    
    cal -A2
  2. Display Monday as the first day
    
    ncal -M
  3. Display September of 1752
    
    cal -m 9 1752
  4. Display 3 months for the data around 9th March 2015
    
    ncal -m 3 2015 -A2 -H 2015-03-09
  5. Display day of the week
    
    date +%A
  6. Display week number of the year
    
    date +%V
  7. Display date on this format - 12th April 1998
    
    date +'%_d %_B %_Y'
  8. Display date on this format - 12th Jan'95
    
    date +"%_d %_b'%_y"
  9. Display date on this format - 05/07/98
    
    date +%d/%m/%y
  10. Display current date with hour minute second
    
    date +%H:%M:%S

Assignment #4

Open a terminal window and show the manual page for the command grep.

Suppose that you have a file abc.txt whose contents are

  1. Your name in sentence case.
  2. Your name in capital case.
  3. Your name in small case.
  4. Email id.
  5. Mobile number.
  6. Phone number.
  7. Your hobby.
  8. A blankline.
  9. Your grade in Data Structures and Algorithms.
  10. Any special character.
  11. A string like 112@456.
  12. Dates in different format.

Write the grep command for the following instructions:

  1. Find your name in small letter.
    
    grep "^[a-z]+ [a-z]+$" abc.txt
    # purbayan chowdhury
  2. Find your name anywhere in file.
    
    grep -i "^[a-z]+ [a-z]+$" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
  3. Show two lines before & after your hobby.
    
    grep -A2 -B2 "^Hobby: [a-zA-Z]+$" abc.txt
    # Hobby: cricket
    #
    # A+
  4. Show your mail id.
    
    grep -i "^[a-z_]+[a-z0-9._]+@[a-z]{3,}.[a-z]{2,}$" abc.txt
    # pur.cho.99@gmail.com
  5. Show all the lines containing @.
    
    grep "@" abc.txt
    # pur.cho.99@gmail.com
    # 112@456
  6. Show all the lines without @.
    
    grep -v "@" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
    # 7898765432
    # +91789765432
    # Hobby: cricket
    #
    # A+
    # 112@456
    # 12/08/2020
  7. Find how many times your name is present in the file.
    
    grep -c "^[a-zA-Z]+ [a-zA-Z]+$" abc.txt
    # 3
  8. Find the line number where your name is present in the file in small case or capital.
    
    grep -n "^[a-z]+ [a-z]+$|^[A-Z]+ [A-Z]+$|" abc.txt
    # 2:PURBAYAN CHOWDHURY
    # 3:purbayan chowdhury
  9. Print all lines that contain a mobile number.
    
    grep "^[0-9]{10}$" abc.txt
    # 7898765432
  10. Print all lines that contain a phone number with an extension.
    
    grep "^[0-9]{2,3}[-][0-9]{6,8}$" abc.txt
    # +91789765432
  11. Print all lines containing a vowel.
    
    grep -i "[aeiou]" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
    # pur.cho.99@gmail.com
    # Hobby: cricket
  12. Print all lines that do not begin with a capital S.
    
    grep -v "^S" abc.txt
    # Purbayan Chowdhury
    # PURBAYAN CHOWDHURY
    # purbayan chowdhury
    # 7898765432
    # +91789765432
    # Hobby: cricket
    #
    # A+
    # 112@456
    # 12/08/2020
  13. Is there any day of a date?
    
    grep -i "^[0-3][0-9]/[0-9]{2}/[0-9]{4}$" abc.txt
    # 12/08/2020

Assignment #5

  • Write a program to print current process ID, parent process ID and child process ID.
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main()
    {
        pid_t pid, ppid, cpid;
    
        pid = getpid();
        ppid = getppid();
        cpid = fork();
    
        printf("Process ID: %d\n", pid);
        printf("Parent Process ID: %d\n", ppid);
        printf("Child Process ID: %d\n", cpid);
    
        return 0;
    }
    
    Process ID: 8
    Parent Process ID: 7
    Child Process ID: 0
  • Show that the orders of print statement in the child and parent process are different at different times of execution. Find the reason behind it.
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main()
    {
        if(fork()==0)
            printf("Child \n");
        else
            printf("Parent \n");
        return 0;
    }
    
    Parent
    Child
    On the execution, both programs (parent and child) will execute independent of each other starting from if statement. In the parent, since pid is non-zero, it prints the parent and on the child, since pid is zero, it prints the child later.
  • Show that parent process ID depends on Shell.
    
    gcc -o exe process1.c
    ./exe
    # Current process: 3148
    # Parent process: 3141
    
    
    gcc -o exe process1.c
    ./exe
    # Current process: 3156
    # Parent process: 3149
    The reason for this is that the parent process ID depends on the Shell.
  • Write a C program using fork() system call that generates the Fibonacci sequence in the child process. The number of the sequence will be provided in the command line. For example, if 5 is provided, the first five numbers in Fibonacci will be output by the childd process. Because the parent and child processes have their own copies of the data, it will be necessary for child to output the sequence.
    
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    int main()
    {
        int a=0, b=1, c=a+b, i, ii;
        pid_t pid;
        printf("Enter the number of terms: ");
        scanf("%d", &ii);
        if(ii<=0)
        {
            printf("Please enter a positive number.\n");
            return 0;
        } else {
            pid = fork();
            if(pid == 0)
            {
                printf("Child is producing the Fibonacci series.....\n");
                for(i=0; i<ii; i++)
                {
                    printf("%d ", c);
                    a=b;
                    b=c;
                    c=a+b;
                }
                printf("\n");
                printf("Child ends.\n");
            } else {
                printf("Parent is waiting for child to finish......\n");
                wait(NULL);
                printf("Parent ends.\n");
            }
        }
        return 0;
    }
    
    /*
    Output:
    */
    
    Enter the number of terms: 5
    Parent is waiting for child to finish......
    Child is producing the Fibonacci series.....
    0 1 1 2 3 5
    Child ends.
    Parent ends.

Assignment #6

  1. Take two numbers through command line argument. Write a shell script to interchange the contents of the variables. Do the same operation without using any third variable.
    
    #!/bin/bash
    file1=$1
    file2=$2
    echo "Before swapping: "$file1 $file2
    temp=$file1
    file1=$file2
    file2=$temp
    echo "After swapping: "$file1 $file2
    
    
    Before swapping: 1 2
    After swapping: 2 1
    
    #!/bin/bash
    file1=$1
    file2=$2
    echo "Before swapping: "$file1 $file2
    file1=$((file1 + file2))
    file2=$((file1 - file2))
    file1=$((file1 - file2))
    echo "After swapping: "$file1 $file2
    
    Before swapping: 1 2
    After swapping: 2 1
  2. Write a shell script to check whether a given year is leap year or not.
    
    #!/bin/bash
    year=$1
    y=$((!(year % 4) && (year % 100 || !(year % 400))))
    if [ $y -eq 1 ]; then
        echo "$year is a leap year"
    else
        echo "$year is not a leap year"
    fi
    
    Enter the year: 2000
    2000 is a leap year
  3. Write a shell script to find the value of y using
    Y(x, n) = {1+x^2 when n=1}
              {1+x/n when n=2}
              {1+2x when n=3}
              {1+nx when n>3 or n<1}
    
    
    #!/bin/bash
    x=$1
    n=$2
    if [ $n -lt 1 ]; then
        echo "Enter a positive number"
    elif [ "$n" -eq "1" ]; then
        echo $((1+x*x))
    elif [ "$n" -eq "2" ]; then
        echo $((1+x/n))
    elif [ "$n" -eq "3" ]; then
        echo $((1+2*x))
    else
        echo $((1+n*x))
    fi
  4. Determine grade as per following rules using a switch case:
    • If marks are more than 90, grade is O
    • If marks are more than 80, grade is E
    • If marks are more than 70, grade is A
    • If marks are more than 60, grade is B
    • If marks are more than 50, grade is C
    • If marks are less than 50, grade is F
    
    #!/bin/bash
    marks=$1
    case $marks in
        [9][0-9]|100)
            echo "O grade"
            ;;
        [8][0-9]|[8][0-9][0-9])
            echo "E grade"
            ;;
        [7][0-9]|[7][0-9][0-9])
            echo "A grade"
            ;;
        [6][0-9]|[6][0-9][0-9])
            echo "B grade"
            ;;
        [5][0-9]|[5][0-9][0-9])
            echo "C grade"
            ;;
        [4][0-9]|[4][0-9][0-9]|[3][0-9]|[3][0-9][0-9])
            echo "F grade"
            ;;
        *)
            echo "Invalid marks"
            ;;
    esac
    
    
    
    Enter the marks: 90
    O grade

Assignment #7,8,9

Write a program to implement the following scheduling.

  • First Come First Served Scheduling
  • Priority Scheduling
  • Shortest Job First Scheduling
  • Round Robin Scheduling
  • Shortest Remaining Time First Scheduling

#include <iostream>
#include <algorithm>

class process
{
    int _id, _atime, _ttime, _btime, _wtime, _priority;

public:
    process()
    {
        _id = 0;
        _atime = 0;
        _ttime = 0;
        _btime = 0;
        _wtime = 0;
        _priority = 0;
    }
    process(int id, int atime, int btime, int priority = 0)
    {
        this->_id = id;
        this->_atime = atime;
        this->_btime = btime;
        this->_ttime = 0;
        this->_wtime = 0;
        this->_priority = priority;
    }
    void print()
    {
        printf("%d\t%d\t%d\t%d\t%d\t%d\n", this->_id, this->_btime, this->_atime, this->_ttime, this->_wtime, this->_priority);
    };
    int id()
    {
        return this->_id;
    }
    int atime()
    {
        return this->_atime;
    }
    int btime()
    {
        return this->_btime;
    }
    int ttime()
    {
        return this->_ttime;
    }
    int wtime()
    {
        return this->_wtime;
    }
    int priority()
    {
        return this->_priority;
    }

    void t_time(int ttime)
    {
        this->_ttime = ttime;
    };
    void w_time(int wtime)
    {
        this->_wtime = wtime;
    };
};

void fcfs(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return p1.atime() < p2.atime(); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
    {
        if (ctime - p[i].atime() < 0)
            ctime += p[i].atime();
        ctime += p[i].btime();
        p[i].t_time(ctime - p[i].atime());
        avg_t_time += p[i].ttime();
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void psa(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.priority() < p2.priority()) || (p1.priority() == p2.priority() && p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
    {
        if (ctime - p[i].atime() < 0)
            ctime += p[i].atime();
        ctime += p[i].btime();
        p[i].t_time(ctime - p[i].atime());
        avg_t_time += p[i].ttime();
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void sjf(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.btime() < p2.btime()) || (p1.btime() == p2.btime() && p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
    {
        if (ctime - p[i].atime() < 0)
            ctime += p[i].atime();
        ctime += p[i].btime();
        p[i].t_time(ctime - p[i].atime());
        avg_t_time += p[i].ttime();
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\tPriority\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void rr(process *p, int n, int quantum = 4)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    int min = -1, st[n], left_jobs = n;

    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
        st[i] = p[i].btime();

    while (left_jobs > 0)
    {
        for (i = 0; i < n; i++)
        {
            if (st[i] == 0 || ctime < p[i].atime())
                continue;
            if (st[i] > quantum)
            {
                ctime += quantum;
                st[i] -= quantum;
            }
            else
            {
                ctime += st[i];
                st[i] = 0;
                p[i].t_time(ctime - p[i].atime());
                avg_t_time += p[i].ttime();
                left_jobs--;
            }
        }
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\tPriority\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

void srtf(process *p, int n)
{
    std::sort(p, p + n, [](process p1, process p2)
                { return (p1.atime() < p2.atime()); });
    int i, ctime = 0, avg_t_time = 0, avg_w_time = 0;
    int min = -1, st[n], left_jobs = n;

    // Turn Around Time Calculation
    for (i = 0; i < n; i++)
        st[i] = p[i].btime();

    while (left_jobs != 0)
    {
        min = -1;
        for (i = 0; i < n; i++)
        {
            if (st[i] == 0 || ctime < p[i].atime())
                continue;
            if (min == -1 || st[i] < st[min])
                min = i;
        }
        ctime++;
        st[min]--;
        if (st[min] == 0)
        {
            left_jobs--;
            p[min].t_time(ctime - p[min].atime());
            avg_t_time += p[min].ttime();
        }
    }
    avg_t_time /= n;

    // Waiting Time
    for (i = 0; i < n; i++)
    {
        p[i].w_time(p[i].ttime() - p[i].btime());
        avg_w_time += p[i].wtime();
    }
    avg_w_time /= n;

    std::sort(p, p + n, [](process p1, process p2)
                { return p1.id() < p2.id(); });
    printf("Id\tB_Time\tA_Time\tT_Time\tW_Time\tPriority\n");
    for (i = 0; i < n; i++)
    {
        p[i].print();
    }

    printf("Average TAT: \t%d\nAverage WT: \t%d\n", avg_t_time, avg_w_time);
}

int main()
{
    int n;
    n = 5;
    process p[n];

    // Process p1
    p[0] = process(1, 0, 24, 1);
    // Process p2
    p[1] = process(2, 3, 12, 4);
    // Process p3
    p[2] = process(3, 2, 6, 3);
    // Process p4
    p[3] = process(4, 0, 18, 0);
    // Process p5
    p[4] = process(5, 4, 3, 3);

    printf("\nFCFS:\n");
    fcfs(p, n);
    printf("\nPSA:\n");
    psa(p, n);
    printf("\nSJF:\n");
    sjf(p, n);
    printf("\nSRTF:\n");
    srtf(p, n);
    printf("\nRR:\n");
    rr(p, n);

    return 0;
}

FCFS:
Id	B_Time	A_Time	T_Time	W_Time
1	24	0	24	0	1
2	12	3	57	45	4
3	6	2	46	40	3
4	18	0	42	24	0
5	3	4	59	56	3
Average TAT: 	45
Average WT: 	33

PSA:
Id	B_Time	A_Time	T_Time	W_Time
1	24	0	42	18	1
2	12	3	60	48	4
3	6	2	46	40	3
4	18	0	18	0	0
5	3	4	47	44	3
Average TAT: 	42
Average WT: 	30

SJF:
Id	B_Time	A_Time	T_Time	W_Time	Priority
1	24	0	67	43	1
2	12	3	22	10	4
3	6	2	11	5	3
4	18	0	43	25	0
5	3	4	3	0	3
Average TAT: 	29
Average WT: 	16

SRTF:
Id	B_Time	A_Time	T_Time	W_Time	Priority
1	24	0	63	39	1
2	12	3	20	8	4
3	6	2	9	3	3
4	18	0	39	21	0
5	3	4	3	0	3
Average TAT: 	26
Average WT: 	14

RR:
Id	B_Time	A_Time	T_Time	W_Time	Priority
1	24	0	63	39	1
2	12	3	42	30	4
3	6	2	27	21	3
4	18	0	59	41	0
5	3	4	15	12	3
Average TAT: 	41
Average WT: 	28
Share:

Programming with C++ - Day1 || Wong Edition || B.Tech Diaries

Lab #1 - C++ Basics (Loops, Functions, Arrays)

  1. A software company sells a package that retails for $99. Quantity discounts are given according to the following table.

    Quantity Discount
    10-19 20%
    20-49 30%
    50-99 40%
    100 or more 50%

    Write a program that asks for the number of units sold and computes the total cost of the purchase. Declare the discount as constants.Input Validation: Make sure the number of units is greater than 0.

    
    #include <iostream>
    
    int main(int argc, char const *argv[])
    {
        int qty;
        // std::cout << "Enter no of units sold: ";
        while (std::cin >> qty)
        {
            if (qty > 0)
                break;
            std::cout << "No of units should be greater than 0" << std::endl;
            // std::cout << "Enter no of units sold: ";
        }
        double dis = 0;
        if (qty < 20)
            dis = 0.2;
        else if (qty < 50)
            dis = 0.3;
        else if (qty < 100)
            dis = 0.4;
        else
            dis = 0.5;
        double price = qty * 99 * (1 - dis);
        printf("\nTotal price is: %.2lf\n", price);
        return 0;
    }
  2. Write a program that generates the day's sales report for five stores. The program asks for the sales figures as input anddisplays a bar graph comparing each store's sales.Create each bar in the bar graph by displaying a row of asterisks. Each asterisk represents $100 of sales.Here is an example of the program's output.

    
    Date: July 22, 2019
    Name of Sales Manager: Tutu Pal
    CityCentre:   **********
    Park Street:  ************
    Rajarhat:     ******************
    South City:   ********
    Dum Dum:      *******************
    The store with the top sales on July 22, 2019 is Dum Dum.
    The total sales is $xxxx.

    Use the function void printbar(string store, int sales) to generate the bar chart.

    
    #include <iostream>
    
    void printbar(std::string store, double sales, double sales_max)
    {
        std::cout << store << ": \t";
        for (int j = 0; j < int(sales * 50.0 / sales_max); j++)
        {
            std::cout << "*";
        }
        std::cout << std::endl;
    }
    
    int main(int argc, char const *argv[])
    {
        std::string date = "July 22, 2019", manager = "Tutu Pal";
        std::string store_names[5] = {"City Centre", "Park Street", "Rajarhat", "South City", "Dum Dum"};
        double store_sales[5], total_sales = 0;
        int max = 0;
    
        for (int i = 0; i < 5; i++)
        {
            // std::cout << "Enter sales for store " << i + 1 << ": ";
            std::cin >> store_sales[i];
            total_sales += store_sales[i];
            if (store_sales[max] < store_sales[i])
                max = i;
        }
        std::cout << "\nDate:\t" << date << "\nName of Sales Manager:\t" << manager << std::endl;
    
        for (int i = 0; i < 5; i++)
        {
            printbar(store_names[i], store_sales[i], store_sales[max]);
        }
    
        std::cout << "\nThe store with the top sales on " << date << " is " << store_names[max] << std::endl;
        printf("\nThe total sales is $%.2lf.\n\n", total_sales);
        return 0;
    }
  3. Write a C++ program to implement the Number Guessing Game. In this game the computer chooses a random number between 1 and 100, and the player tries to guess the number in as few attempts as possible. Each time the player enters a guess, the computer tells him whether the guess is too high, too low, or right. Once the player guesses the number, the game is over.

    
    #include <iostream>
    
    int main(int argc, char const *argv[])
    {
        std::cout << "======NUMBER GUESSING GAME=======" << std::endl;
        int guess, number = rand() % 200 + 1;
        std::cout << "Guess a number between 1 and 200" << std::endl;
        std::cin >> guess;
        while (guess != number)
        {
            if (guess > number)
            {
                std::cout << "Your guess is too high!!" << std::endl;
            }
            else
            {
                std::cout << "Your guess is too low!!" << std::endl;
            }
            std::cin >> guess;
        }
        std::cout << "You guessed the number " << number << std::endl;
        return 0;
    }
Share:

OS Lab Project || Das Edition || B.Tech Diaries

Multilevel Queue Scheduling

Multilevel Queue Scheduling in Operating System

A multilevel queue scheduling is a scheduling algorithm where there are multiple queues for each type of process. The selection of level is done through priority based scheduling while each level queue scheduling are dependent entirely on the type of process. Round robin for upper layers and First come first served for lower layers. 

Source Code


/** 
 * @author  Purbayan Chowdhury
 * @brief   Multilevel Feedback Queue Scheduling Algorithm 
*/

#include <bits/stdc++.h>

class process
{
public:
    int _id, _atime, _wtime, _ttime, _btime, _priority, _percent;
    process(int id = 0, int atime = 0, int btime = 0, int priority = 0) : _id(id), _atime(atime), _btime(btime), _priority(priority), _percent(btime) {}
};

/**
 * Q3 = Batch Process having Low Priority with FCFS Algorithm 
 * Q2 = Interactive Process having Medium Priority with Priority Scheduling 
 * Q1 = System Process having High Priority with Round Robin Algorithm
*/

std::vector<process *> sortArrivalTime(std::vector<process *> p)
{
    int i, j;
    process *k;
    for (i = 0; i < p.size() - 1; i++)
    {
        for (j = p.size() - 1; j >= i + 1; j--)
        {
            if (p[j]->_atime < p[j - 1]->_atime)
            {
                k = p[j - 1];
                p[j - 1] = p[j];
                p[j] = k;
            }
        }
    }
    return p;
}

int FCFS(std::vector<process *> p, int stime, int etime)
{
    int i, c = etime - stime;
    if (c <= 0)
        return etime;
    for (i = 0; i < p.size(); i++)
    {
        if (p[i]->_percent > c)
        {
            p[i]->_percent -= c;
            return etime;
        }
        else
        {
            c = c - p[i]->_percent;
            p[i]->_ttime = stime + p[i]->_percent;
            stime += p[i]->_percent;
            p[i]->_percent = 0;
        }
    }
    return etime - c;
}

std::vector<process *> sortPriority(std::vector<process *> p)
{
    int i, j;
    process *k;
    for (i = 0; i < p.size() - 1; i++)
    {
        for (j = p.size() - 1; j >= i + 1; j--)
        {
            if (p[j]->_atime < p[j - 1]->_atime && (p[j]->_atime < p[j - 1]->_atime && p[j]->_priority < p[j - 1]->_priority))
            {
                k = p[j - 1];
                p[j - 1] = p[j];
                p[j] = k;
            }
        }
    }
    return p;
}

int PR(std::vector<process *> p, int stime, int etime)
{
    p = sortPriority(p);
    int i, c = etime - stime;
    if (c <= 0)
        return etime;
    for (i = 0; i < p.size(); i++)
    {
        if (p[i]->_percent > c)
        {
            p[i]->_percent -= c;
            return etime;
        }
        else
        {
            c = c - p[i]->_percent;
            p[i]->_ttime = stime + p[i]->_percent;
            stime += p[i]->_percent;
            p[i]->_percent = 0;
        }
    }
    return etime - c;
}

int RR(std::vector<process *> p, int stime, int etime)
{
    int i = 0, j, c = etime - stime, ct = p.size();
    int quantum = 4;
    while (ct != 0 && c != 0)
    {
        if (c < quantum)
        {
            if (p[i]->_percent > c)
            {
                p[i]->_percent -= c;
                return etime;
            }
            else
            {
                c = c - p[i]->_percent;
                p[i]->_ttime = stime + p[i]->_percent;
                stime += p[i]->_percent;
                p[i]->_percent = 0;
                ct--;
            }
            i++;
            if (i == p.size())
                break;
        }
        else
        {
            if (p[i]->_percent != 0)
            {
                if (p[i]->_percent > quantum)
                {
                    stime += quantum;
                    p[i]->_percent -= quantum;
                    c -= quantum;
                }
                else
                {
                    stime += p[i]->_percent;
                    p[i]->_ttime = stime;
                    c -= p[i]->_percent;
                    p[i]->_percent = 0;
                    ct--;
                }
            }
            i++;
            i = i % p.size();
        }
    }
    return etime - c;
}

std::vector<int> calculateTime(std::vector<process *> p)
{
    std::vector<int> t(2);
    t[0] = t[1] = 0;
    int i;
    for (i = 0; i < p.size(); i++)
    {
        p[i]->_ttime -= p[i]->_atime;
        t[0] += p[i]->_ttime;
        p[i]->_wtime = p[i]->_ttime - p[i]->_btime;
        t[1] += p[i]->_wtime;
    }
    return t;
}

void displayTime(std::vector<process *> p)
{
    std::cout << std::setfill(' ') << std::setw(10) << "Id"
              << std::setfill(' ') << std::setw(10) << "Priority"
              << std::setfill(' ') << std::setw(10) << "A_Time"
              << std::setfill(' ') << std::setw(10) << "B_Time"
              << std::setfill(' ') << std::setw(10) << "T_Time"
              << std::setfill(' ') << std::setw(10) << "W_Time"
              << std::endl;
    for (int i = 0; i < p.size(); i++)
        std::cout << std::setfill(' ') << std::setw(10) << p[i]->_id
                  << std::setfill(' ') << std::setw(10) << p[i]->_priority
                  << std::setfill(' ') << std::setw(10) << p[i]->_atime
                  << std::setfill(' ') << std::setw(10) << p[i]->_btime
                  << std::setfill(' ') << std::setw(10) << p[i]->_ttime
                  << std::setfill(' ') << std::setw(10) << p[i]->_wtime
                  << std::endl;
}

void displayPercent(std::vector<process *> p)
{
    int i;
    for (i = 0; i < p.size(); i++)
        printf("%d\t", p[i]->_percent);
    printf("\n");
}

int main(int argc, char const **argv)
{
    std::vector<process *> q[3];
    int n = 10, i, j, c = 10;
    std::vector<process *> p(n);
    std::vector<process> cp(n); // 10 Processes
    cp[0] = process(1, 7, 5, 1);
    cp[1] = process(2, 4, 2, 0);
    cp[2] = process(3, 5, 7, 1);
    cp[3] = process(4, 0, 6, 0);
    cp[4] = process(5, 3, 24, 0);
    cp[5] = process(6, 7, 4, 2);
    cp[6] = process(7, 0, 7, 1);
    cp[7] = process(8, 3, 12, 2);
    cp[8] = process(9, 2, 7, 1);
    cp[9] = process(10, 4, 8, 2);
    for (i = 0; i < n; i++)
        p[i] = &cp[i];
    p = sortArrivalTime(p);
    int pburst = 0, pend = 0;
    int co = 0;
    // displayPercent(p);
    while (c != 0)
    {
        c = 10;
        for (i = 0; i < n; i++)
        {
            if (p[i]->_percent != 0)
            {
                if (p[i]->_atime <= pburst)
                {
                    q[p[i]->_priority].push_back(p[i]);
                }
                else
                {
                    pend = p[i]->_atime;
                    break;
                }
            }
        }
        if (pend == pburst)
            pend = 999;
        for (j = 0; j < 3; j++)
        {
            switch (j)
            {
            case 0:
                if (!(q[j].empty()))
                    pburst = RR(q[j], pburst, pend);
                break;
            case 1:
                if (!(q[j].empty()))
                    pburst = PR(q[j], pburst, pend);
                break;
            case 2:
                if (!(q[j].empty()))
                    pburst = FCFS(q[j], pburst, pend);
                break;
            }
            if (pburst == pend)
                break;
        }
        for (i = 0; i < n; i++)
            if (p[i]->_percent == 0)
                c--;
        q[0].clear();
        q[1].clear();
        q[2].clear();
    }
    std::vector<int> t = calculateTime(p);
    displayTime(p);
    printf("Average Turnaround Time: %d\nAverage Waiting Time: %d\n", t[0], t[1]);
    return 0;
}


Share: