Professional Documents
Culture Documents
Assg 4
Assg 4
1)Define task and synchronization? What are the two types of task and synchronization?
Ans:TASK:Task is a unit of work being executed. Task in Operating System may be synonymous
with process. A task is a subpart of a job. Tasks combine to form a job. The task may be a thread,
process, a single job and much more. A task is termed as a thread when it is undergoing execution.
Sequential Tasks: Tasks that execute one after the other in a specific order.
Parallel Tasks: Tasks that can be executed simultaneously, often to improve performance.
Concurrent Tasks: Tasks that appear to overlap in their execution, but they may not
necessarily be executed simultaneously.
2) What is naming encapsulation? Why is naming encapsulation important for developing large
programs? Does Java support naming encapsulation ?
Ans:In large programs, managing global names becomes crucial, and both C++ and Java provide
mechanisms to organize names into logical groupings, which helps improve code organization,
readability, and prevent naming conflicts, this mechanism is called naming encapsulation.
In C++, a namespace is a declarative region that provides a scope to the identifiers (names) contained
within it. It allows you to organize code into logical units, reducing the likelihood of naming conflicts.
Yes, Java supports naming encapsulation through the use of packages.In Java, the equivalent of
namespaces is called packages. A package is a way to organize classes into logical groupings. It helps
in avoiding naming conflicts and providing a structured hierarchy for class organization.
Example:
package vehicles;
public class Car {
public void start() {
System.out.println("The car has started.");
}}
Hardware Requires multiple physical processing Can be achieved with a single processing
Requirement units (cores, processors, etc.). unit.
Can handle a higher workload and Can lead to decreased performance as the
Performance
increase system performance number of tasks increases
When any process wishes to access the shared variables in the monitor, it needs to access it through the
procedures. These processes line up in a queue and are only provided access when the previous
process releases the shared variables. Only one process can be active in a monitor at a time.
Semaphores:A semaphore is an integer variable that allows many processes in a parallel system to
manage access to a common resource like a multitasking OS. It is an integer variable (S), and it is
initialized with the number of resources in the system. The wait() and signal() methods are the only
methods that may modify the semaphore (S) value. When one process modifies the semaphore value,
other processes can't modify the semaphore value simultaneously.
5) Define classes, object, public and private with examples in C++, Java.
Ans:
CLASS:A Class is a user-defined data type that has data members and member functions.Data
members are the data variables and member functions are the functions used to manipulate these
variables together, these data members and member functions define the properties and behavior of the
objects in a Class.
OBJECT:An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
// Class definition
class Car {
public:
string brand;
string model;
int year;
void displayInfo() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}};
int main() {
Car myCar; // Creating an object of the Car class
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;
return 0; }
public and private are keywords that are known as an access modifier or specifier. It restricts the
scope or accessibility of a class, constructor, variables, methods, and data members. It depends on
which it is applied. Access modifiers control whether other classes can use a particular field or invoke
a particular method.
Access Modifier within class within package outside package outside package
by subclass only
Private yes no no no
class Z
{
public:
Z() {
cout<<"Constructor called"<<endl; // constructor
}
~Z() {
cout<<"Destructor called"<<endl; // destructor
} };
int main()
{
Z z1; // Constructor Called
int a = 1;
if(a==1)
{
Z z2; // Constructor Called
} // Destructor Called for z2
} // Destructor called for z1
with Ada.Text_IO;
use Ada.Text_IO;
procedure Concurrency_Example is
task Task1;
task Task2;
begin
Null; -- Allow tasks to execute concurrently
Put_Line("Program completed.");
end Concurrency_Example;
OUTPUT: Task 1: 1
Task 2: 1
Task 1: 2
Task 2: 2
Task 1: 3
Task 2: 3
Task 1: 4
Task 2: 4
Task 1: 5
Task 2: 5
Program completed.
Task Body:It describes the action that takes place when a rendezvous occurs. A task that sends a
message is suspended while waiting for the message to be accepted and during the rendezvous
Entry points in the spec are described with accept clauses in the body accept.
Entry Points: Entry points are similar to procedures but are used for communication between tasks.
Rendezvous: A rendezvous occurs when one task invokes an entry point of another task.
Select Statement:The ‘select’ statement in Ada allows a task to announce its readiness to accept any
one of several possible entries.
Guarded Entries:Entries can be guarded by conditions (when clauses) to specify under what
conditions an entry can be accepted.
Symmetry of Rendezvous:While a task attempting an entry call waits for the destination task to
accept it, a task attempting to accept an entry has more freedom and need not be forced to wait for a
specific rendezvous or any rendezvous at all.
Else Clause in Select:The ‘select’ statement can include an ‘else’ clause, which is executed
immediately if no entries are pending.
Ans:In object-oriented programming (OOP), inheritance is a mechanism that allows a class to inherit
properties and behaviors from another class. It is a fundamental concept in OOP that promotes code
reuse and establishes relationships between classes.
Inheritance is based on a hierarchical relationship between classes, where a derived class (also known
as a subclass or child class) inherits the characteristics of a base class (also known as a superclass or
parent class). The derived class extends the functionality of the base class by adding new features or
overriding existing ones.
Inheritance in object-oriented programming comes in several forms. The five commonly recognized
types of inheritance are:
1.Single Inheritance:In single inheritance, a class can inherit from only one base class. This is the
simplest form of inheritance.
2.Multiple Inheritance:Multiple inheritance allows a class to inherit from more than one base class.
This can lead to the "diamond problem" where ambiguities arise if multiple base classes have a
common ancestor.
3.Multilevel Inheritance:In multilevel inheritance, a class serves as a base class for another class,
which, in turn, becomes the base class for another class, creating a chain of inheritance.
4.Hierarchical Inheritance:Hierarchical inheritance involves a single base class with multiple derived
classes. Each derived class can further serve as a base class for other classes.
// Base class
class Shape {
protected:
int width;
int height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
// Derived class
class Rectangle : public Shape {
public:
int getArea() {
return width * height;
}
};
int main() {
Rectangle rect;
rect.setDimensions(5, 7);
cout << "Area of the rectangle: " << rect.getArea() << endl;
return 0; }
// Base class
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
// Intermediate class inheriting from Animal
class Mammal extends Animal {
void run() {
System.out.println("Mammal is running");
}
}
3a) Explain in detail about the logic programming language, its features and applications.
Ans:Logic programming is a type of declarative programming, where the programmer specifies what
needs to be done rather than explicitly specifying how to do it.
Logic programming languages like Datalog or ASP (Answer Set Programming) are known as purely
declarative languages, because programs written in them consist of declarations rather than
assignments and control flow statements.
One of the key features of logic programming is the use of logic rules and inference mechanisms for
computation. Prolog (Programming in Logic) is one of the most well-known logic programming
languages.
FEATURES OF LOGIC PROGRAMMING:
5.Backtracking:
Backtracking is a fundamental feature in logic programming. If a certain path in the computation leads
to a dead-end, the system can backtrack and explore alternative paths to find a solution.
6.Unification:
Unification is a process in logic programming where values are matched and bound to variables. It is a
key mechanism for working with variables in rules and queries.
7.Non-determinism:
Logic programming allows for non-deterministic computation, meaning that multiple solutions to a
problem can be explored. This is achieved through backtracking and the exploration of alternative
paths.
8.Recursive Programming:
Recursive programming is a common practice in logic programming. Rules can call themselves,
allowing for concise and elegant descriptions of repetitive tasks.
PROLOG:
Prolog is a prominent logic programming language that emerged in 1972 as a result of a collaboration
between Kowalski and Colmerauer. Prolog uses a formal logic named first-order logic. First-order
% Rules
has_skin(X, fur) :- mammal(X), has_fur(X).
has_skin(X, scales) :- reptile(X), has_scales(X).
% Queries
?- has_skin(cat, fur). % Does a cat have fur?
?- has_skin(dog, scales). % Does a dog have scales?
?- has_skin(snake, scales). % Does a snake have scales?
?- has_skin(lizard, scales). % Does a lizard have scales?
2. Computational Linguistics: Logic programming is utilized for tasks like grammar parsing,
semantic analysis, language understanding, and machine translation.
3. Database Systems: Logic programming languages like Datalog are used for querying and reasoning
over relational databases, making it easier to express complex relationships and constraints.
6.Game Playing:Some game-playing systems use logic programming to make strategic decisions,
analyze game states, and determine optimal moves.
7. Expert Systems: Logic programming is well-suited for building expert systems that can reason and
provide expert-level advice in specific domains like medicine, finance, and engineering.
8. Decision Support Systems: Logic programming can be used to model decision-making processes,
allowing for the evaluation of different scenarios and the selection of optimal choices based on
predefined rules and constraints.
9. Robotics: Logic programming is utilized in robotics for tasks like perception, planning, and control,
enabling robots to reason about their environment and make intelligent decisions.
Handler form:
when exception_choice{|exception_choice} => statement_sequence
……….
[when others =>
Statement_sequence]
exception_choice form:
exception_name | others
When:The when clause is used within the exception block to specify which exception or group of
exceptions the handler should catch.
procedure ExceptionHandling is
begin
-- Some code that might raise an exception
declare
Result : Integer;
begin
Result := 10 / 0; -- Division by zero, raises an exception
exception
when Constraint_Error =>
Ada.Text_IO.Put_Line("Caught Constraint_Error: Division by zero is not allowed.");
when others =>
Ada.Text_IO.Put_Line("Caught an exception: " & Exception_Name(Exception_Occurrence));
end;
Ada provides a set of built-in exceptions that can be raised in various situations. These exceptions are
predefined in the Ada language and cover a range of error conditions.
Ans: a) Abstract Data Type:Abstract Data type (ADT) is a type (or class) for objects whose behavior
is defined by a set of values and a set of operations. The definition of ADT only mentions what
operations are to be performed but not how these operations will be implemented. It does not specify
how data will be organized in memory and what algorithms will be used for implementing the
operations. It is called “abstract” because it gives an implementation-independent view.
The process of providing only the essentials and hiding the details is known as abstraction.
An Abstract Data Type is a user-defined data type that satisfies the following two conditions:
– The representation of, and operations on, objects of the type are defined in a single syntactic unit.
– The representation of objects of the type is hidden from the program units that use these objects, so
the only operations possible are those provided in the type's definition
Advantages of Data Abstraction:
Advantage of the first condition – Program organization, modifiability (everything associated with a
data structure is together), and separate compilation.
Advantage the second condition – Reliability--by hiding the data representations, user code cannot
directly access objects of the type or depend on the representation, allowing the representation to be
changed without affecting user code.
Design Issues:
Can abstract types be parameterized?
What access controls are provided?
Examples of ADT in C++:
// C++ Abstract Data Type - Stack
template <class T>
class Stack {
public:
virtual void push(T item) = 0;
virtual T pop() = 0;
virtual T peek() const = 0;
virtual bool isEmpty() const = 0;
virtual ~Stack() {}
};
// Implementation using an array
template <class T>
class ArrayStack : public Stack<T> {
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int top;
public:
ArrayStack() : top(-1) {}
T pop() override {
if (top >= 0)
return data[top--];
else
return T(); // Return default value for simplicity
}
// Other methods
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
c) Smalltalk:Smalltalk, born in the early 1970s at Xerox PARC, is a historic and influential
programming language that laid the foundation for modern object-oriented programming (OOP).
Despite being one of the oldest programming languages, Smalltalk’s concepts and principles continue
to influence software development today.
In Smalltalk, everything is an object, and all interactions occur through message passing between
objects. Smalltalk supports key OOP concepts such as encapsulation, inheritance, and polymorphism.
Encapsulation allows you to bundle data and methods together within an object, providing a way to
hide the internal details and provide a clean interface for interacting with the object.
Inheritance enables you to create new classes by extending existing ones, inheriting their attributes and
behaviors. This promotes code reuse and allows for hierarchical relationships between classes.
Polymorphism allows objects of different classes to respond to the same message in different ways.
This flexibility allows for more modular and flexible code.
Smalltalk also emphasizes dynamic typing, meaning that the types of objects are checked at runtime
rather than compile time. This promotes flexibility and allows for more expressive code.
Live Development Environment is interactive and allows changes to the code to be made on-the-fly,
and the entire system can be modified and extended dynamically.
Overall, Smalltalk provides a rich and powerful environment for developing object-oriented
applications.
Example Smalltalk program :
Object subclass: Person [
| name age |