Lab Manual

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

Experiment No.

– 1

Study of Programming Paradigms


Imperative Programming:
.

public class SumOfNumbers {


public static void main(String[] args) {
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum of numbers from 1 to " + n + " is: " + sum);
}
}

OUTPUT :

Object-Oriented Programming (OOP):

class Circle {
double radius;

double calculateArea() {
return Math.PI * radius * radius;
}
}

public class CircleDemo {


public static void main(String[] args) {
Circle myCircle = new Circle();
myCircle.radius = 5.0;
double area = myCircle.calculateArea();
System.out.println("Area of the circle is: " + area);
}
}
OUTPUT :
Functional Programming:

import java.util.Arrays;
import java.util.List;

public class FunctionalDemo {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.stream()


.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();

System.out.println("Sum of even numbers: " + sum);


}
}

OUTPUT :

Procedural Programming:

public class Factorial {


static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


int n = 5;
int result = factorial(n);
System.out.println("Factorial of " + n + " is: " + result);
}
}

OUTPUT :
Experiment No. – 2

Implement Sum of series (1 + 2+ 3+…..n,1+1/2+1/3 +… 1/n,12 + 22+


32 + n2) using JAVA
Sum of Natural Numbers (1 + 2 + 3 + ... + n)

public class SumOfNaturalNumbers {


public static void main(String[] args) {
int n = 10; // Change this value to the desired 'n'
int sum = 0;

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


sum += i;
}

System.out.println("Sum of natural numbers from 1 to " + n + " is: " + sum);


}
}

OUTPUT:

Sum of Reciprocal of Natural Numbers (1 + 1/2 + 1/3 + ... + 1/n):

public class SumOfReciprocalNumbers {


public static void main(String[] args) {
int n = 10; // Change this value to the desired 'n'
double sum = 0.0;

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


sum += 1.0 / i;
}

System.out.println("Sum of reciprocal numbers from 1 to " + n + " is: " + sum);


}
}

OUTPUT:
Sum of Squares of Natural Numbers (12 + 22 + 32 + ... + n2):

public class SumOfSquares {


public static void main(String[] args) {
int n = 10; // Change this value to the desired 'n'
int sum = 0;

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


sum += i * i;
}
System.out.println("Sum of squares of natural numbers from 1 to " + n + " is: " + sum);
}
}

OUTPUT:
Experiment No. – 3

Simple JAVA Programs to implement functions


Calculate Factorial

public class Factorial {


public static void main(String[] args) {
int n = 5; // Change this value to the desired number
long factorial = 1;

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


factorial *= i;
}

System.out.println("Factorial of " + n + " is: " + factorial);


}
}

OUTPUT:

Find Prime Numbers

public class PrimeNumbers {


public static void main(String[] args) {
int limit = 50; // Change this value to the desired limit

for (int num = 2; num <= limit; num++) {


boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
}
}
OUTPUT :
Calculate Fibonacci Sequence

public class Fibonacci {


public static void main(String[] args) {
int n = 10; // Change this value to the desired number of terms
int a = 0, b = 1;

System.out.print("Fibonacci Sequence: ");


for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
}
}
}
OUTPUT:

Calculate Power (Exponentiation)

public class Power {


public static void main(String[] args) {
double base = 2.0; // Change this value to the base
int exponent = 3; // Change this value to the exponent
double result = 1.0;

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


result *= base;
}

System.out.println(base + " raised to the power of " + exponent + " is: " + result);
}
}

OUTPUT:
Experiment No. – 4

Simple JAVA Programs with Class and Objects

Create a Class and Object:

class Person {
String name;
int age;

void introduce() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class PersonDemo {
public static void main(String[] args) {
// Create two Person objects
Person person1 = new Person();
person1.name = "Alice";
person1.age = 30;

Person person2 = new Person();


person2.name = "Bob";
person2.age = 25;

// Call the introduce method for each person


System.out.println("Person 1:");
person1.introduce();

System.out.println("\nPerson 2:");
person2.introduce();
}
}
OUTPUT:
Bank Account Class:
class BankAccount {
String accountNumber;
String accountHolder;
double balance;
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient funds!");
}
}
void displayBalance() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: $" + balance);
}
}
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account1 = new BankAccount();
account1.accountNumber = "12345";
account1.accountHolder = "Alice";
account1.balance = 1000.0;
account1.displayBalance();
account1.deposit(500.0);
account1.displayBalance();
account1.withdraw(200.0);
account1.displayBalance();
}
}
OUTPUT:
Experiment No. – 5

Implement JAVA program - Simple Calculator using polymorphism


class Calculator {
public int calculate(int num1, int num2) {
return num1 + num2;
}

public double calculate(double num1, double num2) {


return num1 + num2;
}

public int calculateSubtraction(int num1, int num2) {


return num1 - num2;
}

public double calculateSubtraction(double num1, double num2) {


return num1 - num2;
}

public int calculateMultiplication(int num1, int num2) {


return num1 * num2;
}

public double calculateMultiplication(double num1, double num2) {


return num1 * num2;
}

public int calculateDivision(int num1, int num2) {


if (num2 != 0) {
return num1 / num2;
} else {
System.out.println("Division by zero is not allowed.");
return 0;
}
}

public double calculateDivision(double num1, double num2) {


if (num2 != 0.0) {
return num1 / num2;
} else {
System.out.println("Division by zero is not allowed.");
return 0.0;
}
}
}

public class CalculatorDemo {


public static void main(String[] args) {
Calculator calculator = new Calculator();

// Integer addition
System.out.println("Integer Addition: " + calculator.calculate(5, 3));

// Double addition
System.out.println("Double Addition: " + calculator.calculate(5.5, 3.3));

// Integer subtraction
System.out.println("Integer Subtraction: " + calculator.calculateSubtraction(10, 4));

// Double subtraction
System.out.println("Double Subtraction: " + calculator.calculateSubtraction(10.5, 4.2));

// Integer multiplication
System.out.println("Integer Multiplication: " + calculator.calculateMultiplication(6, 7));

// Double multiplication
System.out.println("Double Multiplication: " + calculator.calculateMultiplication(6.6, 7.7));

// Integer division
System.out.println("Integer Division: " + calculator.calculateDivision(20, 4));

// Double division
System.out.println("Double Division: " + calculator.calculateDivision(20.0, 0.0));
}
}
OUTPUT:
Experiment No. – 6

Implement JAVA program - Pay Slip Generator using Inheritance


// Base class Employee
class Employee {
private String name;
private String employeeId;

public Employee(String name, String employeeId) {


this.name = name;
this.employeeId = employeeId;
}

public String getName() {


return name;
}

public String getEmployeeId() {


return employeeId;
}

// This method will be overridden by derived classes


public double calculatePay() {
return 0.0;
}
}

// Derived class SalariedEmployee


class SalariedEmployee extends Employee {
private double monthlySalary;

public SalariedEmployee(String name, String employeeId, double monthlySalary) {


super(name, employeeId);
this.monthlySalary = monthlySalary;
}

@Override
public double calculatePay() {
return monthlySalary;
}
}

// Derived class HourlyEmployee


class HourlyEmployee extends Employee {
private double hourlyRate;
private int hoursWorked;

public HourlyEmployee(String name, String employeeId, double hourlyRate, int hoursWorked) {


super(name, employeeId);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}

@Override
public double calculatePay() {
return hourlyRate * hoursWorked;
}
}

public class PaySlipGenerator {


public static void main(String[] args) {
// Create SalariedEmployee and HourlyEmployee objects
SalariedEmployee salariedEmployee = new SalariedEmployee("Alice", "E001", 5000.0);
HourlyEmployee hourlyEmployee = new HourlyEmployee("Bob", "E002", 15.0, 40);

// Generate pay slips


generatePaySlip(salariedEmployee);
generatePaySlip(hourlyEmployee);
}

// Method to generate pay slip


public static void generatePaySlip(Employee employee) {
System.out.println("Pay Slip for Employee: " + employee.getName());
System.out.println("Employee ID: " + employee.getEmployeeId());
System.out.println("Monthly Salary: $" + employee.calculatePay());
System.out.println("--------------------------");
}
}

OUTPUT:
Experiment No. – 7

Simple JAVA Programs to implement thread


Using the Thread Class:

class MyThread extends Thread {


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + ": Count " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

thread1.start();
thread2.start();
}
}

OUTPUT:
Using the Runnable Interface:

class MyRunnable implements Runnable {


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + ": Count " + i);
}
}
}

public class RunnableExample {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable);
Thread thread2 = new Thread(myRunnable);

thread1.start();
thread2.start();
}
}

OUTPUT:
Experiment No. – 8

Simple JAVA Programs with Java Data Base Connectivity (JDBC)


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCSample {


public static void main(String[] args) {
Connection connection = null;

try {
// Connect to the database (SQLite in this case)
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Connected to the database.");

// Create a table
Statement statement = connection.createStatement();
String createTableSQL = "CREATE TABLE IF NOT EXISTS employees " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INT)";
statement.executeUpdate(createTableSQL);
System.out.println("Table 'employees' created (if it didn't exist).");

// Insert data
String insertDataSQL = "INSERT INTO employees (name, age) VALUES ('Alice', 30),
('Bob', 25), ('Charlie', 35)";
statement.executeUpdate(insertDataSQL);
System.out.println("Data inserted into the table.");

// Query data
String querySQL = "SELECT * FROM employees";
ResultSet resultSet = statement.executeQuery(querySQL);

// Display query results


System.out.println("\nEmployee Data:");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
System.out.println("\nDisconnected from the database.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

OUTPUT:
Experiment No. – 9

Form Design with applet and Swing using JAVA

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleFormApplet extends JApplet implements ActionListener {


private JTextField nameField;
private JTextField emailField;
private JButton submitButton;

@Override
public void init() {
// Set up the layout manager
setLayout(new GridLayout(3, 2));

// Create and add components to the form


JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(20);
JLabel emailLabel = new JLabel("Email:");
emailField = new JTextField(20);

submitButton = new JButton("Submit");


submitButton.addActionListener(this);

add(nameLabel);
add(nameField);
add(emailLabel);
add(emailField);
add(new JLabel()); // Empty cell for spacing
add(submitButton);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submitButton) {
// Handle the submit button click
String name = nameField.getText();
String email = emailField.getText();

// Display a message dialog with the entered data


JOptionPane.showMessageDialog(this,
"Name: " + name + "\nEmail: " + email,
"Form Submission",
JOptionPane.INFORMATION_MESSAGE);

// Clear the input fields


nameField.setText("");
emailField.setText("");
}
}
}

To run this applet, you can create an HTML file (e.g., SimpleFormApplet.html) with the
following content:
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Applet</title>
</head>
<body>
<applet code="SimpleFormApplet.class" width="300" height="120"></applet>
</body>
</html>

OUTPUT:
Experiment No. – 10

Simple Python Program to implement functions


Calculate Factorial:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

num = 5 # Change this value to the desired number


result = factorial(num)
print(f"Factorial of {num} is: {result}")

OUTPUT:

Find Prime Numbers:

def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

limit = 50 # Change this value to the desired limit


prime_numbers = [num for num in range(2, limit + 1) if is_prime(num)]
print("Prime numbers up to", limit, "are:", prime_numbers)

OUTPUT:
Calculate Fibonacci Sequence:

def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence

num_terms = 10 # Change this value to the desired number of terms


fibonacci_sequence = fibonacci(num_terms)
print("Fibonacci Sequence:", fibonacci_sequence)

OUTPUT:

Calculate Power (Exponentiation):

def power(base, exponent):


result = 1
for _ in range(exponent):
result *= base
return result

base = 2.0 # Change this value to the base


exponent = 3 # Change this value to the exponent
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
Python program using control structures and arrays

OUTPUT:
Experiment No. – 11

Python program using control structures and arrays


# Create an array (list) of numbers
numbers = [12, 45, 78, 23, 56, 89, 9, 67, 32, 5]

# Initialize variables to store the maximum and minimum values


max_value = numbers[0]
min_value = numbers[0]

# Use a for loop to iterate through the array and find max and min values
for num in numbers:
if num > max_value:
max_value = num
if num < min_value:
min_value = num

# Print the maximum and minimum values


print("Maximum value in the array:", max_value)
print("Minimum value in the array:", min_value)

OUTPUT:
Experiment No. – 12

Implement Python program - TCP/UDP program using Sockets


TCP Server:

import socket
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Get the local machine's hostname and specify a port


host = socket.gethostname()
port = 12345

# Bind the socket to the address


server_socket.bind((host, port))

# Listen for incoming connections


server_socket.listen(5)

print("TCP Server listening on {}:{}".format(host, port))

while True:
# Establish a connection with the client
client_socket, addr = server_socket.accept()
print("Connected to {}:{}".format(addr[0], addr[1]))

# Send data to the client


message = "Hello, client! This is the TCP server."
client_socket.send(message.encode('utf-8'))

# Receive data from the client


data = client_socket.recv(1024)
print("Received from client: {}".format(data.decode('utf-8')))

# Close the client socket


client_socket.close()

OUTPUT:
TCP Client:

import socket
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Get the server hostname and port


host = socket.gethostname()
port = 12345

# Connect to the server


client_socket.connect((host, port))

# Receive data from the server


data = client_socket.recv(1024)
print("Received from server: {}".format(data.decode('utf-8')))

# Send data to the server


message = "Hello, server! This is the TCP client."
client_socket.send(message.encode('utf-8'))

# Close the client socket


client_socket.close()

To run the TCP server and client, you can run them in separate terminal windows or on different
machines.

OUTPUT:
UDP Server:

import socket
# Create a UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Get the local machine's hostname and specify a port


host = socket.gethostname()
port = 12345

# Bind the socket to the address


server_socket.bind((host, port))

print("UDP Server listening on {}:{}".format(host, port))

while True:
# Receive data from the client
data, addr = server_socket.recvfrom(1024)
print("Received from client {}:{}".format(addr[0], addr[1]))
print("Data: {}".format(data.decode('utf-8')))

# Send data back to the client


response = "Hello, client! This is the UDP server."
server_socket.sendto(response.encode('utf-8'), addr)

OUTPUT:
UDP Client:

import socket

# Create a UDP socket


client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Get the server hostname and port


host = socket.gethostname()
port = 12345

# Send data to the server


message = "Hello, server! This is the UDP client."
client_socket.sendto(message.encode('utf-8'), (host, port))

# Receive data from the server


data, addr = client_socket.recvfrom(1024)
print("Received from server {}:{}".format(addr[0], addr[1]))
print("Data: {}".format(data.decode('utf-8')))

# Close the client socket


client_socket.close()

OUTPUT:
Experiment No. – 13

Construct NFA and DFA using Python

# Define the NFA transitions as a dictionary


nfa = {
'q0': {'0': ['q0'], '1': ['q0', 'q1']},
'q1': {'0': ['q2']},
'q2': {}
}

def nfa_accepts(input_string, current_state, nfa):


if not input_string:
return current_state in accepting_states

current_char, remaining_input = input_string[0], input_string[1:]


next_states = nfa.get(current_state, {}).get(current_char, [])

for next_state in next_states:


if nfa_accepts(remaining_input, next_state, nfa):
return True

return False

# Test the NFA


accepting_states = ['q2']
input_string = "0110"
result = nfa_accepts(input_string, 'q0', nfa)
print(f"NFA Result: Input '{input_string}' {'accepted' if result else 'rejected'}")
def powerset(s):
return list(chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)))

