Tuesday, October 31, 2023

R Programming Lab - Bsc CS DA and BSC ML And AI -Bharathiar University - Program 2- Manipulation of Vectors and matrix

 B.Sc Computer Science  

R Programming - Lab  

Bharathiar University 

Program 2

Manipulation of vectors and matrix 

Program 2 {a}- Write a R program to perform manipulation in vectors


SOURCE CODE:

# Manipulation of Vectors
# Create  two numeric vectors
v1 <- c(1, 2, 3, 4, 5)
v2 <- c(1, 1, 1, 1, 1)

# Print the original vector
print("Original Numeric Vectors:")
print(v1) 
print(v2)

print("Manipulation of Vectors")
print("Adding 1 to each element of the 1st vector")
m <- v1 + 1
print(m)

print("Adding 1st and 2 nd vectors")
print(v1+v2)

print("Subtract 2nd vector from 1st vector")
print(v1-v2)

print(" Multiplying two vectors")
print(v1*v2)


OUPUT


Program 2 {b}- Write a R program to perform manipulations in matrix 


SOURCE CODE:


# Manipulation of Matrix

# Create two matrices
m1 <- matrix(1:9, nrow = 3, ncol = 3)
m2 <- matrix(1:9, nrow = 3, ncol = 3)

# Print the original matrix
print("Original Matrices:")
print("Matrix 1:")
print(m1)
print("Matrix 2:")
print(m2)


print("Addition of two matrices")
print(m1+m2)

print("Subtraction of two matrices")
print(m1-m2)

print("Multiplication of two matrices")
print(m1*m2)

print("Division of two matrices")
print(m1/m2)


OUTPUT:

Monday, October 30, 2023

R Programming Lab - Bsc CS DA and BSC ML And AI -Bharathiar University - Program 1- R Expressions and Data structures

 

 B.Sc Computer Science  

R Programming - Lab  

Bharathiar University

R Expressions and Data Structures 

Program 1 {a}- Write a R program to perform some arithmetic expressions. 


SOURCE CODE:

# R Program for Expressions
# This program demonstrates basic arithmetic expressions in R.
  
# Define variables
a <- 10
b <- 5
 
# Calculate and print the results of different expressions
sum <- a + b
difference <- a - b
product <- a * b
quotient <- a / b

# Print the results
print(paste("Sum:",sum))
print(paste("Difference:", difference))
print(paste("Product:", product))
print(paste("Quotient:", quotient))


Sample  OUTPUT:

Monday, October 23, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 12- Write a python program for Linear Search and Binary Search.

 


 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 12 - Write a python program for Linear Search and Binary Search.


SOURCE CODE:

def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index of the target element if found
return -1 # Return -1 if the target element is not in the list


def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Return the index of the target element if found
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Return -1 if the target element is not in the list


# Main program
arr_input = input("Enter the elements of the array separated by space: ")
arr = list(map(int, arr_input.split()))

print("Entered Array:", arr)
search_method = input("Choose search method (linear/binary): ").lower()

try:
target = int(input("Enter the element to search: "))
except ValueError:
print("Invalid input! Please enter a valid number.")
target = None

if target is not None:
if search_method == 'linear':
result = linear_search(arr, target)
elif search_method == 'binary':
arr.sort() # Binary search requires a sorted array
result = binary_search(arr, target)
else:
print("Invalid search method. Please choose 'linear' or 'binary'.")
result = -1

if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")


OUTPUT:

Enter the elements of the array separated by space: 5 2 45 12 31 22
Entered Array: [5, 2, 45, 12, 31, 22]
Choose search method (linear/binary): linear
Enter the element to search: 12
Element 12 found at index 3.

Enter the elements of the array separated by space: 5 2 45 12 31 22
Entered Array: [5, 2, 45, 12, 31, 22]
Choose search method (linear/binary): binary
Enter the element to search: 31
Element 31 found at index 4.


Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 11- Write a python program to make a simple calculator.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 11 - Write a python program to make a simple calculator.


SOURCE CODE:


# Function to add two numbers
def add(x, y):
return x + y


# Function to subtract two numbers
def subtract(x, y):
return x - y


# Function to multiply two numbers
def multiply(x, y):
return x * y


# Function to divide two numbers
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y


# Main function to perform calculations based on user input
def calculator():
print("Simple Calculator")
print("Operations: +, -, *, /")

while True:
# Get user input for operation and numbers
operation = input("Enter operation (+, -, *, /) or 'exit' to quit: ")

if operation.lower() == 'exit':
break

try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter numbers.")
continue

