Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Assignment Questions(UNIT-IV) CSE(A&B)

DECCAN COLLEGE OF ENGINEERING AND TECHNOLOGY


Darussalam, Hyderabad-500001
B.E V Semester 2023-2024
SUBJECT:PRINCIPLES OF PROGRAMMING LANGUAGES
[UNIT-IV]

SHORT QUESTION AND ANSWERS

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.

Two General Categories of Tasks


1.Heavyweight tasks execute in their own address space.
2.Lightweight tasks all run in the same address space.
A task is disjoint if it does not communicate with or affect the execution of any other task in the
program in any way.

SYNCHRONIZATION:Synchronization is the coordination of multiple tasks or threads to ensure


they execute in a well-defined order and avoid conflicts or race conditions. It involves mechanisms
that control the access to shared resources, ensuring consistency and preventing data corruption.
Kinds of synchronization:
1.Cooperation: Task A must wait for task B to complete some specific activity before task A can
continue its execution, e.g., the producer-consumer problem
2.Competition: Two or more tasks must use some resource that cannot be simultaneously used,
e.g., a shared counter. Competition is usually provided by mutually exclusive access.

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.

CSE-Dept 1 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Example of a C++ namespace:


namespace MyNamespace {
int someVariable;
void someFunction() {
// Code here
}
}

// Accessing members of the namespace


int main() {
MyNamespace::someVariable = 42;
MyNamespace::someFunction();
return 0;
}

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.");
}}

// Accessing members of the package


import vehicles.Car;
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); }}

3) Difference between physical and logical concurrency?


Ans:

CSE-Dept 2 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Feature Physical Concurrency Logical Concurrency

It refers to the simultaneous time-sharing


It refers to the simultaneous execution of execution of multiple tasks on a single
Execution
multiple tasks on multiple physical physical processor or core using
Mechanism
processors or cores.. techniques like multitasking or
multithreading

Hardware Requires multiple physical processing Can be achieved with a single processing
Requirement units (cores, processors, etc.). unit.

Apparent parallelism created through


Parallelism True parallelism at the hardware level.
interleaved execution.

Can handle a higher workload and Can lead to decreased performance as the
Performance
increase system performance number of tasks increases

Physical Concurrency Offers better Logical ConcurrencyHas limited


Scalability
scalability scalability

Resource utilization may be lower, as


Resource High resource utilization due to parallel
tasks share a single processing unit, but
Utilization execution.
still efficient.

Operating Systems(multitasking), Web


Examples Distributed computing clusters, High-
Performance servers, Supercomputers. servers, Database management systems.

4) What advantages do monitors have over semaphores?


Ans:Monitor:A Monitor type high-level synchronization construct. It is an abstract data type. The
Monitor type contains shared variables and the set of procedures that operate on the shared variable.

CSE-Dept 3 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

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.

Advantages of Monitors over Semaphores:


1.Monitors are easier to implement than semaphores.
2.Mutual exclusion in monitors is automatic while in semaphores, mutual exclusion needs to be
implemented explicitly.
3.Monitors can overcome the timing errors that occur while using semaphores.
4.Shared variables are global to all processes in the monitor while shared variables are hidden in
semaphores.
5.Synchronization in monitors is provided by condition variables while there are no condition variables
in semaphores.
6.Access to the monitor is through protected shared variables while access to shared variables in
semaphores is not protected.

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.

Example program in C++ to demonstrate class and object:


#include <iostream>
using namespace std;

// Class definition
class Car {
public:
string brand;
string model;
int year;

CSE-Dept 4 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

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;

myCar.displayInfo(); // Calling the object's method

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

Public yes yes yes yes

Private yes no no no

Example program in Java to demonstrate public and private access modifiers:

public class AccessModifiersExample {


// Public member accessible from outside the class
public String publicMessage = "This is a public message.";

// Private member accessible only within the class


private String privateMessage = "This is a private message.";

// Public method to access private member


public void displayMessages() {
System.out.println("Public Message: " + publicMessage);
System.out.println("Private Message: " + privateMessage);
}

CSE-Dept 5 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

public static void main(String[] args) {


// Create an object of the class
AccessModifiersExample example = new AccessModifiersExample();

// Access public member directly


System.out.println("Accessing Public Member: " + example.publicMessage);

// Access private member using a public method


example.displayMessages();
}
}

6) Define constructor and destructor.


Ans:Constructor: A constructor is a member function of a class that has the same name as the class
name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to
allocate the memory to an object of the class. It is called whenever an instance of the class is created. It
can be defined manually with arguments or without arguments.
Syntax:
ClassName()
{
//Constructor's Body
}
Destructor: Like a constructor, Destructor is also a member function of a class that has the same name
as the class name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is
called while the object of the class is freed or deleted. In a class, there is always a single destructor
without any parameters so it can’t be overloaded.
Syntax:
~ClassName()
{
//Destructor's Body
}
Implementation of Constructor and Destructor:
#include <iostream>
using namespace std;

class Z
{
public:
Z() {
cout<<"Constructor called"<<endl; // constructor
}

~Z() {
cout<<"Destructor called"<<endl; // destructor

CSE-Dept 6 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

} };
int main()
{
Z z1; // Constructor Called
int a = 1;
if(a==1)
{
Z z2; // Constructor Called
} // Destructor Called for z2
} // Destructor called for z1

LONG QUESTION AND ANSWERS

1a) Explain concurrency mechanism in Ada?


Ans:Concurrency in programming refers to the ability of a system to perform more than one task at the
same time.
The Ada programming language has built in support for concurrent programming through the use of
tasks. A task in Ada is similar to a thread in other programming languages but with more sophisticated
and safer facilities for synchronization and communication. Tasks are defined with the task keyword
and can have their own declarations and executable parts.
A concurrent Ada program can include any number of tasks - declared by
task My_Task is
-- Task declarations and body
end My_Task;

Task Communication and Synchronization:


A key element in managing concurrency in Ada is the concept of tasks and protected objects.While
tasks help us to structure our program in concurrent flows, protected objects provide a way to
safeguard shared data, ensuring that only one task can access them at a time, thereby avoiding race
conditions.
Ada provides synchronization mechanisms such as entry points and selective waiting to coordinate the
execution of tasks. Entry points are used to control access to shared resources and ensure mutual
exclusion.
Example of a protected body in Ada:
protected body Shared_Data is
entry Set_Value(New_Value : Integer) when Data = 0 is
begin
Data := New_Value;
end Set_Value;

entry Get_Value(Result : out Integer) when Data /= 0 is


begin
Result := Data;
end Get_Value;
end Shared_Data;

CSE-Dept 7 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Example program in Ada that demonstrates the use of concurrency mechanisms:

with Ada.Text_IO;
use Ada.Text_IO;

procedure Concurrency_Example is
task Task1;
task Task2;

task body Task1 is


begin
for I in 1 .. 5 loop
delay 1.0; -- Simulate some work
Put_Line("Task 1: " & Integer'Image(I));
end loop;
end Task1;

task body Task2 is


begin
for J in 1 .. 5 loop
delay 1.0; -- Simulate some work
Put_Line("Task 2: " & Integer'Image(J));
end loop;
end Task2;

begin
Null; -- Allow tasks to execute concurrently

-- Wait for tasks to complete


Put_Line("Press Enter to continue...");
Ada.Text_IO.New_Line;

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.

CSE-Dept 8 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

1b)Explain the message passing in Ada.


Ans:In Ada, message passing is a mechanism used for communication between tasks. It allows tasks
to exchange data or synchronize their execution by sending and receiving messages. To implement
message passing in Ada, one can use various constructs such as protected objects, selective wait
statements, and rendezvous.
Rendezvous is a synchronization mechanism where tasks can synchronize their execution by
rendezvousing at a shared entry point. Tasks can send and receive messages at the entry point, ensuring
that the sender and receiver synchronize their actions.

The Ada 83 Message-Passing Model


– Ada tasks have specification and body parts, like packages; the spec has the interface, which is the
collection of entry points:
task Task_Example is
entry ENTRY_1 (Item : in Integer);
end Task_Example;

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_name (formal parameters) do


...
end entry_name
Example of a Task Body
task body Task_Example is
begin
loop
accept Entry_1 (Item: in Float) do

end Entry_1;
end loop;
end Task_Example;

Ada Message Passing Semantics


● The task executes to the top of the accept clause and waits for a message.
● During execution of the accept clause, the sender is suspended.
● accept parameters can transmit information in either or both directions.
● Every accept clause has an associated queue to store waiting messages.

CSE-Dept 9 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Message Passing: Server/Actor Tasks:


● A task that has accept clauses, but no other code is called a server task (the
example above is a server task)
● A task without accept clauses is called an actor task
– An actor task can send messages to other tasks
– Note: A sender must know the entry name of the receiver, but not vice versa (asymmetric)

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.

CSE-Dept 10 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Example of Task Select Statement:


select
when not BUFFER_FULL =>
accept STORE(C: in CHARACTER) do
-- Implementation for storing a character in the buffer
end STORE;
or
when not BUFFER_EMPTY =>
accept RETRIEVE(C: out CHARACTER) do
-- Implementation for retrieving a character from the buffer
end RETRIEVE;
or
accept PRODUCER_DONE do
-- Implementation for signaling that the producer is done
end PRODUCER_DONE;
end select;

2) Explain the concept of Inheritance with examples in C++ and Java.

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.

