Java and Python Programs
Name : Shanmuga Nathan Manavalan
[Link] : RA2311030050031
Subject code : 21CSC203P
Subject name : Advanced Programming Practice
Question 1:
Study of Programming Paradigms(Control Structures Using Java)
Solution:
public class ControlStructures {
public static void main(String[] args) {
int number = 10;
// if-else example
if (number % 2 == 0) {
[Link](number + " is even.");
} else {
[Link](number + " is odd.");
}
// for loop example
[Link]("For Loop:");
for (int i = 0; i < 5; i++) {
[Link](i);
}
// while loop example
[Link]("While Loop:");
int j = 0;
while (j < 5) {
[Link](j);
j++;
}
// switch example
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Other day");
break;
}
}
}
OUTPUT:
Question 2:
Comparative Analysis between programming Paradigms
1. Declarative Vs Imperative
2. Object Vs Procedural
3. Logic Vs Functional
Solution:
1. Declarative
import [Link];
public class DeclarativeExample {
public static void main(String[] args) {
int sum = [Link](new int[]{1, 2, 3, 4, 5}).sum();
[Link]("Sum: " + sum);
}
}
Declarative Output:
Imperative
public class ImperativeExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
[Link]("Sum: " + sum);
}
}
Imperative Output:
2. Object :
// Object-Oriented example
class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class ObjectOrientedExample {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = [Link](2, 3);
[Link]("Result: " + result);
}
}
Object Output:
Procedural :
// Procedural example
public class ProceduralExample {
public static void main(String[] args) {
int result = add(2, 3);
[Link]("Result: " + result);
}
public static int add(int a, int b) {
return a + b;
}
}
Procedure output:
3. Logic :
import [Link];
import [Link];
public class LogicExample {
public static void main(String[] args) {
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = new ArrayList<>();
for (int number : numbers) {
if (isEven(number)) { // Logic: Only select even numbers
[Link](number);
}
}
[Link]("Even Numbers (Logic-Based): " + evenNumbers);
}
// Rule definition for even numbers
public static boolean isEven(int number) {
return number % 2 == 0;
}
}
Logic output:
Functional:
import [Link];
import [Link];
public class FunctionalExample {
public static void main(String[] args) {
List<Integer> numbers = [Link](1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Functional approach with streams and lambda expression
List<Integer> evenNumbers = [Link]()
.filter(number -> number % 2 == 0) // Lambda expression
for even check
.collect([Link]());
[Link]("Even Numbers (Functional-Based): " +
evenNumbers);
}
}
Functional output:
Question 3:
Simple JAVA Programs to implement functions
Solution:
public class SimpleFunctions {
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
public static void main(String[] args) {
[Link]("Addition: " + add(5, 3));
[Link]("Subtraction: " + subtract(5, 3));
}
}
OUTPUT:
Question 4:
Simple JAVA Programs with Class and Objects
Solution:
class Student {
String name;
int age;
Student(String name, int age) {
[Link] = name;
[Link] = age;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Alice", 20);
[Link]();
}
}
OUTPUT:
Question 5:
Implement JA VA program using polymorphism
Solution:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Polymorphism
[Link](); // Calls Dog's sound method
}
}
OUTPUT:
Question 6:
Implement JAVA program using Inheritance
Solution:
class Person {
String name;
void showName() {
[Link]("Name: " + name);
}
}
class Employee extends Person {
int employeeId;
void showEmployeeId() {
[Link]("Employee ID: " + employeeId);
}
}
public class InheritanceExample {
public static void main(String[] args) {
Employee emp = new Employee();
[Link] = "Bob";
[Link] = 101;
[Link]();
[Link]();
}
}
OUTPUT:
Question 7:
Simple JAVA Programs to implement thread
Solution:
import [Link];
class Thread1 extends Thread {
public void run() {
[Link]("Thread1 is running");
}
}
class Thread2 extends Thread {
public void run() {
[Link]("Thread2 is running");
}
}
public class ThreadExample {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
[Link]();
[Link]();
}
}
OUTPUT:
Question 8:
Simple JAVA Programs with Java Data Base Connectivity (JDBC)
Solution:
import [Link];
import [Link];
import [Link];
public class JDBCExample {
public static void main(String[] args) {
try {
Connection con =
[Link]("jdbc:mysql://localhost:3306/mydatabase",
"user", "password");
Statement stmt = [Link]();
String sql = "CREATE TABLE Students (ID INT PRIMARY KEY, Name
VARCHAR(50))";
[Link](sql);
[Link]("Table created");
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
OUTPUT:
Question 9:
Form Design with applet and Swing using JAVA
Solution:
import [Link].*;
import [Link];
import [Link];
public class FormDesign {
public static void main(String[] args) {
JFrame frame = new JFrame("Form");
JLabel label = new JLabel("Name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");
[Link](label);
[Link](textField);
[Link](button);
[Link](new [Link]());
[Link](300, 200);
[Link](true);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = [Link]();
[Link]("Name: " + name);
}
});
}
}
OUTPUT:
Question 10:
Simple Python Program to implement functions
Solution:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b if b != 0 else "Cannot divide by zero"
# Test the functions
print("Addition:", add(5, 3))
print("Subtraction:", subtract(5, 3))
print("Multiplication:", multiply(5, 3))
print("Division:", divide(5, 3))
OUTPUT:
Question 11:
Python program using control structures and arrays
Solution:
numbers = [1, 2, 3, 4, 5]
even_numbers = []
odd_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print("Even Numbers:", even_numbers)
print("Odd Numbers:", odd_numbers)
OUTPUT:
Question 12:
Implement Python program - TCP/UDP program using Sockets
Solution:
TCP server:
import socket
def tcp_server():
server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("[Link]", 2224)) # Use server's local
IP address
server_socket.listen(1)
print("TCP Server is listening on port 2224...")
conn, addr = server_socket.accept()
print(f"Connection from {addr}")
while True:
data = [Link](1024)
if not data:
break
print("Received from client:", [Link]())
[Link](b"Message received")
[Link]()
server_socket.close()
if __name__ == "__main__":
tcp_server()
OUTPUT:
TCP client:
import socket
def tcp_client():
client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("[Link]", 2224)) # Connect to
server's local IP
try:
message = "Hello, TCP Server!"
client_socket.sendall([Link]())
response = client_socket.recv(1024)
print("Received from server:", [Link]())
finally:
client_socket.close()
if __name__ == "__main__":
tcp_client()
OUTPUT:
UDP server:
import socket
def udp_server():
server_socket = [Link](socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("[Link]", 2224)) # Use server's local
IP address
print("UDP Server is listening on port 12345...")
while True:
data, addr = server_socket.recvfrom(1024)
print(f"Received from {addr}: {[Link]()}")
server_socket.sendto(b"Message received", addr)
if __name__ == "__main__":
udp_server()
OUTPUT:
UDP client:
import socket
def udp_client():
client_socket = [Link](socket.AF_INET, socket.SOCK_DGRAM)
server_address = ("[Link]", 2224) # Use server's local IP
address
message = "Hello, UDP Server!"
client_socket.sendto([Link](), server_address)
data, _ = client_socket.recvfrom(1024)
print("Received from server:", [Link]())
client_socket.close()
if __name__ == "__main__":
udp_client()
OUTPUT:
Question 13:
Construct NFA and DFA using Python
Solution:
Non-deterministic Finite Automaton(NFA)
def nfa_accepts(string):
current_states = {0} # Start with initial state 0
for char in string:
next_states = set()
for state in current_states:
if state == 0:
if char == '0':
next_states.update([0, 1]) # Stay in 0 or move to
1
elif char == '1':
next_states.add(0) # Stay in 0 on '1'
elif state == 1:
if char == '1':
next_states.add(2) # Move to accepting state 2
current_states = next_states
return 2 in current_states # Accept if any current state is 2
# Test the NFA
test_string = "1101"
print(f"NFA accepts '{test_string}':", nfa_accepts(test_string))
OUTPUT:
Deterministic Finite Automaton (DFA)
def dfa_accepts(string):
state = 0 # Start state
for char in string:
if state == 0:
state = 1 if char == '0' else 0
elif state == 1:
state = 2 if char == '1' else 1
elif state == 2:
state = 1 if char == '0' else 0
return state == 2 # Accept if in state 2
# Test the DFA
test_string = "1101"
print(f"DFA accepts '{test_string}':", dfa_accepts(test_string))
OUTPUT:
Question 14:
Implement a Python program for the algebraic manipulations using
symbolicparadigm
Solution:
from sympy import symbols, expand, factor
# Define symbolic variables
x, y = symbols('x y')
# Algebraic manipulation
expression = (x + y)**2
expanded_expr = expand(expression)
factored_expr = factor(expanded_expr)
print("Original Expression:", expression)
print("Expanded Expression:", expanded_expr)
print("Factored Expression:", factored_expr)
OUTPUT:
Question 15:
Simple Python programs to implement event handling
Solution:
import tkinter as tk
def on_button_click():
print("Button clicked!")
# Create the main window
window = [Link]()
[Link]("Event Handling Example")
# Create a button and bind the click event
button = [Link](window, text="Click Me", command=on_button_click)
[Link]()
# Run the event loop
[Link]()
OUTPUT: