Q. Write a program, which accepts a character from the user and checks if it is an alphabet, digit or punctuation symbol. If it is an alphabet, check if it is uppercase or lowercase and then change the case.
Program
#include<stdio.h>
int main()
{
char ch;
printf("Enter Character : ");
scanf("\n %c",&ch);
if((ch>=65 && ch<=90 )|| (ch>=97 && ch<=122))
{
printf("\nIt is an Alphabet.:");
if(isupper(ch))
{
ch=tolower(ch);
printf("%c",ch);
}
else
{
ch=toupper(ch);
printf("%c",ch);
}
}
if(ch>=48 && ch<=57)
{
printf("\n'%c' is Digit.",ch);
}
if((ch>=58 && ch<=64) || (ch>=91 && ch<=96) || (ch>=33 && ch<=47) || (ch>=123 && ch<=126))
{
printf("\n'%c' is Punctuation Symbol.",ch);
}
return 0;
}
Output:
Enter Character : r
It is an Alphabet.:R
Program
#include<stdio.h>
int main()
{
char ch;
printf("Enter Character : ");
scanf("\n %c",&ch);
if((ch>=65 && ch<=90 )|| (ch>=97 && ch<=122))
{
printf("\nIt is an Alphabet.:");
if(isupper(ch))
{
ch=tolower(ch);
printf("%c",ch);
}
else
{
ch=toupper(ch);
printf("%c",ch);
}
}
if(ch>=48 && ch<=57)
{
printf("\n'%c' is Digit.",ch);
}
if((ch>=58 && ch<=64) || (ch>=91 && ch<=96) || (ch>=33 && ch<=47) || (ch>=123 && ch<=126))
{
printf("\n'%c' is Punctuation Symbol.",ch);
}
return 0;
}
Output:
Enter Character : r
It is an Alphabet.:R


