0% found this document useful (0 votes)
21 views24 pages

PCPF - PRACTICAL - Manual - Output 2

It is use full in partial exam

Uploaded by

donnoorain69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views24 pages

PCPF - PRACTICAL - Manual - Output 2

It is use full in partial exam

Uploaded by

donnoorain69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

PCPF Manual

Experiment __
Code:

/*
1)
programm in C++ to demonstrate concepts like - Encapsulation, Inheritance, Initialization and
Finalization, Dynamic Binding.

*/

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

// Encapsulation: Private data members with public getter and setter methods
class Person {
private:
string name;
int age;

public:
// Constructor: Initialization
Person(string n, int a) : name(n), age(a) {
cout << "Person constructor called for " << name << endl;
}

// Destructor: Finalization
virtual ~Person() {
cout << "Person destructor called for " << name << endl;
}

// Getter for name (encapsulation)


string getName() const {
return name;
}

// Getter for age (encapsulation)


int getAge() const {
return age;
}

// Virtual function for Dynamic Binding


virtual void displayInfo() const {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Inheritance: Student inherits from Person


class Student : public Person {
private:
string major;

public:
// Constructor: Initialization
Student(string n, int a, string m) : Person(n, a), major(m) {
cout << "Student constructor called for " << getName() << endl;
}

// Destructor: Finalization
~Student() {
cout << "Student destructor called for " << getName() << endl;
}

// Overriding the virtual function (Dynamic Binding)


void displayInfo() const override {
cout << "Name: " << getName() << ", Age: " << getAge()
<< ", Major: " << major << endl;
}
};

int main() {
// Using a base class pointer for dynamic binding
Person* p = new Student("Alice", 20, "Computer Science");

// Dynamic binding ensures that the correct displayInfo is called


p->displayInfo();

// Destructor is called when deleting the object


delete p;

return 0;
}

Output:

Person constructor called for Alice


Student constructor called for Alice
Name: Alice, Age: 20, Major: Computer Science
Student destructor called for Alice
Person destructor called for Alice
Experiment __
Code:

/*
5)
A c++ Program to understand Exception handling and Garbage collection
*/

#include <iostream>
#include <memory>
#include <exception>

// Custom exception class


class CustomException : public std::exception {
public:
const char* what() const noexcept override {
return "A custom exception occurred!";
}
};

// A simple class to demonstrate resource management


class Resource {
public:
// Constructor
Resource() {
std::cout << "Resource acquired." << std::endl;
}

// Destructor
~Resource() {
std::cout << "Resource released." << std::endl;
}

// Method that may throw an exception


void useResource(bool causeError) {
std::cout << "Using resource..." << std::endl;
if (causeError) {
throw CustomException();
}
}
};
void handleResource(bool causeError) {
// Using smart pointer for automatic memory management
std::unique_ptr<Resource> resource = std::make_unique<Resource>();

// Try to use the resource


resource->useResource(causeError);
// Resource will be automatically released when it goes out of scope
}

int main() {
try {
// Normal execution
handleResource(false);

// Exception scenario
handleResource(true);
} catch (const CustomException& e) {
std::cout << "Caught Exception: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cout << "Caught Standard Exception: " << e.what() << std::endl;
}

// Smart pointer automatically handles resource cleanup


std::cout << "End of program." << std::endl;

return 0;
}

Output:

Caught Exception: Division by zero exception.


Experiment __
Code:

/*
2)
Program in c++ to demonstrate Thread management and synchronization

if facing issue in debugging then, you can add the -pthread flag to the compilation command. Here's
how to compile the program:

g++ -pthread -o your_program your_program.cpp

*/

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>

using namespace std;

// Shared resource (critical section)


int counter = 0;

// Mutex to protect the shared resource


mutex mtx;

// Function that will be run by multiple threads


void incrementCounter(int threadID) {
for (int i = 0; i < 10000; ++i) {
// Locking the critical section to ensure synchronized access
mtx.lock();
++counter;
mtx.unlock();
}
cout << "Thread " << threadID << " finished execution." << endl;
}

int main() {
// Vector to hold thread objects
vector<thread> threads;
// Launch 5 threads
for (int i = 0; i < 5; ++i) {
threads.push_back(thread(incrementCounter, i + 1));
}

// Join all threads to the main thread (wait for all threads to finish)
for (auto& th : threads) {
th.join();
}

// Display the final counter value


cout << "Final counter value: " << counter << endl;

return 0;
}

Output:

This code involves thread management, so the output would involve messages from multiple
threads completing tasks concurrently.
Experiment __
Code:

/*
4)
A java Program to understand Exception handling and Garbage collection
*/
class Resource implements AutoCloseable {
// Constructor
public Resource() {
System.out.println("Resource acquired.");
}

// Method to simulate resource usage


public void useResource() throws Exception {
System.out.println("Using resource...");
// Simulating an error condition
throw new Exception("An error occurred while using the resource!");
}

// Implement the close() method for explicit cleanup


@Override
public void close() {
System.out.println("Resource cleaned up (AutoCloseable).");
}
}

public class ExceptionHandlingDemo {


public static void main(String[] args) {
// Try-with-resources ensures that the resource is automatically closed
try (Resource resource = new Resource()) {
// Attempt to use the resource
resource.useResource();
} catch (Exception e) {
// Handling the exception
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Finally block: Cleanup tasks if needed.");
}

// No need to call System.gc() explicitly since cleanup is done by AutoCloseable


System.out.println("End of program.");
}
}

Output:

Using resource: MyResource


Caught Exception: Simulated Exception
Finally block: Cleanup tasks if needed.
End of program.
Experiment __
Code:

/*
3)
Program in java to demonstrate Thread management and synchronization
*/

class Counter {
private int count = 0;

// Synchronized method to increment the counter


public synchronized void increment() {
count++;
}

// Getter for count


public int getCount() {
return count;
}
}

class Worker extends Thread {


private Counter counter;
private int threadId;

// Constructor to initialize the thread with the shared counter


public Worker(Counter counter, int id) {
this.counter = counter;
this.threadId = id;
}

// The run method contains the code that the thread will execute
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
System.out.println("Thread " + threadId + " finished execution.");
}
}
public class ThreadSynchronizationDemo {
public static void main(String[] args) throws InterruptedException {
// Shared resource (counter object)
Counter counter = new Counter();

// Creating and starting 5 worker threads


Worker[] workers = new Worker[5];
for (int i = 0; i < 5; i++) {
workers[i] = new Worker(counter, i + 1);
workers[i].start();
}

// Waiting for all threads to finish execution


for (Worker worker : workers) {
worker.join();
}

// Display the final counter value


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

Output:

Thread 1 finished execution.


Thread 2 finished execution.
Thread 3 finished execution.
Thread 4 finished execution.
Thread 5 finished execution.
Final counter value: 50000
Experiment __
1) Haskell Programming
Here is a simple example in Haskell to demonstrate key features of functional programming like
pure functions, immutability, recursion, and pattern matching. Following program that
calculates the factorial of a number using these principles.

Can use online link to Execute the program

https://www.onlinegdb.com/online_haskell_compiler

-- Factorial function using recursion and pattern matching

factorial :: Integer -> Integer

factorial 0 = 1 -- Base case: factorial of 0 is 1

factorial n = n * factorial (n - 1) -- Recursive case

-- Main function to run the program

main :: IO ()

main = do

-- Input from the user

putStrLn "Enter a number to calculate its factorial:"

input <- getLine

-- Convert input to an Integer

let number = read input :: Integer

-- Compute factorial and display the result

putStrLn ("The factorial of " ++ show number ++ " is " ++ show (factorial number))

Key Concepts Demonstrated:

1. Recursion:
o The factorial function calls itself recursively to calculate the factorial of a given
number n.
o The base case is defined for n = 0, where factorial 0 = 1, and the recursive case
is defined as n * factorial (n - 1).
2. Pattern Matching:
o Haskell uses pattern matching to define different behaviors for different inputs.
Here, factorial 0 is a pattern that matches the base case, and factorial n matches
any other number n.
3. Immutability:
o Haskell variables, like number, are immutable. Once assigned, their values
cannot be changed.
4. Pure Functions:
o The factorial function is a pure function, meaning its output depends only on its
input, and it has no side effects.
5. I/O Operations:
o The main function uses putStrLn to display messages and getLine to read user
input. The input is processed by reading and converting it to an integer, and the
result is displayed using string concatenation.
How to Run the Program:

