C& Python Lab Manual
C& Python Lab Manual
2023 Regulation
Prepared by
SUGASHINI.P .M.E,
Safety Rules
1. 💻 Handle Equipment with Care
o Do not bang on the keyboard or mouse.
o Avoid moving or tilting monitors or CPU units.
o Use gentle touches when handling devices.
2. ⚡ Electrical Safety
o Do not touch power cables, sockets, or wires with wet hands.
o Avoid overloading power outlets with multiple devices.
o Report any exposed wires or faulty equipment immediately.
3. 🛡️ Data and Privacy Protection
o Do not share your passwords or personal information.
o Log out from your account after use.
o Avoid downloading unauthorized or unknown files.
4. 🚫 Food and Drinks Prohibited
o Do not bring food or beverages near the computers.
o Spills can damage hardware and cause electric shocks.
5. ️ Proper Posture and Ergonomics
o Sit with a straight back and adjust the chair height properly.
o Keep a comfortable distance from the monitor (about 20 inches).
o Take regular breaks to prevent eye strain.
6. 🔥 Fire Safety
o Know the location of fire extinguishers.
o Do not attempt to repair electrical issues yourself—report them.
o In case of fire, leave the lab immediately and call for help.
7. 📚 Follow Lab Rules and Instructions
o Always listen to the lab instructor or technician.
o Do not install or uninstall software without permission.
o Use the equipment for educational purposes only.
8. 🌐 Internet Safety
o Avoid visiting suspicious or inappropriate websites.
o Do not download unknown software or open suspicious emails.
o Use only authorized and legal resources.
9. 🚷 No Unauthorized Access
o Do not access or modify other users' files.
o Only authorized personnel should access the server room.
10. ️ Maintain Cleanliness
Keep the area around the workstation tidy.
Dispose of waste properly and keep the lab clutter-free.
ER. PERUMAL MANIMEKALAI POLYTECHNIC
COLLEGE, HOSUR
VISION OF THE COLLEGE
PMC Tech Polytechnic College shall emerge as a premier Institute for valued added
technical education coupled with Innovation, Incubation, Ethics and Professional values
2023 Regulation
Prepared by
P.SUGASHINI M.E. Lecturer
Department of E-Robotics
Er. Perumal Manimekalai Polytechnic College.
Hosur- 635117
DO'S AND DON'TS IN THE LAB
Do’s
1. Use the lab for its intended purpose: Only work on educational or
authorized activities.
2. Handle equipment carefully: Use the mouse, keyboard, and other
peripherals gently.
3. Keep food and drinks away: To prevent spills and damage.
4. Maintain cleanliness: Keep the workstation tidy and dispose of waste
properly.
5. Save your work frequently: To avoid losing progress due to unexpected
issues.
6. Log out properly: Ensure you sign out of your account when done.
7. Follow the lab rules: Adhere to all lab-specific regulations or guidelines.
8. Ask for help when needed: If you experience issues, inform the lab
supervisor or IT staff.
9. Use authorized software: Only use programs that are approved and installed
by the institution.
10. Respect others: Keep noise levels low and avoid disturbing others.
Don’ts
4
Vision of the Department
To develop Electronics Robotics Engineering diploma holders to meet the growing needs
of industry and society.
Breadth: Our students will be able to design and create novel products and
PEO 2 solutions for real life problems using the knowledge of Scientific, Mechanical,
Electronics and Computer Engineering.
5
PROGRAMME OUTCOMES
6
Contents
PartA
1. Write a simple C Program
a) Print your Name and Address
7
Write a simple c program print your Name and address
Ex No 1a
Date:
Aim:
To write a simple c program print your Name and address.
Program:
#include <stdio.h>
#include<conio.h>
int main ()
{
clrscr();
printf("Name: ROBO\n");
print("Address: 123 AI Street, OpenAI City, CodeLand\n");
getch();
return 0;
}
Output
Name: ROBO
Address: Address: 123 AI Street, OpenAI City, CodeLand
Result:
Thus the C program is executed and the output is verified successfully.
8
Program to calculate simple and compound interest
Ex No 1b
Date:
Aim:
To write and execute a C program to calculate simple and compound interest.
Program:
#include <stdio.h>
#include<conio.h>
#include <math.h>
float calculateSimpleInterest(float principal, float rate, float time)
{
float simpleInterest;
simpleInterest = (principal * rate * time) / 100.0; return
simpleInterest;
}
float calculateCompoundInterest(float principal, float rate, float time) { float
compoundInterest;
compoundInterest = principal * (pow((1 + rate / 100.0), time)) - principal; return
compoundInterest;
}
int main()
{
clrscr();
float principal, rate, time, simpleInterest, compoundInterest;
printf("Enter principal amount: ");
scanf("%f", &principal);
printf("Enter rate of interest (per annum): ");
scanf("%f", &rate);
printf("Enter time period (in years): "); scanf("%f",
&time);
simpleInterest = calculateSimpleInterest(principal, rate, time);
compoundInterest = calculateCompoundInterest(principal, rate, time);
printf("\nSimple Interest: %.2f\n", simpleInterest);
printf("Compound Interest: %.2f\n", compoundInterest); clrscr();
return 0;
}
9
Flow Chart:
Output
Enter principal amount: 1000
Enter rate of interest (per annum): 5
Enter time period (in years): 3
Simple Interest: 150.00
Compound Interest: 157.63
Result:
Thus the C program is executed and the output is verified successfully.
10
Program to swap two variable’s using
(i) Third variable and (ii) Without using a third variable.
Ex No 2
Date:
Aim:
To Write a C program to swap two variable’s using (i) Third variable and (ii) Without using a
third variable.
11
Flow Chart
Result:
Thus the C program is executed and the output is verified successfully.
12
Program to find the largest number between given three numbers.
Ex No 3
Date:
Aim:
To write a program to find the largest number between given three numbers.
Program:
#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
int num1, num2, num3;
printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
int largest = num1;
if (num2 > largest)
{
largest = num2;
}
if (num3 > largest)
{
largest = num3;
}
printf("The largest number is: %d\n", largest);
getch();
return 0;
}
Output :
Enter three integers: 25 10 45
The largest number is: 45
13
Flow Chart
Result:
Thus the C program is executed and the output is verified successfully.
14
Write a Python Program to print prime numbers in the given
range Ex No 4a
Date:
Aim:
To write a Python Program to print prime numbers in the given range.
Program:
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1): # Check divisibility up to the square root of num
if num % i == 0:
return False
return True
Output :
15
Flow Chart
Result:
Thus the Python program is executed and the output is verified successfully.
16
Write a Python Program to convert decimal to binary and octal
Ex No 4b
Date:
Aim:
To Write a Python Program to convert decimal to binary and octal
Program:
def decimal_to_octal(num):
return oct(num)[2:] # oct() returns a string with a '0o' prefix, so we slice off the '0o'
print(f"Decimal: {decimal_number}")
print(f"Binary: {binary}")
print(f"Octal: {octal}")
Output :
Result:
Thus the Python program is executed and the output is verified successfully.
17
Write a Python Program to check the given year is leap year or not.
Ex No 5a
Date:
Aim:
To Write a Python Program to check the given year is leap year or not.
Program:
def is_leap_year(year):
"""
Function to check if a given year is a leap year or not.
"""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
18
Write a Python Program to print Armstrong numbers between given range.
Ex No 5b
Date:
Aim:
To Write a Python Program to print Armstrong numbers between given range.
Program:
def is_armstrong(num):
"""Check if a number is an Armstrong number."""
digits = [int(d) for d in str(num)]
num_digits = len(digits)
sum_of_powers = sum(d ** num_digits for d in digits)
return sum_of_powers == num
# Input range
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
19
Write a Python program function for display calendar
Ex No 6
Date:
Aim:
To Write a Python program function for display calendar.
Program:
import calendar
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
20
Write a Python Program using recursion to print ‘n’ terms in Fibonacci series.
Ex No 7a
Date:
Aim:
To Write a Python Program using recursion to print ‘n’ terms in Fibonacci series.
Program:
def fibonacci(n):
"""Recursive function to return the nth Fibonacci number."""
if n <= 0:
return 0
elif n ==
1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def print_fibonacci_series(n):
"""Print the first n terms of the Fibonacci series."""
for i in range(n):
print(fibonacci(i), end=' ')
print() # For a new line after printing all terms
def main():
# Get the number of terms from the user
n = int(input("Enter the number of terms in the Fibonacci series: "))
if n > 0:
print_fibonacci_series(n)
else:
print("Please enter a positive integer.")
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
21
Write a Python Program using without recursion to print ‘n’ terms in Fibonacci
series Ex No 7b
Date:
Aim:
To Write a Python Program using without recursion to print ‘n’ terms in Fibonacci series
Program:
def print_fibonacci_series(n):
"""Print the first n terms of the Fibonacci series."""
if n <= 0:
print("Please enter a positive integer.")
return
elif n == 1:
print("0")
return
elif n == 2:
print("0 1")
return
def main():
# Get the number of terms from the user
n = int(input("Enter the number of terms in the Fibonacci series: "))
print_fibonacci_series(n)
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
22
Write a program to prepare the total marks for N students by reading
the Reg. No, Name, and Mark1 to Mark6 by using array of structures.
Ex No 8
Date:
Aim:
To write a program to prepare the total marks for N students by reading the Reg. No, Name, and
Mark1 to Mark6 by using array of structures.
Program:
def calculate_total_marks(students):
for student in students:
total_marks = sum(student['marks'])
student['total_marks'] = total_marks
def display_student_details(students):
print("Student details with total marks:")
for student in students:
print(f"Registration Number: {student['reg_no']}, Name: {student['name']}, Total Marks:
{student['total_marks']}")
if name == " main ":
# Number of students
N=3
students = []
for i in range(N):
reg_no = input(f"Enter Registration Number for student {i+1}: ")
name = input(f"Enter Name for student {i+1}: ")
marks = []
for j in range(6):
mark = float(input(f"Enter Mark{j+1} for {name}: "))
marks.append(mark)
student_details = {
'reg_no': reg_no,
'name': name,
'marks': marks,
'total_marks': 0 # Placeholder for total marks
}
students.append(student_details)
calculate_total_marks(students)
display_student_details(students)
23
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
24
Write a program using the function power (a,b) to calculate the value of a raised to
b Ex No 9
Date:
Aim:
To Write a program using the function power (a,b) to calculate the value of a raised to b.
Program:
def power(a, b):
"""Calculate and return a raised to the power of b."""
return a ** b
def main():
# Input base and exponent from the user
a = float(input("Enter the base (a): "))
b = int(input("Enter the exponent (b): "))
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
25
Write a program to find the length of the given string using
pointers
Ex No 10
Date:
Aim:
To write a program to find the length of the given string using pointers
Program:
def find_string_length(s):
length = 0
while s[length:]:
length += 1
return length
if name == " main ":
string = input("Enter a string: ")
length = find_string_length(string)
print(f"Length of the string '{string}' is:
{length}")
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
26
Write a program to find factorial of a number using recursion.
Ex No 11
Date:
Aim:
To write a program to find factorial of a number using recursion.
Program:
def. factorial(n):
"""Calculate the factorial of a number using recursion."""
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)
def main():
# Input a number from the user
number = int(input("Enter a non-negative integer: "))
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
27
Write a Python Program to make a simple calculator
Ex No 12
Date:
Aim:
To Write a Python Program to make a simple calculator.
Program:
def add(x, y):
"""Return the sum of x and y."""
return x + y
def main():
while True:
# Display the menu
print("\nSimple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
28
if choice == '5':
print("Exiting...")
break
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
29
Write a Python Program to take a list of words and return the length of
the longest one using string.
Ex No 13
Date:
Aim:
To Write a Python Program to take a list of words and return the length of the longest one using
string.
Program:
def longest_word_length(words):
"""Return the length of the longest word in the list.""" #
Check if the list is empty
if not words:
return 0
# Find the longest word using the max function with key=len
longest_word = max(words, key=len)
def main():
# Input a list of words from the user
words = input("Enter a list of words separated by spaces: ").split()
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
30
Write a Python Program to copy file contents from one file to another
and display number of words copied
Ex No 14
Date:
Aim:
To Write a Python Program to copy file contents from one file to another and display number of words
copied
Program:
def copy_file_contents(source_file, destination_file):
"""Copy contents from source_file to destination_file and return the number of words
copied."""
try:
# Open the source file in read mode
with open(source_file, 'r') as src:
content = src.read()
return word_count
except
FileNotFoundError:
print(f"Error: The file {source_file} was not found.")
return 0
except IOError as e:
print(f"Error: An IOError occurred.
{e}") return 0
def main():
# Get the names of the source and destination files from the user
source_file = input("Enter the source file name: ")
destination_file = input("Enter the destination file name: ")
if words_copied > 0:
print(f"Contents copied successfully. Number of words copied: {words_copied}")
else:
print("Failed to copy contents.")
31
Output:
Successfully copied 6 words from 'source.txt' to 'destination.txt'.
Result:
Thus the Python program is executed and the output is verified successfully.
32
Write a Python Program to demonstrate to use Dictionary and related
Functions. Ex No 15
Date:
Aim:
To Write a Python Program to demonstrate to use Dictionary and related Functions.
Program:
def demo_dictionary_operations():
# Create a dictionary
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
33
items = my_dict.items()
print("\nKeys:", list(keys))
print("Values:",
list(values)) print("Items:",
list(items))
def main():
demo_dictionary_operations()
Output:
Result:
Thus the Python program is executed and the output is verified successfully.
34
Write a C program to perform logic gates
Ex No 16
Date:
Aim:
To Write a C program to perform logic gates
Program:
#include <stdio.h>
#include<conio.h>
int and_gate(int a, int b);
int or_gate(int a, int b);
int not_gate(int a);
int xor_gate(int a, int b);
int main()
{
clrscr();
int input1, input2;
printf("Enter first input (0 or 1): ");
scanf("%d", &input1);
printf("Enter second input (0 or 1): ");
scanf("%d", &input2);
printf("\nAND Gate: %d AND %d = %d\n", input1, input2, and_gate(input1, input2));
printf("OR Gate: %d OR %d = %d\n", input1, input2, or_gate(input1, input2));
printf("NOT Gate for %d = %d\n", input1, not_gate(input1));
printf("XOR Gate: %d XOR %d = %d\n", input1, input2, xor_gate(input1, input2));
getch();
return 0;
}
int and_gate(int a, int b) {
return a && b;
}
int or_gate(int a, int b) {
return a || b;
}
int not_gate(int a) {
return !a;
}
int xor_gate(int a, int b) {
return a ^ b;
}
35
Output:
Enter first input (0 or 1): 1
OR Gate: 1 OR 0 = 1
Result:
Thus the C program is executed and the output is verified successfully.
36
Write a python program to calculate Ohm’s Law
Ex No 17
Date:
Aim:
To write a python program to calculate Ohm’s law
Program:
def calculate_voltage(current, resistance): """
Calculate voltage using Ohm's law """
return current * resistance
def calculate_current(voltage, resistance): """
Calculate current using Ohm's law """
return voltage / resistance
def calculate_resistance(voltage, current):
""" Calculate resistance using Ohm's law """
return voltage / current
if name == " main ":
print("Ohm's Law
Calculator")
print("Choose what you want to calculate:")
print("1. Voltage (V)")
print("2. Current (I)")
print("3. Resistance (R)")
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
current = float(input("Enter current (I) in amperes: "))
resistance = float(input("Enter resistance (R) in ohms: "))
voltage = calculate_voltage(current, resistance)
print(f"The voltage (V) across the circuit is: {voltage} volts")
elif choice == 2:
voltage = float(input("Enter voltage (V) in volts: "))
resistance = float(input("Enter resistance (R) in ohms: "))
current = calculate_current(voltage, resistance)
print(f"The current (I) flowing through the circuit is: {current} amperes")
elif choice == 3:
voltage = float(input("Enter voltage (V) in volts: "))
current = float(input("Enter current (I) in amperes: "))
resistance = calculate_resistance(voltage, current)
print(f"The resistance (R) of the circuit is: {resistance} ohms")
else:
print("Invalid choice. Please enter a valid option (1/2/3).")
37
Output:
Ohm's Law Calculator
1. Voltage (V)
2. Current (I)
3. Resistance (R)
Result:
Thus the Python program is executed and the output is verified successfully.
38