# Perform calculation based on the chosen operation
if operation == '+':
print("Result:", add(num1, num2))
elif operation == '-':
print("Result:", subtract(num1, num2))
elif operation == '*':
print("Result:", multiply(num1, num2))
elif operation == '/':
print("Result:", divide(num1, num2))
else:
print("Invalid operation! Please enter +, -, *, or /.")


# Call the calculator function to run the calculator program
calculator()

OUTPUT:

Simple Calculator
Operations: +, -, *, /
Enter operation (+, -, *, /) or 'exit' to quit: +
Enter first number: 2
Enter second number: 5
Result: 7.0
Enter operation (+, -, *, /) or 'exit' to quit: -
Enter first number: 10
Enter second number: 2
Result: 8.0
Enter operation (+, -, *, /) or 'exit' to quit: *
Enter first number: 2
Enter second number: 3
Result: 6.0
Enter operation (+, -, *, /) or 'exit' to quit: /
Enter first number: 10
Enter second number: 5
Result: 2.0
Enter operation (+, -, *, /) or 'exit' to quit: =
Enter first number: 2
Enter second number: 3
Invalid operation! Please enter +, -, *, or /.
Enter operation (+, -, *, /) or 'exit' to quit: exit

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 10- Write a python program to sort a given sequence: String, List and Tuple.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 10-  Write a python program to sort a given sequence: String, List and Tuple. 

SOURCE CODE:
# Function to sort a sequence (string, list, or tuple)
def sort_sequence(seq):
if isinstance(seq, str):
# If input is a string, convert it to a list of characters
s = ''.join(sorted(seq))
elif isinstance(seq, (list, tuple)):
# If input is a list or tuple, sort it directly
s = sorted(seq)
else:
return "Invalid input. Please provide a string, list, or tuple."
return s

# read input from user
input_sequence = input("Enter a string, list, or tuple to sort: ")

sorted_sequence = sort_sequence(input_sequence)

print("Sorted sequence:", sorted_sequence)

OUTPUT:
SORTING STRING
Enter a string, list, or tuple to sort: hello
Sorted sequence: ehllo

SORTING LIST
Enter a string, list, or tuple to sort: [3,1,4,2,5]
Sorted sequence: [1,2,3,4,5]

SORTING TUPLE
Enter a string, list, or tuple to sort: (9,2,7,1,5)
Sorted sequence: (1,2,5,7,9)


Sunday, October 22, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 9 - Write a python program that writes a series of random numbers to a file from 1 to n and display

 

B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 9 - Write a python program that writes a series of random numbers to a file from 1 to n and display


SOURCE CODE:

# Function to generate and write random numbers to a file
import random


def write_random_numbers_to_file(f, n):
with open(filename, 'w') as f:
for _ in range(n):
random_number = random.randint(1, n)
f.write(str(random_number) + '\n')


# Function to read and display numbers from a file
def read_and_display_numbers(f):
with open(f, 'r') as file:
numbers = file.readlines()
print("Numbers from the file:")
for number in numbers:
print(number.strip())


# read file name and range for random numbers
filename = input("Enter file name: ")
n = int(input("Enter the range (n) for random numbers: "))

# Write random numbers to the file
write_random_numbers_to_file(filename, n)

# Read and display numbers from the file
read_and_display_numbers(filename)

OUTPUT:


Enter file name: C:\\Users\\Admin\\Desktop\\Sample.txt
Enter the range (n) for random numbers: 10
Random numbers to write in file
Random numbers read from file
Numbers from the file:
9
6
7
3
10
8
5
1
4
7
 Sample.txt file


Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 8 - Write recursive functions to display prime number from 2 to n.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 8 - Write recursive functions to display prime number from 2 to n.


SOURCE CODE:

def is_prime(num, divisor=2):
if num <= 2:
return num == 2
if num % divisor == 0:
return False
if divisor * divisor > num:
return True
return is_prime(num, divisor + 1)

def display_primes(n, current=2):
if current <= n:
if is_prime(current):
print(current, end=" ")
display_primes(n, current + 1)

# read n value from user
num = int(input("Enter a number (n) to display prime numbers from 2 to n: "))

# Check if the input is non-negative
if num < 2:
print("Prime numbers start from 2. Please enter a number greater than or equal to 2.")
else:
print("Prime numbers from 2 to", num, "are:")
display_primes(num)

OUTPUT

Enter a number (n) to display prime numbers from 2 to n: 10
Prime numbers from 2 to 10 are:
2 3 5 7 

Saturday, October 21, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 7 -Write recursive functions for Fibonacci Sequence up to given number n.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 7 -  Write recursive functions for Fibonacci Sequence up to given number n.


SOURCE CODE:

def fibonacci(n, a=0, b=1):
if n == 0:
return []
elif n == 1:
return [a]
else:
if a + b > n:
return [a]
else:
return [a] + fibonacci(n, b, a + b)