 Save the code in a file called Factorial.hs.


 Compile it using ghc (Glasgow Haskell Compiler):
bash

ghc -o factorial Factorial.hs

 Run the compiled program:


bash

./factorial

Example Input and Output:

Enter a number to calculate its factorial:

The factorial of 5 is 120

Explanation:
 The program prompts the user to input a number.
 The factorial function computes the factorial of that number using recursion.
 The result is printed to the console.
Conclusion:

This Haskell example introduces important functional programming concepts like recursion,
pattern matching, immutability, and pure functions, while also showing basic I/O operations.
Experiment __
2) Haskell Programming

In Haskell Implement safetail function that behaves in the same way as tail, except that safetail
maps the empty list to the empty list, whereas tail gives an error in this case. Define safetail
using: (a) a conditional expression; (b) guarded equations; (c) pattern matching. Hint: the library
function null :: [a]-> Bool can be used to test if a list is empty.

Can use online link to Execute the program

https://www.onlinegdb.com/online_haskell_compiler

-- safetail using a conditional expression

safetail_cond :: [a] -> [a]

safetail_cond xs = if null xs then [] else tail xs

-- safetail using guarded equations

safetail_guarded :: [a] -> [a]

safetail_guarded xs

| null xs = []

| otherwise = tail xs

-- safetail using pattern matching

safetail_pattern :: [a] -> [a]

safetail_pattern [] = []

safetail_pattern (_:xs) = xs

-- Main function to run tests


main :: IO ()

main = do

-- Testing safetail_cond with Integer type

print (safetail_cond [1 :: Integer, 2, 3]) -- [2, 3]

print (safetail_cond ([] :: [Integer])) -- []

-- Testing safetail_guarded with Integer type

print (safetail_guarded [1 :: Integer, 2, 3]) -- [2, 3]

print (safetail_guarded ([] :: [Integer])) -- []

-- Testing safetail_pattern with Integer type

print (safetail_pattern [1 :: Integer, 2, 3]) -- [2, 3]

print (safetail_pattern ([] :: [Integer])) -- []

Key Changes:

1. Type Annotations:
o I added type annotations like 1 :: Integer to specify that the lists are of type
Integer. This allows the compiler to infer the types correctly.
o For the empty list, ([] :: [Integer]) explicitly defines the type of the empty list.

How to Compile and Run:

1. Save this updated program as main.hs.


2. Compile it using GHC:
bash

ghc -o main main.hs

3. Run the compiled program:


bash

./main
Expected Output:

[2,3]

[]

[2,3]

[]

[2,3]

[]
Experiment __
3) Haskell Programming
Here’s the complete Haskell program that defines both the addition and multiplication functions:

