IT_SEM III_CPP LAB

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

DEPARTMENT OF INFORMATION TECHNOLOGY

Laboratory Manual
Second Year Semester-III
Subject: Computer Programming Paradigms Lab
(ITL303)

ODD Semester
Academic year 2024-25

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


PROFILE

Name of Student :
ARMIET PIN:
Roll No.
Exam Seat No.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


INDEX

Sr NAME OF EXPERIMENTS
no
1 Demonstrate Compilation and interpretation stages to students for C, C++, JAVA along with how to

debug the code.

2 At least two Programming Implementations Preferably in C++ to demonstrate concepts like

Encapsulation, Inheritance, Initialization and Finalization. Dynamic Binding.

3 Tutorial Introduction to Haskell programming environment.


4 Tutorial exercise on operators, types etc. in Haskell.
5 At least 5 Haskell Programs to demonstrate Functional Programming Concept.
6 Implement safetail with conditionals and guards, list comprehension, recursive multiplication using
addition, implementing Nim game with lists, generating infinite Fibonacci series, and a basic
calculator, all aimed at teaching Haskell's syntax and functional programming concepts effectively.

7 Tutorial Installation and working of SWI Prolog Environment.


8 Implement at least 5 Prolog programs to understand declarative programming concepts.
9 At least two Programs preferably in C++ and java to demonstrate Thread management and
synchronization.
10 A Program to understand Exception handling and Garbage collection, preferably in C++ and
JAVA.
11 At Least two implementations each implemented on multiple paradigms like procedural, object
oriented, functional, logic.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


VISION AND MISSION OF THE IT DEPARTMENT

Vision
To be a globally recognized, skilled, research oriented and communally responsible software and
hardware engineers for catering to the various industrial needs

Mission
M1: To impart high-quality education with a focus on entrepreneurship, social responsibility,
and professional ethics.

M2: To provide students and faculty members with opportunities to innovate and disseminate
knowledge with research capability.

M3: To undertake collaborative projects with academia and industry

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Program Educational Objectives (PEO):
Sr. PEO Code Program Educational Objectives Statements
No.
1. PEO1: Graduates must be knowledgeable in both
applied and fundamental engineering sciences
in order to comprehend engineering concepts
and formulate and resolve information
technology related challenges

2. PEO2: Motivate and prepare the graduates to pursue


higher studies, research and development thus
contributing to the ever Increasing academic
demands of the country.

3. PEO3: To inculcate managerial and entrepreneur


skills, ethical and professional attitudes to
meet the needs of industry.

4. PEO4: Create new methods / processes to meet the


needs of the society.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Program Specific Outcomes (PSO):
Sr. PSO Code Program Specific Outcomes Statements
No.
1. PSO1: Identify, analyze and develop software systems
using appropriate techniques and concepts
related to user experience, predictive analysis
and health care information systems through
Information Technology.

2. PSO2: Design an algorithm or process within realistic


constraints to meet the desired needs through
analytical, logical and problem-solving skills.

3. PSO3: Apply state of the art IT tools and


technologies, IT infrastructure management
abilities in treading innovative career path as a
prospective IT engineer.

4. PSO4: Educate students with proficiency in core areas


of Information Technology and related
engineering so as to comprehend engineering
trade-offs, analyze, design, and synthesize data
and technical concepts to create novel products
and solutions for the real life problems.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Program Outcomes
Sr.No PO Code Program Outcomes Statements
Engineering knowledge : Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
1 PO.1 complex engineering problems.

Problem analysis : Identify, formulate, review research literature, and