# read a number
num = int(input("Enter a number to generate Fibonacci sequence up to that number: "))

# Check if the input is non-negative
if num < 0:
print("Please enter a non-negative number.")
else:
fib_sequence = fibonacci(num)
print("Fibonacci sequence up to", num, "is:", fib_sequence)

OUTPUT:

Enter a number to generate Fibonacci sequence up to that number: 5
Fibonacci sequence up to 5 is: [0, 1, 1, 2, 3]

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 6 - Write recursive functions for the factorial of positive integer.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 6 - Write recursive functions for the factorial of positive integer.


SOURCE CODE:


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

# Read an integer
num = int(input("Enter a positive integer: "))

# Check if the input is a positive integer
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print("Factorial of", num, "is:", result)

OUTPUT:

Enter a positive integer: 5
Factorial of 5 is: 120

Friday, October 20, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 5 - Write recursive functions for GCD of two integers.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 5 - Write recursive functions for GCD of two integers.


SOURCE CODE

def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)

# Example usage
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

result = gcd(num1, num2)
print("GCD of", num1, "and", num2, "is:", result)

OUTPUT:
Enter the first integer: 12
Enter the second integer: 24
GCD of 12 and 24 is: 12

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 4 - Write a python program to find the product of two matrices [A]mxp and [B]pxr


Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 4 - Write a python program to find the product of two matrices [A]mxp and [B]pxr

Source Code

# Function to input a matrix from the user
def input_matrix(rows, cols):
matrix = []
print("Enter the matrix of size {",rows,"}x{",cols,"}:")
for i in range(rows):
r = list(map(int, input().split()))
if len(r) != cols:
print("Invalid input. Please enter exactly", cols, "numbers.")
return None
matrix.append(r)
return matrix

# Function to multiply two matrices
def multiply_matrices(A,B):
# Get dimensions of matrices A and B
m, p = len(A), len(A[0])
p, r = len(B), len(B[0])

# Check if matrices can be multiplied
if p != len(A[0]):
return "Matrices cannot be multiplied. Invalid dimensions."

# Initialize the result matrix with zeros
result = [[0 for _ in range(r)] for _ in range(m)]

# Perform matrix multiplication
for i in range(m):
for j in range(r):
for k in range(p):
result[i][j] += A[i][k] * B[k][j]

return result


# Get dimensions of matrices from the user
m = int(input("Enter the number of rows for matrix A: "))
p = int(input("Enter the number of columns for matrix A and rows for matrix B: "))
r = int(input("Enter the number of columns for matrix B: "))

# Input matrices from the user
matrix_A = input_matrix(m, p)
matrix_B = input_matrix(p, r)

# Check if input matrices are valid
if matrix_A and matrix_B:
# Calculate the product of matrices A and B
result_matrix = multiply_matrices(matrix_A, matrix_B)

# Display the result
if isinstance(result_matrix, str):
print(result_matrix) # If matrices cannot be multiplied
else:
print("Product of matrices A and B:")
for row in result_matrix:
print(row)


OUTPUT

Enter the number of rows for matrix A: 2
Enter the number of columns for matrix A and rows for matrix B: 2
Enter the number of columns for matrix B: 2
Enter the matrix of size { 2 }x{ 2 }:
1 2
1 2
Enter the matrix of size { 2 }x{ 2 }:
2 4
2 4
Product of matrices A and B:
[6, 12]
[6, 12]

Thursday, October 19, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 3 - Write a python program that asks user to enter series of positive numbers (the user should enter a negative number to signal the end of series) and the program should display numbers in order and their sum

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 3 - Write a python program that asks user to enter series of positive numbers   (the user should enter a negative number to signal the end of series) and the program should display numbers in order and their sum 

Source Code

# Initializing an empty list to store positive numbers
numbers = []

# Loop to take input from the user
while True:
num = int(input("Enter a positive number (or a negative number to end the series): "))
if num < 0:
break # Break the loop if a negative number is entered
numbers.append(num)

# Displaying the entered numbers
if len(numbers) > 0:
print("Entered numbers:", sorted(numbers))
# Calculating and displaying the sum of the entered numbers
print("Sum of the numbers:", sum(numbers))
else:
print("No positive numbers were entered.")

OUTPUT:
Enter a positive number (or a negative number to end the series): 5
Enter a positive number (or a negative number to end the series): 6
Enter a positive number (or a negative number to end the series): 3
Enter a positive number (or a negative number to end the series): 16
Enter a positive number (or a negative number to end the series): 10
Enter a positive number (or a negative number to end the series): -1
Entered numbers: [3, 5, 6, 10, 16]
Sum of the numbers: 40