Can use online link to Execute the program

https://www.onlinegdb.com/online_haskell_compiler

-- Addition function for natural numbers

add :: Integer -> Integer -> Integer

add 0 b = b

add a b = 1 + add (a - 1) b

-- Multiplication function using the predefined add function

multiply :: Integer -> Integer -> Integer

multiply 0 _ = 0 -- Base case: anything multiplied by 0 is 0

multiply a b = add a (multiply a (b - 1)) -- Recursive case

-- Main function to test the multiplication

main :: IO ()

main = do

let a = 5

let b = 3

print (multiply a b) -- Output: 15

print (multiply 0 b) -- Output: 0

print (multiply a 0) -- Output: 0

print (multiply 4 6) -- Output: 24


Explanation:

 Addition Function:
o add 0 b = b: If the first number is 0, return the second number (identity of
addition).
o add a b = 1 + add (a - 1) b: Otherwise, add 1 to the result of adding a - 1 to b.

 Multiplication Function:
o multiply 0 _ = 0: If the first number is 0, return 0 (anything multiplied by 0 is 0).

o multiply a b = add a (multiply a (b - 1)): Otherwise, add a to the result of


multiplying a by b - 1.
Running the Program

You can save the code in a file named Main.hs and then compile and run it using GHC:

bash

ghc -o main Main.hs