5.Hybrid (Virtual) Inheritance:Hybrid inheritance is a combination of multiple and hierarchical


inheritance. It is often achieved using virtual inheritance to address issues like the diamond problem.

CSE-Dept 11 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Example of a C++ program that demonstrates single-level inheritance:


#include <iostream>
using namespace std;

// 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; }

Example of a Java program that demonstrates multi-level inheritance:

// 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");
}
}

CSE-Dept 12 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

// Derived class inheriting from Mammal


class Dog extends Mammal {
void bark() {
System.out.println("Dog is barking");
}}
// Main class to demonstrate multi-level inheritance
public class MultiLevelInheritanceDemo {
public static void main(String[] args) {
// Creating an object of the derived class
Dog myDog = new Dog();
// Calling methods from various levels of inheritance
myDog.eat(); // Inherited from Animal
myDog.run(); // Inherited from Mammal
myDog.bark(); // Specific to Dog class
}}
Example of a C++ program that demonstrates Hierarchical inheritance:
#include <iostream>
// Base class (parent class)
class Shape {
public:
void draw() {
std::cout << "Drawing a generic shape" << std::endl;
} };
// Derived class (child class)
class Circle : public Shape {
public:
void draw() {
std::cout << "Drawing a circle" << std::endl;
} };
// Another derived class
class Square : public Shape {
public:
void draw() {
std::cout << "Drawing a square" << std::endl;
} };
int main() {
Circle circle;
Square square;
// Using inherited method
circle.draw(); // Calls Circle's draw method
square.draw(); // Calls Square's draw method
return 0;
}

CSE-Dept 13 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

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:

1.Express Programs in the Form of Symbolic Logic:


Represent programs using symbolic logic, specifying relationships between entities and logical rules.

2.Use a Logical Inference Process to Produce Results:


Utilize a logical inference process to deduce conclusions and generate results based on the specified
logical rules and relationships.

3.Declarative Rather Than Procedural:


Emphasize a declarative programming style where only the desired results are stated, without
specifying detailed step-by-step procedures for achieving them.

4.Facts and Rules:


Propositions in logic programming can take the form of facts or rules. Facts represent known
information, while rules specify relationships and conditions that lead to new information.

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

CSE-Dept 14 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

logic uses quantified variables in logical statements to define an expression.


In prolog programming language, the logic of the program is expressed in terms of mathematical
relations, which represent the rules and facts on which the program runs. Computations are performed
by running queries on these relations.
EXAMPLE PROLOG PROGRAM:
% Facts
mammal(cat).
mammal(dog).
reptile(snake).
reptile(lizard).
has_fur(cat).
has_fur(dog).
has_scales(snake).
has_scales(lizard).

% 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?

APPLICATIONS OF LOGIC PROGRAMMING:


Logic programming has several applications across various domains. Here are some common
applications:
1. Artificial Intelligence: Logic programming, such as Prolog, is widely used in AI for tasks like
expert systems, natural language processing, automated reasoning, and knowledge representation.

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.