analyze complex Engineering problems reaching substantiated conclusions
2 PO.2
using first principles of mathematics natural sciences, and Engineering
sciences
Design / Development of Solutions : Design solutions for complex
Engineering problems and design system components or processes that meet
3 PO.3
the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and Environmental considerations
Conduct Investigations of Complex Problems : Use research-based
knowledge and research methods including design of experiments, analysis
4 PO.4
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern Tool Usage : Create, select, and apply appropriate techniques,
resources, and modern Engineering and IT tools including prediction and
5 PO.5
modeling to complex Engineering activities with an understanding of the
limitations.
6 PO.6 The Engineer and Society : Apply reasoning informed by the contextual

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice
Environment and Sustainability : Understand the impact of the professional
7 PO.7 Engineering solutions in societal and Environmental contexts, and
demonstrate the knowledge of, and need for sustainable development
Ethics : Apply ethical principles and commit to professional ethics and
8 PO.8
responsibilities and norms of the Engineering practice
9 PO.9 Individual and Team Work : Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
10 PO.10 Communication Skills : Communicate effectively on complex Engineering
activities with the Engineering community and with society at large, such as,
being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions
11 PO.11 Project Management and Finance : Demonstrate knowledge and
understanding of the Engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary Environments.
12 PO.12 Life-long : Learning Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest
context of technological change.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Lab Outcomes

LO Code Lab Outcomes Statements


LO.1 Implement Object Oriented concepts in C++.

LO.2 Design and Develop solution based on declarative programming paradigm


using functional and logic programming.
LO.3 Understand the multi threaded programs in Java and C++.
Understand the need and use of exception handling and garbage collection
LO.4
in C++ and JAVA.

LO.5 Implement a solution to the same problem using multiple paradigms.


Compare the implementations in multiple paradigms at coding and execution
LO.6
level.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw
Experiment No. 1
Aim: Demonstrate Compilation and interpretation stages to students for C, C++, JAVA along with how
to debug the code.
Theory:
In programming, the compilation and interpretation processes vary between languages like C, C++, and
Java. In C and C++, the programming process begins with preprocessing, where directives such as
#include and #define are handled.
 This is followed by compiling the preprocessed source code into assembly code specific to the
target architecture.
 The assembly code is then assembled into object code, which is further linked to create an
executable file.
 Debugging in C and C++ involves using tools like gdb, which allows developers to set
breakpoints, step through the code line by line, inspect variable values, and view the call stack to
understand program execution and resolve issues.

Java’s process differs as it compiles source code into platform-independent bytecode rather than native
machine code. This bytecode is executed by the Java Virtual Machine (JVM), which interprets or just-in-
time compiles it into native machine code. Debugging in Java typically occurs within integrated
development environments (IDEs) such as Eclipse or IntelliJ IDEA, which offer features like setting
breakpoints, stepping through code, and inspecting variable values. Additionally, command-line tools
like jdb provide alternative debugging options for Java programs. Understanding Java’s compilation
and execution model is crucial for troubleshooting and optimizing code to ensure proper functionality
across various platforms.

Setting up Libraries and Software:


In C/C++, standard libraries like libc (for C) and libstdc++ (for C++) provide essential functions and
data structures. In Java, the standard library (Java Standard Edition API) offers built-in classes and
methods for various programming tasks.

Installing GHC Compiler


The GHC (Glasgow Haskell Compiler) is a widely used compiler for the Haskell programming language.
GHC supports advanced features of Haskell, including its rich type system, lazy evaluation, and higher-
order functions. It also includes tools for profiling, debugging, and interacting with the Haskell runtime
system.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Compilation and Interpretation in C

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Debugging in C

Compilation and Interpretation in C++

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Debugging in C++

Output

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw
Conclusion: Understanding these stages and debugging techniques is crucial for
effective development and troubleshooting. Each language has its own tools and
processes, but the principles of code transformation and debugging remain
foundational to all programming.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 2
Aim: At least two Programming Implementations Preferably in C++ to demonstrate concepts like
Encapsulation, Inheritance, Initialization and Finalization. Dynamic Binding.

Theory: This experiment demonstrates encapsulation, inheritance, initialization, and dynamic


binding.

A Simple Banking System

This demonstrates encapsulation, inheritance, initialization, and dynamic binding.

Implementation 1. Base Class: Account

Encapsulation is demonstrated through private data members and public methods to access and modify
these members. Inheritance is shown by creating a derived class that inherits from this base class.

#include <iostream>
#include <string>
using namespace std;

// Base class
class Account {
private:
string accountNumber;
double balance;

public:
// Constructor to initialize account
Account(string number, double initialBalance) : accountNumber(number),
balance(initialBalance) {}

// Destructor
virtual ~Account() {
cout << "Account destructor called for " << accountNumber << endl;
}

// Method to deposit money


void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}

// Method to withdraw money

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


virtual void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
cout << "Insufficient funds or invalid amount" << endl;
}
}

// Method to display account info


virtual void display() const {
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: " << balance << endl;
}
};

// Derived class
class SavingsAccount : public Account {
private:
double interestRate;

public:
// Constructor to initialize savings account
SavingsAccount(string number, double initialBalance, double rate)
: Account(number, initialBalance), interestRate(rate) {}

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

// Overriding the withdraw method


void withdraw(double amount) override {
// Add a small fee for withdrawals
const double fee = 1.0;
Account::withdraw(amount + fee);
}

// Overriding the display method


void display() const override {
Account::display();
cout << "Interest Rate: " << interestRate << "%" << endl;
}
};

int main() {
Account* account = new SavingsAccount("123456", 1000.0, 2.5);

account->display();
account->deposit(200.0);
account->withdraw(100.0);

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


account->display();

delete account; // Calls the destructor for SavingsAccount and Account

return 0;
}

 Encapsulation: The Account class encapsulates accountNumber and balance with private
access modifiers. Public methods allow controlled access and modification.
 Inheritance: SavingsAccount inherits from Account, demonstrating how a derived class
extends the functionality of a base class.
 Initialization and Finalization: The constructors initialize objects, and destructors clean up
resources. Notice the virtual destructor in the base class to ensure proper cleanup of derived
class objects.
 Dynamic Binding: The withdraw and display methods are virtual, allowing for dynamic
binding. The SavingsAccount class overrides these methods, which are resolved at runtime.

Shape Hierarchy

This demonstrates encapsulation, inheritance, dynamic binding, and initialization.

Implementation 2. Base Class: Shape

A shape class hierarchy where different shapes have different implementations for calculating area
and displaying information.

#include <iostream>
#include <cmath>
using namespace std;

// Base class
class Shape {
public:
// Virtual destructor
virtual ~Shape() {
cout << "Shape destructor called" << endl;
}

// Pure virtual method for area


virtual double area() const = 0;

// Pure virtual method for display


virtual void display() const = 0;
};

// Derived class: Circle


class Circle : public Shape {

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


private:
double radius;

public:
// Constructor
Circle(double r) : radius(r) {}

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

// Override area method


double area() const override {
return M_PI * radius * radius;
}

// Override display method


void display() const override {
cout << "Circle with radius: " << radius << endl;
cout << "Area: " << area() << endl;
}
};

// Derived class: Rectangle


class Rectangle : public Shape {
private:
double width;
double height;

public:
// Constructor
Rectangle(double w, double h) : width(w), height(h) {}

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

// Override area method


double area() const override {
return width * height;
}

// Override display method


void display() const override {
cout << "Rectangle with width: " << width << " and height: " <<
height << endl;
cout << "Area: " << area() << endl;
}
};

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


int main() {
Shape* shapes[2];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 6.0);

for (int i = 0; i < 2; ++i) {


shapes[i]->display();
}

for (int i = 0; i < 2; ++i) {


delete shapes[i]; // Calls destructors for Circle and Rectangle
}

return 0;
}

 Encapsulation: The Circle and Rectangle classes encapsulate their specific data (radius,
width, height) and provide methods to access and manipulate this data.
 Inheritance: Both Circle and Rectangle inherit from Shape, showing how different shapes
can be treated through a common interface.
 Initialization and Finalization: Constructors initialize the shapes, and destructors are used to
clean up. The virtual destructor in Shape ensures proper destruction of derived class objects.
 Dynamic Binding: The area and display methods are pure virtual and overridden in derived
classes. The correct method implementations are called at runtime based on the actual object
type, demonstrating dynamic binding.

In Implementation 1, the destructors for both the base class (Account) and the derived class
(SavingsAccount) are called when the SavingsAccount object is deleted. This ensures that both
destructors are executed correctly due to the virtual destructor in the base class.

In Implementation 2, each derived class (Circle and Rectangle) has its destructor called,
followed by the base class destructor. This ensures proper cleanup, with each shape's specific
destructor being called first, followed by the base class destructor.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output 1:

Output 2:

Conclusion: These implementations cover fundamental concepts of C++ programming, showcasing


the power and flexibility of object-oriented design in managing and extending functionalities. These
outputs illustrate how constructors and destructors work in object-oriented programming, how
methods are overridden, and how dynamic binding is utilized to call the appropriate methods at
runtime.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 3
Aim: Tutorial Introduction to Haskell programming environment.

Theory: Haskell is a functional programming language, which means that functions are first-class
citizens. This means functions can be passed as arguments, returned from other functions, and assigned to
variables.

Setting Up the Haskell Environment

Installing Haskell

To start programming in Haskell, you’ll need to install the Haskell compiler and tools. The most common
way to do this is through the Haskell Platform or the Glasgow Haskell Compiler (GHC).

1. Haskell Platform:
o Windows/Mac/Linux: Download from Haskell Platform and follow the installation
instructions.
2. GHC (Glasgow Haskell Compiler):
o GHCup: For a more up-to-date installation, you can use GHCup to install GHC, Cabal,
and other tools.
 Visit GHCup for installation instructions.

Using GHCi

GHCi is the interactive environment for GHC. It allows you to run Haskell commands and test
code snippets quickly.

1. Start GHCi:
o Open your terminal or command prompt.
o Type ghci and press Enter.
o You should see a prompt like Prelude> indicating that GHCi is ready to accept commands.

Writing and Running Haskell Code

1. Write Code:
o Create a file with a .hs extension, for example, HelloWorld.hs.
2. Run Code:
o In GHCi, you can load your file using :load HelloWorld.hs or :l HelloWorld.hs.
o To run functions defined in the file, just type their names at the GHCi prompt.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


3. Basic Haskell Concepts

Hello World Program

Create a file named HelloWorld.hs with the following content:

To run this program:

1. Compile: ghc -o HelloWorld HelloWorld.hs


2. Run: ./HelloWorld (on Windows, just HelloWorld.exe)

Output

Define simple functions

 Create a file named Functions.hs: Open your preferred text editor and create a new file
named Functions.hs.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


 Add the following content to Functions.hs:

 Compile and run the program:


1. Open a terminal or command prompt.
2. Navigate to the directory containing Functions.hs.
3. Compile the Haskell file:

Run the executable:

Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Conclusion: We now set up the Haskell programming environment and learned the basics of
creating, building, and running Haskell projects. This process includes writing, compiling, and running
Haskell programs, which forms the basis for further exploration of the language. This should provide a
solid foundation to start exploring Haskell and its features further.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 4
Aim: Tutorial exercise on operators, types etc. in Haskell.

Theory: This tutorial will introduce us to operators, types, and basic concepts in Haskell. We'll cover
arithmetic and logical operators, type declarations, and type inference.

1. Arithmetic Operators:

2. Logical Operators

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


3. Comparison Operators:

4. Types and Type Inference:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


5. List Operations:

6. Tuples:

Conclusion: These concepts form the foundation of Haskell programming. Experimenting


with these examples will help us become more comfortable with the language.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 5
Aim: At least 5 Haskell Programs to demonstrate Functional Programming Concept.

Theory: Functional programming is a paradigm that treats computation as the evaluation of


mathematical functions and avoids changing state and mutable data. Here are five Haskell programs
that demonstrate core functional programming concepts:

1. Higher-Order Functions

Output:

2. Recursion

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output:

3. Map, Filter, and Fold

Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


4. Pure Functions

Output:

5. Lazy Evaluation

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output:

Conclusion: By studying and experimenting with these examples, we'll gain a deeper
understanding of functional programming in Haskell.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 6
Aim: Implement safetail with conditionals and guards, list comprehension, recursive multiplication
using addition, implementing Nim game with lists, generating infinite Fibonacci series, and a basic
calculator, all aimed at teaching Haskell's syntax and functional programming concepts effectively.

Theory: Haskell programs that demonstrate functional programming concepts such as


conditionals, guards, list comprehension, recursion, and infinite data structures.

1. Implementing safetail with Conditionals and Guards

Using Conditionals

Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Using Guards

Output:

2. List Comprehension

Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


3. Recursive Multiplication Using Addition

Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


4. Implementing Nim Game with Lists

Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


5. Generating Infinite Fibonacci Series

Output:

6. Basic Calculator

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output:

Conclusion: By studying and running these examples, we'll gain a deeper


understanding of Haskell's syntax and functional programming capabilities.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 7
Aim: Tutorial Installation and working of SWI Prolog Environment.

Theory: SWI-Prolog is a comprehensive and robust Prolog environment, widely used for
research, education, and development. This tutorial will guide you through the installation
process and introduce you to the basic working of SWI-Prolog.

Step 1: Installation

Windows

1. Download SWI-Prolog:
o Visit the SWI-Prolog download page.
o Click on the appropriate installer for your version of Windows (64-bit or 32-bit).
2. Run the Installer:
o Once the download is complete, run the installer.
o Follow the on-screen instructions to complete the installation.
3. Verify the Installation:
o Open the Command Prompt.
o Type swipl and press Enter.
o If the installation is successful, you will see the SWI-Prolog interactive shell.

Starting the Prolog Environment

To start the SWI-Prolog environment, open your terminal or command prompt and type swipl, then press
Enter.

Writing Your First Prolog Program

1. Create a File:
o Create a new file named hello.pl using a text editor.
o Add the following content to the file:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


2. Load and Run the Program:
o Open the terminal or command prompt.
o Navigate to the directory where hello.pl is located.
o Start SWI-Prolog by typing swipl.
o Load your program using the [filename] command:

o Run the main predicate by typing main.:

Basic Prolog Concepts

1. Facts and Rules:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Prolog programs consist of facts and rules. Here is an example:

o parent(john, mary). is a fact.


o grandparent(X, Y) :- parent(X, Z), parent(Z, Y). is a rule.
2. Queries:

We can ask Prolog questions (queries) based on the facts and rules:

Variables:

Variables in Prolog start with an uppercase letter. Here’s an example:

Conclusion: With these basics, we're ready to explore more complex Prolog programs
and harness the power of logic programming with SWI-Prolog.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 8
Aim: Implement at least 5 Prolog programs to understand declarative programming concepts.

Theory: Below are five Prolog programs that demonstrate declarative programming concepts such as
facts, rules, recursion, backtracking, and list processing.

1. Family Relationships
% family.pl parent(john, mary).
parent(mary, susan).
parent(paul, mary).
parent(jane, susan).
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
main :-
write('Parent relationships:'), nl,
forall(parent(X, Y), (write(X), write(' is parent of '), write(Y), nl)), nl,
write('Grandparent relationships:'), nl,
forall(grandparent(X, Y), (write(X), write(' is grandparent of '), write(Y), nl)),
halt.
Output:

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


2. Recursive Factorial

Output:

3. List Length

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output:

4. Fibonacci Series

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output:

5. Basic Arithmetic Operations

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Output:

Conclusion: By running these programs, we will gain a better understanding of Prolog's


syntax and the declarative programming paradigm.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 9