./main

Expected Output

15

24

This program effectively uses recursion to perform multiplication through repeated addition.
Experiment __

Prolog programming

Prolog is a logic programming language that is particularly well-suited for tasks that involve
reasoning and knowledge representation. Its declarative nature allows programmers to express
the logic of a computation without explicitly describing its control flow. Here are some simple
Prolog programs that illustrate various declarative programming concepts:

1. Basic Facts and Rules

This example defines simple facts and rules about family relationships.

% Facts

parent(john, mary). % John is a parent of Mary

parent(john, sam). % John is a parent of Sam

parent(susan, mary). % Susan is a parent of Mary

parent(susan, sam). % Susan is a parent of Sam

% Rules

mother(X, Y) :- parent(X, Y), female(X).

father(X, Y) :- parent(X, Y), male(X).

% Additional facts for gender

female(mary).

female(susan).

male(john).

male(sam).

Concepts Illustrated:
 Facts: These are the basic assertions about the world.
 Rules: These define relationships based on existing facts.
 Queries: You can ask questions like mother(susan, mary). to check if Susan is Mary’s
mother.

2. Lists and Recursion

This example shows how to manipulate lists in Prolog.

% Base case: an empty list has a length of 0

length([], 0).

% Recursive case: the length of a non-empty list

length([_|Tail], Length) :-

length(Tail, TailLength),

Length is TailLength + 1.

% Example query: length([a, b, c], L).

Concepts Illustrated:

 Recursion: The function calls itself to process the tail of the list.
 Base Case: Important for terminating the recursion.
 List Handling: Prolog's native support for lists.

3. Backtracking
This example demonstrates Prolog’s ability to search through possible solutions.

% Define some basic facts

likes(mary, ice_cream).

likes(mary, chocolate).

likes(sam, pizza).

likes(sam, ice_cream).

% Find out who likes what

likes(X, Y) :- likes(X, Y).

% Example query: likes(mary, X).

Concepts Illustrated:

 Backtracking: Prolog automatically searches for all possible values of Y that satisfy the
likes predicate for mary.
 Logical Variables: Variables like X can take on different values during the search
process.

4. Simple Search Algorithm

This example implements a depth-first search on a graph.

% Define a simple graph using facts

edge(a, b).

edge(b, c).

edge(a, d).

edge(d, e).

% Define a path finding rule


path(X, Y) :- edge(X, Y).

path(X, Y) :- edge(X, Z), path(Z, Y).

% Example query: path(a, c).

Concepts Illustrated:

 Graph Representation: Using edges to represent connections.


 Recursive Search: Exploring paths through recursion.
 Declarative Logic: Expressing the problem without specifying how to traverse the
graph.

5. Knowledge Representation

This example uses Prolog to represent and query knowledge about animals.

% Facts about animals

animal(dog).

animal(cat).

animal(bird).

% Facts about characteristics

mammal(dog).

mammal(cat).

bird(bird).

% Rules based on characteristics

is_mammal(X) :- mammal(X).

% Example query: is_mammal(dog).


Concepts Illustrated:

 Knowledge Representation: Defining concepts and their relationships.


 Querying Knowledge: Asking questions based on defined rules.
Running Prolog Code

To run these Prolog examples, you can use various environments such as SWI-Prolog, GNU
Prolog, or online Prolog interpreters. Simply enter the facts and rules, then run queries to see
how Prolog responds.

Running Prolog Code Online

https://www.onlinegdb.com/online_prolog_compiler

Conclusion

These examples demonstrate some core concepts of declarative programming in Prolog, such
as defining facts and rules, recursion, backtracking, and knowledge representation. You can
expand on these ideas to explore more complex logic programming tasks! If you have any
specific concepts you'd like to explore further, feel free to ask!

You might also like