Wednesday, October 18, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 2 - Write a python program to find the largest three integers using if-else and conditional operator.

 

 B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 2 - Write a python program to find the largest three integers using if-else and conditional operator.

Source Code

# Taking user input for three integers
a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))
c = int(input("Enter third integer: "))
# Find the largest among the three integers using if-else and conditional operators
largest = a if a > b and a > c else (b if b > c else c)


# Displaying the largest number
print("The largest number among", a, ",", b, "and", c, "is:", largest)


OUTPUT:
Enter first integer: 50
Enter second integer: 76
Enter third integer: 23
The largest number among 50 , 76 and 23 is: 76

Python Programming - Lab- Core Lab 5 - bharathiar University - Program 1 - Write a python program that displays the following information: Your name, Full address Mobile number, College name, Course subjects

 Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 1 - Write a python program that displays the following information: Your name, Full address Mobile  number, College name, Course subjects


Source Code

Here's a simple Python program that takes input for full name, address, mobile number, college name, and course subject, and then displays the entered information. 

Below is a Python program that prompts the user for their full name, address, mobile number, college name, and course subject. Then, it displays this information back to the user. Let's go through the code step by step. 

# Taking user input for personal information
full_name = input("Enter your full name: ")
address = input("Enter your address: ")
mobile_number = input("Enter your mobile number: ")
college_name = input("Enter your college name: ")
course_subject = input("Enter your course subject: ")


# Displaying the entered information
print("\nPersonal Information:")
print("Full Name:", full_name)
print("Address:", address)
print("Mobile Number:", mobile_number)
print("College Name:", college_name)
print("Course Subject:", course_subject)



Explanation of the steps:

User Input: The input() function is used to take input from the user.

The program prompts the user to enter their full name, address, mobile number, college name, and course subject.

The entered values are stored in respective variables (full_name, address, mobile_number, college_name, course_subject).

Display Information: The collected information is displayed back to the user using the print() function.

Each piece of information is printed along with its corresponding label.

When you run this program, it will ask you for the mentioned details one by one.

After you provide the input, it will display the entered information back to you.

Remember, you can run this Python code in any Python environment,

such as IDLE, Python shell, or a code editor like Visual Studio Code or PyCharm.


OUTPUT:
Enter your full name: Ram
Enter your address: 127, Ambedkar street, coimbatore
Enter your mobile number: 1234567890
Enter your college name: psg college of arts and science
Enter your course subject: python programming,data warehousing and data mining, deep learning

Personal Information:
Full Name: Ram
Address: 127, Ambedkar street, coimbatore
Mobile Number: 1234567890
College Name: psg college of arts and science
Course Subject: python programming, data warehousing and data mining, deep learning

Wednesday, October 11, 2023

BCA and B.Sc Programs - Programming in Java Lab - Bharathiar University -Program -9- Write a Java Program to create Menu Bars and pull down menus

 

Bharathiar University

Programming Java Lab
Java Program 9
Write a Java Program to create Menu Bars and pull down menus




Source Code

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

public class UserMenu { 
private static String text=""; 
private static JTextArea content;
    public static void main(String[] args) {
        JFrame frame = new JFrame("Menu Program");
   frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        content=new JTextArea(50,50);
        content.setFont(new Font("Serif",Font.PLAIN,20));
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenuItem newItem = new JMenuItem("New");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem exitItem = new JMenuItem("Exit");

        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);

      JMenu editMenu = new JMenu("Edit");
       JMenuItem cutItem = new JMenuItem("Cut");
      JMenuItem copyItem = new JMenuItem("Copy");
      JMenuItem pasteItem = new JMenuItem("Paste");
      JMenuItem selectallItem = new JMenuItem("Select All");

        editMenu.add(cutItem);
        editMenu.add(copyItem);
        editMenu.add(pasteItem);
        editMenu.add(selectallItem);

        JMenu helpMenu = new JMenu("Help");
        JMenuItem aboutItem = new JMenuItem("About");
        helpMenu.add(aboutItem);

        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(helpMenu);

frame.setJMenuBar(menuBar);
frame.add(new JScrollPane(content));
frame.setVisible(true);

newItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        content.setText("");
            }
        });

exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });



 cutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
  text=(String)content.getSelectedText();
     content.replaceSelection("");

            }
        });

 copyItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
          text=(String)content.getSelectedText();

            }
        });

 pasteItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        int pos=content.getCaretPosition();
        content.insert(text,pos);
            }
        });

 selectallItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        content.selectAll();
            }
        });
        aboutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Menu Bar and Pull DownMenu Program");
            }
        });
    }
}

OUTPUT:






















Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...