4. Symbolic Mathematics: Logic programming can be used for symbolic manipulation of


mathematical expressions, allowing for solving equations, simplifying expressions, and performing
symbolic differentiation and integration.

CSE-Dept 15 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

5. Software Verification: Logic programming is employed for formal verification of software


systems, ensuring correctness and identifying potential bugs or errors.

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.

3b) Explain how exceptions are handled in Ada with examples.


Ans:In Ada, exception handling is a crucial feature that allows the program to gracefully handle
unexpected situations or errors during execution. Exceptions in Ada are raised when an error condition
occurs, and the program can respond to these exceptions using a mechanism called exception handling.
In Ada, the structure for handling exceptions involves three main components:
Raise: The raise statement is used to explicitly raise an exception. This is typically done when an
error condition is detected.
Exception Handler:The exception block defines a handler for a specific exception or a group of
exceptions. It specifies the actions to be taken when an exception is raised.
The frame of an exception handler in Ada is either a subprogram body, a package body, a task, or a
block.
Exception handlers are usually local to the code in which the exception can be raised, they do not have
parameters.

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.

CSE-Dept 16 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Example program to demonstrate Exception Handling in Ada:


with Ada.Text_IO;

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.Text_IO.Put_Line("Program continues after exception handling.");


end ExceptionHandling;

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.

- CONSTRAINT_ERROR: The event group that occurs if a declaration constraint is violated,


for example, an index bound is exceeded.
-PROGRAM_ERROR:Raised for errors that are detectable at compile-time or elaboration time.
This includes violations of static semantics.
- NUMERIC_ERROR: Arithmetic errors, including underflow and overflow errors, division by
zero, etc.
- STORAGE_ERROR: Memory errors (including all allocation-related problems): the memory
region referred to is not available.
- TASKING_ERROR: Rendezvous is not possible with the given task.

4) Write a short note on- a) Abstract Data Type (ADT)


b) Encapsulation
c) Smalltalk

CSE-Dept 17 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

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;

CSE-Dept 18 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

public:
ArrayStack() : top(-1) {}

void push(T item) override {


if (top < MAX_SIZE - 1)
data[++top] = item;
}

T pop() override {
if (top >= 0)
return data[top--];
else
return T(); // Return default value for simplicity
}

T peek() const override {


if (top >= 0)
return data[top];
else
return T(); // Return default value for simplicity
}

bool isEmpty() const override {


return top == -1;
}
};

b) Encapsulation:Encapsulation is one of the four fundamental Object-Oriented Programming (OOP)


concepts and refers to the bundling of data and methods that operate on the data within a single unit
known as a class. It is about hiding the internal details of an object and providing a well-defined
interface for interacting with it. Encapsulation helps in achieving information hiding and modularity,
making the code more maintainable and scalable.
Advantages of encapsulation:
1.Information Hiding
2.Modularity
3.Code Organization
4.Code Reusability
5.Improved Maintenance
6.Security and Integrity:

CSE-Dept 19 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

Examples of Encapsulation in Java:

public class Student {


private String name;
private int age;

// Getter and Setter methods for encapsulated attributes


public String getName() {
return name;
}

public void setName(String newName) {


name = newName;
}

public int getAge() {


return age;
}

public void setAge(int newAge) {


if (newAge > 0) {
age = newAge;
}
}

// Other methods
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


// Using the encapsulated class
Student student1 = new Student();
student1.setName("John");
student1.setAge(20);

System.out.print("Student Information: ");


student1.displayInfo();
}
}

CSE-Dept 20 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

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 |

Person >> initializeWithName: aName age: anAge [


name := aName.
age := anAge.
]

Person >> displayInfo [


Transcript
show: 'Name: ', name;
show: ', Age: ', age printString;
cr.
]
]

"Creating instances of the Person class"


| person1 person2 |
person1 := Person new initializeWithName: 'Alice' age: 30.
person2 := Person new initializeWithName: 'Bob' age: 25.

CSE-Dept 21 Faculty:Afroze Begum


Assignment Questions(UNIT-IV) CSE(A&B)

"Displaying information for each person"


person1 displayInfo.
person2 displayInfo.

CSE-Dept 22 Faculty:Afroze Begum

You might also like