11 Comments
1 tic tack toe
ReplyDeletedef print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def check_win(board, player):
for i in range(3):
if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
return True
if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
return True
return False
def is_board_full(board):
return all(board[i][j] != " " for i in range(3) for j in range(3))
def tic_tac_toe():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
print(f"Player {current_player}'s turn.")
row = int(input("Enter row (0, 1, or 2): "))
col = int(input("Enter column (0, 1, or 2): "))
if board[row][col] != " ":
print("That position is already taken. Try again.")
continue
board[row][col] = current_player
print_board(board)
if check_win(board, current_player):
print(f"Player {current_player} wins!")
break
if is_board_full(board):
print("It's a tie!")
break
current_player = "O" if current_player == "X" else "X"
if __name__ == "__main__":
tic_tac_toe()
2 DFS Program
ReplyDeletegraph = {
'1': ['2', '3'],
'2': ['4', '5'],
'3': ['6'],
'4': [],
'5': [],
'6': []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("Depth First Search starting from node 1:")
dfs(visited, graph, '1')
3 Breadth First Search (BFS)
ReplyDeletefrom collections import deque
def bfs(graph, start):
queue = deque([start])
visited = set()
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=" ")
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
graph = {
'1': ['2', '3'],
'2': ['1', '4', '5'],
'3': ['1', '6'],
'4': ['2'],
'5': ['2', '6'],
'6': ['3', '5']
}
print("Breadth First Search starting from node 1:")
bfs(graph, '1')
4 Water Jug Problem
ReplyDeletedef gcd(a, b):
while b:
a, b = b, a % b
return a
def display_state(jug1, jug2):
print(f"{'JUG 1: ':>11}{jug1:<6} | {'JUG 2: ':>12}{jug2}")
def pour_water(jug1, jug2, capacity1, capacity2):
pour_amount = min(jug1, capacity2 - jug2)
jug1 -= pour_amount
jug2 += pour_amount
return jug1, jug2
def water_jug_solution(capacity1, capacity2, target_amount):
jug1 = 0
jug2 = 0
print(f"Jug 1 Capacity: {capacity1} | Jug 2 Capacity: {capacity2}")
while jug1 != target_amount and jug2 != target_amount:
if jug1 == 0:
jug1 = capacity1
elif jug2 == capacity2:
jug2 = 0
else:
jug1, jug2 = pour_water(jug1, jug2, capacity1, capacity2)
display_state(jug1, jug2)
first_jug = int(input("Enter the capacity of the first jug: "))
second_jug = int(input("Enter the capacity of the second jug: "))
target_amount = int(input("Enter the target liters of water: "))
if target_amount < first_jug or target_amount < second_jug:
if target_amount % gcd(first_jug, second_jug) == 0:
water_jug_solution(first_jug, second_jug, target_amount)
else:
print("This is not possible....")
else:
print("This is not possible....")
5 Basic Text Editor
ReplyDeletefrom tkinter import *
root = Tk()
root.geometry("350x250")
root.title("Sticky Notes")
root.minsize(height=250, width=350)
root.maxsize(height=250, width=350)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text_info = Text(root, yscrollcommand=scrollbar.set)
text_info.pack(fill=BOTH)
scrollbar.config(command=text_info.yview)
root.mainloop()
6 To-Do List
ReplyDeleteimport tkinter as tk
from tkinter import messagebox
class ToDoApp:
def __init__(self, root):
self.root = root
self.root.title("To-Do List Application")
self.root.geometry("400x500")
self.root.resizable(False, False)
self.tasks = []
tk.Label(root, text="My To-Do List", font=("Arial", 18, "bold")).pack(pady=10)
self.task_entry = tk.Entry(root, font=("Arial", 14))
self.task_entry.pack(pady=10, padx=10, fill=tk.X)
btn_frame = tk.Frame(root)
btn_frame.pack(pady=5)
tk.Button(btn_frame, text="Add Task", width=12,
command=self.add_task).grid(row=0, column=0, padx=5)
tk.Button(btn_frame, text="Delete Task", width=12,
command=self.delete_task).grid(row=0, column=1, padx=5)
tk.Button(btn_frame, text="Clear All", width=12,
command=self.clear_all).grid(row=0, column=2, padx=5)
self.task_listbox = tk.Listbox(root, font=("Arial", 14),
selectmode=tk.SINGLE, height=15)
self.task_listbox.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
scrollbar = tk.Scrollbar(self.task_listbox)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.task_listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.task_listbox.yview)
def add_task(self):
task = self.task_entry.get().strip()
if task == "":
messagebox.showwarning("Input Error", "Please enter a task.")
return
self.tasks.append(task)
self.update_listbox()
self.task_entry.delete(0, tk.END)
def delete_task(self):
try:
selected_index = self.task_listbox.curselection()[0]
del self.tasks[selected_index]
self.update_listbox()
except IndexError:
messagebox.showwarning("Selection Error",
"Please select a task to delete.")
def clear_all(self):
if messagebox.askyesno("Clear All",
"Are you sure you want to delete all tasks?"):
self.tasks.clear()
self.update_listbox()
def update_listbox(self):
self.task_listbox.delete(0, tk.END)
for task in self.tasks:
self.task_listbox.insert(tk.END, task)
if __name__ == "__main__":
root = tk.Tk()
app = ToDoApp(root)
root.mainloop()
7 Simple Chatbot using Keyword Matching
ReplyDeleteimport random
import re
responses = {
"hello": [
"Hello there!",
"Hi! How can I help you today?",
"Hey! What's up?"
],
"how are you": [
"I'm just a program, but I'm doing great!",
"Feeling binary good today!",
"I'm fine, thanks for asking!"
],
"name": [
"I'm your friendly chatbot.",
"You can call me ChatPy.",
"I don't have a fancy name, but I can chat!"
],
"weather": [
"I can't check the weather, but I hope it's nice where you are!",
"It's always sunny in my code!"
],
"bye": [
"Goodbye!",
"See you later!",
"Bye! Have a great day!"
],
"joke": [
"Why do programmers prefer dark mode? Because light attracts bugs!",
"Why was the computer cold? It forgot to close its Windows!",
"I told my computer I needed a break, and it said 'No problem, I'll go to sleep.'"
]
}
fallback_responses = [
"Interesting... tell me more.",
"Hmm, I see. Can you elaborate?",
"That's fascinating!",
"Why do you say that?",
"I'm not sure I understand, but please continue."
]
def preprocess_input(user_input):
return re.sub(r'[^\w\s]', '', user_input.strip().lower())
def chatbot():
print("Chatbot: Hello! I'm here to chat with you. Type 'bye' to exit.")
while True:
try:
user_input = input("You: ").strip()
if not user_input:
print("Chatbot: Please say something.")
continue
processed_input = preprocess_input(user_input)
if processed_input == "bye":
print(random.choice(responses["bye"]))
break
matched = False
for keyword, reply_list in responses.items():
if keyword in processed_input:
print("Chatbot:", random.choice(reply_list))
matched = True
break
if not matched:
print("Chatbot:", random.choice(fallback_responses))
except KeyboardInterrupt:
print("\nChatbot: Goodbye!")
break
except Exception as e:
print(f"Chatbot: Oops! Something went wrong: {e}")
if __name__ == "__main__":
chatbot()
8 Rule-Based Knowledge Representation
ReplyDeleterules = [
{"if": ["fever", "cough"], "then": "flu"},
{"if": ["fever", "rash"], "then": "measles"},
{"if": ["sore_throat", "fever"], "then": "strep_throat"},
{"if": ["flu"], "then": "rest_needed"},
{"if": ["measles"], "then": "isolate_patient"},
{"if": ["strep_throat"], "then": "antibiotics_needed"}
]
facts = set()
def forward_chaining(rules, facts):
inferred = True
while inferred:
inferred = False
for rule in rules:
if all(condition in facts for condition in rule["if"]):
if rule["then"] not in facts:
facts.add(rule["then"])
print(f"[Inference] Added fact: {rule['then']}")
inferred = True
return facts
def get_user_facts():
print("Enter known symptoms/facts (comma-separated)")
user_input = input("Facts: ").strip().lower()
if not user_input:
print("No facts entered. Exiting.")
exit(1)
return set(fact.strip() for fact in user_input.split(",") if fact.strip())
if __name__ == "__main__":
try:
facts = get_user_facts()
print("\n[Initial Facts]", facts)
final_facts = forward_chaining(rules, facts)
print("\n[Final Facts]", final_facts)
except KeyboardInterrupt:
print("\nProcess interrupted by user.")
except Exception as e:
print(f"Error: {e}")
9 Tower of Hanoi
ReplyDeletedef tower_of_hanoi(n, source, auxiliary, target):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)
def main():
try:
n = int(input("Enter the number of disks: "))
if n <= 0:
print("Number of disks must be a positive integer.")
return
print(f"\nSolution for {n} disks:\n")
tower_of_hanoi(n, 'A', 'B', 'C')
print(f"\nTotal moves required: {2**n - 1}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
if __name__ == "__main__":
main()
10 N-Queens Problem
ReplyDeletedef print_board(board):
for row in board:
print(" ".join("Q" if col else "." for col in row))
print("\n" + "-" * (2 * len(board) - 1) + "\n")
def is_safe(board, row, col, n):
for i in range(row):
if board[i][col]:
return False
i, j = row, col
while i >= 0 and j >= 0:
if board[i][j]:
return False
i -= 1
j -= 1
i, j = row, col
while i >= 0 and j < n:
if board[i][j]:
return False
i -= 1
j += 1
return True
def solve_n_queens(board, row, n, solutions):
if row == n:
solutions.append([r[:] for r in board])
return
for col in range(n):
if is_safe(board, row, col, n):
board[row][col] = 1
solve_n_queens(board, row + 1, n, solutions)
board[row][col] = 0
def n_queens(n):
if not isinstance(n, int) or n <= 0:
raise ValueError("N must be a positive integer greater than 0.")
board = [[0] * n for _ in range(n)]
solutions = []
solve_n_queens(board, 0, n, solutions)
return solutions
if __name__ == "__main__":
try:
N = int(input("Enter the value of N (>=4 recommended): "))
solutions = n_queens(N)
print(f"\nTotal solutions for {N}-Queens: {len(solutions)}\n")
for idx, sol in enumerate(solutions, start=1):
print(f"Solution {idx}:")
print_board(sol)
except ValueError as e:
print(f"Error: {e}")
Tic-Tac-Toe – 2-player game; checks rows, columns, diagonals to find winner.
ReplyDeleteDFS – visits one path deeply first, then other paths.
BFS – visits level by level using a queue.
Water Jug – fills, empties, and pours water to get target amount; uses gcd.
Text Editor – simple Tkinter window with text box and scrollbar.
To-Do List – add, delete, and clear tasks using Tkinter.
Chatbot – replies by matching keywords in user input.
Rule-Based System – uses if-then rules and forward chaining.
Tower of Hanoi – recursive disk-moving problem.
N-Queens – places queens safely using backtracking.