Aim: At least two Programs preferably in C++ and java to demonstrate Thread management and
synchronization.

Theory:

1. Thread Management and Synchronization in C++ and Java


// thread_management.cpp
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>

std::mutex mtx;
int counter = 0;

void increment(int id) {


for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}
std::cout << "Thread " << id << " finished\n";
}

int main() {
std::vector<std::thread> threads;

for (int i = 0; i < 10; ++i) {


threads.emplace_back(increment, i);
}

for (auto& th : threads) {


th.join();
}

std::cout << "Final counter value: " << counter << '\n';

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


return 0;
}
Output:

2. Thread Management and Synchronization with Thread and synchronized


// ThreadManagement.java
public class ThreadManagement {
private static int counter = 0;

public static void main(String[] args) {


Thread[] threads = new Thread[10];

for (int i = 0; i < 10; i++) {


threads[i] = new Thread(new Incrementer(i));
threads[i].start();
}

for (int i = 0; i < 10; i++) {


try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


System.out.println("Final counter value: " + counter);
}

static class Incrementer implements Runnable {


private int id;

Incrementer(int id) {
this.id = id;
}

@Override
public void run() {
for (int i = 0; i < 1000; i++) {
incrementCounter();
}
System.out.println("Thread " + id + " finished");
}

private synchronized void incrementCounter() {


counter++;
}
}
}
Output:

Conclusion: These programs demonstrate thread management and synchronization in C++


and Java. Both programs increment a shared counter with multiple threads and ensure that the
final counter value is consistent due to proper synchronization.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 10
Aim:A Program to understand Exception handling and Garbage collection, preferably in
C++ and JAVA.
Theory: In C++, exception handling is done using try, catch, and throw keywords.
#include &lt;iostream&gt;
#include &lt;stdexcept&gt; // For std::runtime_error

void mightGoWrong() {
bool errorOccurred = true; // Simulating an error
if (errorOccurred) {
throw std::runtime_error(&quot;Something went wrong!&quot;);
}
}

int main() {
try {
mightGoWrong();
} catch (const std::runtime_error&amp; e) {
std::cerr &lt;&lt; &quot;Caught an exception: &quot; &lt;&lt; e.what() &lt;&lt; std::endl;
}

return 0;
}
In this program:
mightGoWrong function simulates an error by throwing a std::runtime_error.
The try block calls mightGoWrong and if an exception is thrown, it&#39;s caught in
the catch block,
where an error message is printed.
Java
In Java, exception handling is quite similar, but it uses try, catch, finally, and throw
keywords.
public class Main {
public static void mightGoWrong() throws Exception {
boolean errorOccurred = true; // Simulating an error
if (errorOccurred) {
throw new Exception(&quot;Something went wrong!&quot;);

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


}
}

public static void main(String[] args) {


try {
mightGoWrong();
} catch (Exception e) {
System.err.println(&quot;Caught an exception: &quot; + e.getMessage());
} finally {
System.out.println(&quot;This block is executed regardless of an exception.&quot;);
}
}
}
In this program:
 mightGoWrong method simulates an error by throwing an Exception.
 The try block calls mightGoWrong, and if an exception is thrown, it&#39;s caught in the
catch block.
 The finally block is executed whether an exception is thrown or not.

Garbage Collection
C++
In C++, garbage collection is not built into the language, and memory management is
manual. You need to explicitly allocate and deallocate memory using new and delete.
#include &lt;iostream&gt;

class Example {
public:
Example() { std::cout &lt;&lt; &quot;Constructor called\n&quot;; }
~Example() { std::cout &lt;&lt; &quot;Destructor called\n&quot;; }
};

int main() {
Example* obj = new Example(); // Memory allocated
delete obj; // Memory deallocated

return 0;
}

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


In this program:
 new allocates memory for an Example object.
 delete deallocates that memory, calling the destructor and freeing the memory.

Java
Java has automatic garbage collection. You don&#39;t need to manually manage
memory, as Java&#39;s garbage
collector handles deallocation.
public class Main {
static class Example {
Example() {
System.out.println(&quot;Constructor called&quot;);
}

@Override
protected void finalize() throws Throwable {
try {
System.out.println(&quot;Destructor called&quot;);
} finally {
super.finalize();
}
}
}

public static void main(String[] args) {


Example obj = new Example(); // Memory allocated
obj = null; // The object is now eligible for garbage collection

System.gc(); // Suggests that the JVM perform garbage collection

// Sleep to give garbage collector time to run


try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


}
}
}
In this program:
 new allocates memory for an Example object, and Java handles deallocation
automatically.
 System.gc() is a suggestion to the JVM to run the garbage collector, but it is not
guaranteed to immediately deallocate the memory.

Conclusion: These experiments illustrate the basics of exception handling and garbage
collection in both languages.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Experiment No. 11

Aim: At Least two implementations each implemented on multiple paradigms like procedural, object
oriented, functional, logic.

Theory: Two tasks implemented in multiple paradigms—procedural, object-oriented, functional, and


logic. This will demonstrate the differences and strengths of each paradigm.

Task 1: Factorial Calculation

Procedural (C)

#include <stdio.h>

// Factorial function

int factorial(int n) {

int result = 1;

for (int i = 1; i <= n; i++) {

result *= i;

return result;

int main() {

int num = 5;

printf("Factorial of %d is %d\n", num, factorial(num));

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


return 0;

Object-Oriented (Java)

public class Factorial {

public int factorial(int n) {

int result = 1;

for (int i = 1; i <= n; i++) {

result *= i;

return result;

public static void main(String[] args) {

Factorial fact = new Factorial();

int num = 5;

System.out.println("Factorial of " + num + " is " + fact.factorial(num));

Functional (Haskell)

factorial :: Integer -> Integer

factorial 0 = 1

factorial n = n * factorial (n - 1)

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


main :: IO ()

main = do

let num = 5

putStrLn ("Factorial of " ++ show num ++ " is " ++ show (factorial num))

Logic (Prolog)

factorial(0, 1).

factorial(N, F) :-

N > 0,

N1 is N - 1,

factorial(N1, F1),

F is N * F1.

% Query: factorial(5, F).

Task 2: Fibonacci Sequence Generation

1. Procedural (C)
#include <stdio.h>

void fibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm;
for (int i = 1; i <= n; i++) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
}

int main() {
int num = 5;
fibonacci(num);

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


return 0;
}

2. Object-Oriented (Python)
class Fibonacci:
def generate(self, n):
t1, t2 = 0, 1
for _ in range(n):
print(t1, end=" ")
t1, t2 = t2, t1 + t2

if name == " main ":


fib = Fibonacci()
fib.generate(5)

3. Functional (Haskell)
haskell
Copy code
fibonacci :: Int -> [Int]
fibonacci n = take n $ map fst $ iterate (\(a,b) -> (b, a+b)) (0,1)

main :: IO ()
main = do
let num = 5
print (fibonacci num)

4. Logic (Prolog)
prolog
Copy code
fibonacci(0, 0).
fibonacci(1, 1).
fibonacci(N, F) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fibonacci(N1, F1),
fibonacci(N2, F2),
F is F1 + F2.

% Query: fibonacci(5, F).

Conclusion:
Procedural Paradigm: Focuses on step-by-step instructions. The task is broken down into
procedures or functions that change the state of the program.

Object-Oriented Paradigm: Encapsulates the task within objects, which manage their state and
behavior. Involves defining classes and methods to perform the task.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw


Functional Paradigm: Emphasizes the use of pure functions and recursion. The task is
represented as a composition of functions without side effects.
Logic Paradigm: Describes the task declaratively using logical relationships and rules. It uses
a backtracking algorithm to find the solution.

SE IT SEM 3 Programming Lab Faculty Name- Ms. Priyanka Shaw

You might also like