def nfa_to_dfa(nfa):
alphabet = set(chain.from_iterable(nfa[state].keys() for state in nfa))
dfa = {}
states_to_explore = [frozenset(['q0'])]

while states_to_explore:
current_state_set = states_to_explore.pop()
dfa[current_state_set] = {}

for char in alphabet:


next_state_set = set()
for nfa_state in current_state_set:
next_state_set.update(nfa.get(nfa_state, {}).get(char, []))

dfa[current_state_set][char] = frozenset(next_state_set)

if frozenset(next_state_set) not in dfa:


states_to_explore.append(frozenset(next_state_set))

return dfa

# Convert NFA to DFA

dfa = nfa_to_dfa(nfa)

# Define accepting states for the DFA


accepting_states_dfa = {k for k, v in dfa.items() if any(state in accepting_states for state in k)}

# Test the DFA


input_string_dfa = "0110"
current_state_dfa = frozenset(['q0'])
for char in input_string_dfa:
current_state_dfa = dfa[current_state_dfa][char]

dfa_result = current_state_dfa in accepting_states_dfa


print(f"DFA Result: Input '{input_string_dfa}' {'accepted' if dfa_result else 'rejected'}")

OUTPUT:
Experiment No. – 14

Implement a Python program for the algebraic manipulations using


symbolic paradigm

# Define symbolic variables


x, y = sp.symbols('x y')
# Define algebraic expressions
expression1 = x**2 + 2*x + 1
expression2 = x**3 - y**3
# Expand an expression
expanded_expression = sp.expand(expression1)
print("Expanded Expression:", expanded_expression)
# Factorize an expression
factored_expression = sp.factor(expression2)
print("Factored Expression:", factored_expression)
# Simplify an expression
expression3 = (x**2 - 1)/(x - 1)
simplified_expression = sp.simplify(expression3)
print("Simplified Expression:", simplified_expression)
# Solve equations
equation = sp.Eq(x**2 - 4, 0)
solutions = sp.solve(equation, x)
print("Solutions to x^2 - 4 = 0:", solutions)
# Differentiate an expression
derivative = sp.diff(x**3, x)
print("Derivative of x^3:", derivative)
# Integrate an expression
integral = sp.integrate(x**2, x)
print("Integral of x^2:", integral)

OUTPUT:
Experiment No. – 15

Simple Python programs to implement event handling

# Define a function to handle the button click event


def button_click():
label.config(text="Button Clicked!")

# Create the main window


root = tk.Tk()
root.title("Event Handling Example")

# Create a label widget


label = tk.Label(root, text="Click the button")

# Create a button widget and attach the button_click function to its command
button = tk.Button(root, text="Click Me", command=button_click)

# Pack the label and button widgets


label.pack()
button.pack()

# Start the main event loop


root.mainloop()

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy