0% found this document useful (0 votes)
9 views

AnshYadavCP

Uploaded by

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

AnshYadavCP

Uploaded by

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

Netaji subhas

uNiversity of techNology

Computer Programming File

Submitted By :- Ansh Yadav


Roll No.-2022UIT3001
S.no. Practicals Signature
Write a C program to input 3
1 numbers and print their
average.
Write a C program to enter the
2 radius of circle/sphere and
compute its (i) Perimeter (ii)
Area and (iii)
Write a program in C to show
3 that Right shift effectively
divides a number by 2 and a left
shift effectively multiplies a
number by 2
Write a C program to find the
4 roots of an quadratic equation
Write down a function in C to
5 implement bitwise AND, OR,
XOR and NOT operations
Given a n integer number write
6 a program that displays the
number as follows First line: All
digits Second Line :All except
first digit Third line : All except
first two digits . . Last line : The
last digit
Write a program to enter an
7 integer and print the sum of the
digits in the integer
Write a C program to input an
8 investment amount and
compute its fixed deposit
cumulative return after 10
years at the rate of interest of
7.75%

Write A C program to compute


9 the roots of a quadratic
equation.
A company has categorized its
10 employees at 4 different levels
(from 1 to 4). For different
employees at different levels
the perks are as follows
Given a text file, which contains
11 few integers and few strings.
WAP in python to select all the
prime numbers from the file
and store them in another file
Given a text file, which contains
12 few lines.WAP in python to
remove all the articles
(a,an,the)and store in another file
Given a text file, which contains
13 few paragraphs. WAP in python to
append line number before every
line and store it another
file..Count the no of lines in that
file. A line which end with full
stop(.) is counted as one line.
Given a text file, which contains
14 few lines.WAP in python to count
number of characters, words and
lines
(File Encryption and Decryption
15 )Write a program that uses a
dictionary to assign “codes” to
each letter of the alphabet. For
example: codes = { 'A' : '%', 'a' : '9',
'B' : '@', 'b' : '#', etc...} Using this
example, the letter A would be
assigned the symbol %, the letter a
would be assigned the number 9,
the letter B would be assigned the
symbol @, and so forth. The
program should open a specified
text file, read its contents, and
then use the dictionary to write an
encrypted version of the file’s
contents to a second file. Each
character in the second file should
contain the code for the
corresponding character in the
first file. Write a second program
that opens an encrypted file and
displays its decrypted contents on
the screen.
Write a program that opens a
16 specified text file and then
displays a list of all the unique
words found in the file
(Capital Quiz) Write a program
17 that creates a dictionary
containing the U.S. states as
keys and their capitals as
values. (Use the Internet to get
a list of the states and their
capitals.) The program should
then randomly quiz the user by
displaying the name of a state
and asking the user to enter
that state’s capital. The
program should keep a count of
the number of correct and
incorrect responses. (As an
alternative to the U.S. states,
the program can use the names
of countries and their capitals.)
Q1.Write a C program to input 3 numbers and print their average.
Source code and Output:

Q2. Write a C program to enter the radius of circle/sphere and compute its (i)Perimeter (ii) Area and (iii)
Volume

Source code and Output:


Q3. Write a program in C to show that Right shift effectively divides a number by
2 and a left shift effectively multiplies a number by 2.
Source code and Output:
Q4. Write a C program to find the roots of an quadratic equation.
Source code And Output:
Q5. Write down a function in C to implement bitwise AND, OR, XOR and NOT
Operations
Source Code And Output:

Q6. Given a n integer number write a program that displays the number as
follows
First line : All digits
Second Line :All except first digit
Third line : All except first two digits
.
.Last line : The last digit

Output:
Q7. Write a program to enter an integer and print the sum of the digits in the Integer.
Source code And Output:
Q8. Write a C program to input an investment amount and compute its fixed
deposit commulative return after 10 years at the rate of interest of 7.75%
Source code and Output:
Q9. Write A C program to compute the roots of a quadratic equation.

Source code and Output:


Q10. A company has categorized its employees at 4 different levels(from 1 to 4). For different
employees at different levels the perks are as follows

Level TA entertainment Allowance


1 7000 3000
2. 6000 2000
3 5000 1500
4. 5000 1500
For Level 1 Basic salary is between Rs 40000 to 60000 and Tax rate is 10%
For level 2 Basic Salary is between Rs 30000 to 40000 and Tax rate is 8%
For level 3 Basic salary is between Rs 20000 to 30000 and Tax rate is 5%
For Level 4 Basic Salary is between Rs 15000 to 20000 and tax rate is 0 Gross Salary is sum of Basic salary,
Perks and HRA which is 25% of Basic Salary
Tax is computed on Gross Salary. Net Salary is Gross salary- Income tax
Write a Program that will read Employees name, Level and Basic pay and will print Gross
salary, Tax and Net Salary. Use Switch-case statement and if statements

#include <stdio.h>

int main()
{
char name[20];
int level;
float basic_salary, hra, perks, gross_salary, tax, net_salary;

printf("Enter employee name: ");


scanf("%s", name);
printf("Enter employee level (1-4): ");
scanf("%d", &level);
printf("Enter basic salary: ");
scanf("%f", &basic_salary);

switch (level) {
case 1:
perks = 7000 + 3000;
if (basic_salary >= 40000 && basic_salary <= 60000) {
tax = 0.10 * basic_salary;
} else {
printf("Invalid basic salary for level 1\n");
return 0;
}
break;
case 2:
perks = 6000 + 2000;
if (basic_salary >= 30000 && basic_salary <= 40000) {
tax = 0.08 * basic_salary;
} else {
printf("Invalid basic salary for level 2\n");
return 0;
}
break;
case 3:
perks = 5000 + 1500;
if (basic_salary >= 20000 && basic_salary <= 30000) {
tax = 0.05 * basic_salary;
} else {
printf("Invalid basic salary for level 3\n");
return 0;
}
break;

case 4:
perks = 5000 + 1500;
if (basic_salary >= 15000 && basic_salary <= 20000) {
tax = 0.0;
} else {
printf("Invalid basic salary for level 4\n");
return 0;
}
break;
default:
printf("Invalid level\n");
return 0;
}

hra = 0.25 * basic_salary;


gross_salary = basic_salary + perks + hra;
net_salary = gross_salary - tax;

printf("\nEmployee Name: %s\n", name);


printf("Level: %d\n", level);
printf("Basic Salary: %.2f\n", basic_salary);
printf("Perks: %.2f\n", perks);
printf("HRA: %.2f\n", hra);
printf("Gross Salary: %.2f\n", gross_salary);
printf("Tax: %.2f\n", tax);
printf("Net Salary: %.2f\n", net_salary);

return 0;
}
Output:

11 :Given a text file, which contains few integers and few strings.
WAP in python to select all the prime numbers from the file and
store them in another file.
Solution :
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def extract_primes(input_file, output_file):
"""Extract prime numbers from input_file and save to output_file."""
with open(input_file, 'r') as infile:
data = infile.read().split() # Read file and split into words
primes = []
for item in data:
if item.isdigit(): # Check if item is a number
num = int(item)
if is_prime(num): # Check if it's a prime number
primes.append(num)
with open(output_file, 'w') as outfile:
outfile.write('\n'.join(map(str, primes))) # Write primes to output file
# Specify input and output file paths
input_file = 'input.txt'
output_file = 'primes.txt'
# Call the function
extract_primes(input_file, output_file)
print(f"Prime numbers have been written to {output_file}.")
Input :
23 apple 45 67 banana 89 12 10
Output :
23
67
89
12.Given a text file, which contains few lines.WAP in python to
remove all the articles (a,an,the)and store in another file.
Solution :
def remove_articles(input_file, output_file):
"""Remove articles ('a', 'an', 'the') from input_file and save to output_file."""
articles = {"a", "an", "the"}

with open(input_file, 'r') as infile:


lines = infile.readlines() # Read all lines from the file

cleaned_lines = []
for line in lines:
words = line.split() # Split line into words
# Remove articles
filtered_words = [word for word in words if word.lower() not in articles]
cleaned_lines.append(' '.join(filtered_words)) # Join filtered words back
into a line

with open(output_file, 'w') as outfile:


outfile.write('\n'.join(cleaned_lines)) # Write cleaned lines to output file
# Specify input and output file paths
input_file = 'input.txt'
output_file = 'cleaned.txt'
# Call the function
remove_articles(input_file, output_file)
print(f"File with articles removed has been written to {output_file}.")
13. . Given a text file, which contains few paragraphs. WAP in python to
append line number before every line and store it another file..Count the
no of lines in that file. A line which end with full stop(.) is counted as one
line.
For eg. Input-Python is a programming language. C++ is object oriented
programming language.C is procedural programming language
Output-
1. Python is a programming language
2. C++ is object oriented programming language
3. C is procedural programming languange .
Solution :
def process_file(input_file, output_file):
"""Append line numbers and count the lines ending with a full stop."""
with open(input_file, 'r') as infile:
content = infile.read() # Read the entire file

# Split content into lines based on full stop followed by optional


whitespace
lines = [line.strip() for line in content.split('.') if line.strip()]
line_count = len(lines) # Count the number of valid lines

with open(output_file, 'w') as outfile:


for i, line in enumerate(lines, 1): # Enumerate lines starting from 1
outfile.write(f"{i}. {line}\n") # Write each line with line number

return line_count
# Specify input and output file paths
input_file = 'input.txt'
output_file = 'output.txt'
# Call the function and get the line count
line_count = process_file(input_file, output_file)
print(f"Processed text has been written to {output_file}.")
print(f"Number of lines in the output file: {line_count}")
Input :
Python is a programming language. C++ is object oriented programming
language.C is procedural programming language
Output :
1. Python is a programming language
2. C++ is object oriented programming language
3. C is procedural programming language
14. Given a text file, which contains few lines.WAP in python to
count number of characters, words and lines.
Solution :
def count_file_contents(input_file):
"""Count characters, words, and lines in a text file."""
with open(input_file, 'r') as infile:
lines = infile.readlines() # Read all lines from the file
# Count lines
line_count = len(lines)
# Count words and characters
word_count = 0
char_count = 0
for line in lines:
words = line.split() # Split line into words
word_count += len(words)
char_count += len(line) # Include spaces and punctuation
return char_count, word_count, line_count
# Specify input file path
input_file = 'input.txt'
# Call the function and get counts
char_count, word_count, line_count = count_file_contents(input_file)
# Display the results
print(f"Number of characters: {char_count}")
print(f"Number of words: {word_count}")
print(f"Number of lines: {line_count}")
Input : This is the first line.
Here is the second line.
And the third one.
Output : Number of characters: 69
Number of words: 14
Number of lines: 3
15 : (File Encryption and Decryption )Write a program that uses a
dictionary to assign “codes” to each letter of the alphabet. For example:
codes = { 'A' : '%', 'a' : '9', 'B' : '@', 'b' : '#', etc...} Using this example, the
letter A would be assigned the symbol %, the letter a would be assigned
the number 9, the letter B would be assigned the symbol @, and so
forth. The program should open a specified text file, read its contents,
and then use the dictionary to write an encrypted version of the file’s
contents to a second file. Each character in the second file should
contain the code for the corresponding character in the first file. Write a
second program that opens an encrypted file and displays its decrypted
contents on the screen.
Solution :
def encrypt_file(input_file, output_file, codes):
"""Encrypts a file using a dictionary of codes."""
with open(input_file, 'r') as infile:
content = infile.read() # Read the file's contents
encrypted_content = ''.join([codes.get(char, char) for char in content])
# Encrypt content

with open(output_file, 'w') as outfile:


outfile.write(encrypted_content) # Write encrypted content to file
print(f"File encrypted successfully! Encrypted content written to
{output_file}")
# Define the codes dictionary
codes = {
'A': '%', 'a': '9', 'B': '@', 'b': '#', 'C': '&', 'c': '*', 'D': '$', 'd': '!',
'E': '^', 'e': '3', 'F': '(', 'f': ')', 'G': '-', 'g': '_', 'H': '+', 'h': '=',
'I': '[', 'i': ']', 'J': '{', 'j': '}', 'K': '|', 'k': '\\', 'L': ':', 'l': ';',
'M': '<', 'm': '>', 'N': ',', 'n': '.', 'O': '?', 'o': '/', 'P': '`', 'p': '~',
'Q': '1', 'q': '2', 'R': '4', 'r': '5', 'S': '6', 's': '7', 'T': '8', 't': '0',
'U': 'z', 'u': 'x', 'V': 'y', 'v': 'w', 'W': 'v', 'w': 'u', 'X': 't', 'x': 's',
'Y': 'r', 'y': 'q', 'Z': 'p', 'z': 'o', ' ': '_'
}
# Specify input and output file paths
input_file = 'input.txt'
output_file = 'encrypted.txt'
# Call the encryption function
encrypt_file(input_file, output_file, codes)
Input : Hello World
Output: Hello World
16 . . Write a program that opens a specified text file and then displays a
list of all the unique words found in the file.
Solution :
def get_unique_words(input_file):
"""Read a file and return a list of unique words."""
with open(input_file, 'r') as infile:
content = infile.read() # Read the entire file content

# Split content into words and normalize to lowercase


words = content.split()
words = [word.strip('.,!?()[]{}"\'').lower() for word in words] # Remove
punctuation and normalize
# Get unique words
unique_words = sorted(set(words)) # Use set to get unique words
and sort them
return unique_words
# Specify the input file path
input_file = 'input.txt'
# Call the function and get the unique words
unique_words = get_unique_words(input_file)
# Display the unique words
print("Unique Words:")
print(unique_words)
Input :
Hello world! This is a test file. Hello again, world.
Output :
Unique Words:
['a', 'again', 'file', 'hello', 'is', 'test', 'this', 'world']
17. (Capital Quiz) Write a program that creates a dictionary containing
the U.S. states as keys and their capitals as values. (Use the Internet to
get a list of the states and their capitals.) The program should then
randomly quiz the user by displaying the name of a state and asking the
user to enter that state’s capital. The program should keep a count of the
number of correct and incorrect responses. (As an alternative to the U.S.
states, the program can use the names of countries and their capitals.)
Solution :
import random
# Dictionary of U.S. states and their capitals
states_and_capitals = {
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
'Arkansas': 'Little Rock',
'California': 'Sacramento',
'Colorado': 'Denver',
'Connecticut': 'Hartford',
'Delaware': 'Dover',
'Florida': 'Tallahassee',
'Georgia': 'Atlanta',
'Hawaii': 'Honolulu',
'Idaho': 'Boise',
'Illinois': 'Springfield',
'Indiana': 'Indianapolis',
'Iowa': 'Des Moines',
'Kansas': 'Topeka',
'Kentucky': 'Frankfort',
'Louisiana': 'Baton Rouge',
'Maine': 'Augusta',
'Maryland': 'Annapolis',
'Massachusetts': 'Boston',
'Michigan': 'Lansing',
'Minnesota': 'Saint Paul',
'Mississippi': 'Jackson',
'Missouri': 'Jefferson City',
'Montana': 'Helena',
'Nebraska': 'Lincoln',
'Nevada': 'Carson City',
'New Hampshire': 'Concord',
'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe',
'New York': 'Albany',
'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck',
'Ohio': 'Columbus',
'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem',
'Pennsylvania': 'Harrisburg',
'Rhode Island': 'Providence',
'South Carolina': 'Columbia',
'South Dakota': 'Pierre',
'Tennessee': 'Nashville',
'Texas': 'Austin',
'Utah': 'Salt Lake City',
'Vermont': 'Montpelier',
'Virginia': 'Richmond',
'Washington': 'Olympia',
'West Virginia': 'Charleston',
'Wisconsin': 'Madison',
'Wyoming': 'Cheyenne'
}
def quiz_user(states_and_capitals):
"""Quiz the user on U.S. states and capitals."""
correct = 0
incorrect = 0
# Convert the dictionary to a list of states for random selection
states = list(states_and_capitals.keys())
random.shuffle(states)
print("Welcome to the U.S. States and Capitals Quiz!")
print("Type 'exit' to end the quiz at any time.\n")
for state in states:
capital = input(f"What is the capital of {state}? ").strip()

if capital.lower() == 'exit':
break
if capital.lower() == states_and_capitals[state].lower():
print("Correct!")
correct += 1
else:
print(f"Incorrect! The capital of {state} is
{states_and_capitals[state]}.")
incorrect += 1
print("\nQuiz Finished!")
print(f"Correct Answers: {correct}")
print(f"Incorrect Answers: {incorrect}")
# Run the quiz
quiz_user(states_and_capitals)

You might also like