C Program 1-14
C Program 1-14
Traverse:
arr=[1,2,3,4,5]
n=len(arr)
for i in range(n):
print(f"arr[{i}]={arr[i]}")
output:
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4
arr[4]=5
Insertion:
arr = [1, 2, 3, 4, 5]
n = len(arr)
pos = 2
x = 10
for i in range(n):
print(f"arr[{i}]={arr[i]}")
arr.append(0)
for i in range(pos,n -1):
arr[i] = arr[i - 1]
arr[pos] = x
n += 1
for i in range(n):
print(f"arr[{i}]={arr[i]}")
output:
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4
arr[4]=5
arr[0]=1
arr[1]=2
arr[2]=10
arr[3]=3
arr[4]=4
arr[5]=5
Deletion:
arr = [1, 2, 3, 4, 5]
n = len(arr)
pos = 2
for i in range(n):
print(f"arr[{i}] = {arr[i]}")
for i in range(pos, n-1):
arr[i] = arr[i+1]
n -= 1
for i in range(n):
print(f"arr[{i}] = {arr[i]}")
output:
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
arr[0] = 1
arr[1] = 2
arr[2] = 4
arr[3] = 5
Program No:03
Linear search:
arr = [1, 5, 3, 2, 6]
x=5
found = False
for i in range(5):
if arr[i] == x:
print(f"Element {x} found at position {i}.")
found = True
if not found:
print(f"Element {x} not found in the array!")
Output:
Element 5 found at position 1.
Binary search:
arr = [2, 4, 6, 8, 10, 12]
n=6
x = 10
low = 0
high = n - 1
found = False
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
print(f"Element {x} found at index {mid}")
found = True
break
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
if not found:
print(f"Element {x} not found")
Output:
Element 10 found at index 4.
Program No:04
Stack Implementation:
stack = []
max_size = 5
def push(value):
if len(stack) == max_size:
print(f"Stack Overflow! Cannot push {value} onto the stack.")
else:
stack.append(value)
print(f"Pushed {value} onto the stack.")
def pop():
if len(stack) == 0:
print("Stack Underflow! Cannot pop from the stack.")
else:
value = stack.pop()
print(f"Popped {value} from the stack.")
def display():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Stack elements are:")
for element in reversed(stack):
print(element)
def peek():
if len(stack) == 0:
print("Stack is empty.")
else:
print(f"Top element is {stack[-1]}")
def main():
while True:
print("\nStack Operations:")
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
print("4. PEEK")
print("5. EXIT")
if choice == 1:
value = int(input("Enter the value to push: "))
push(value)
elif choice == 2:
pop()
elif choice == 3:
display()
elif choice == 4:
peek()
else:
print("Invalid choice! Please try again.")
break
main()
Output:
Stack Operations:
1. PUSH
2. POP
3. DISPLAY
4. PEEK
5. EXIT
Enter your choice: 1
Enter the value to push: 10
Pushed 10 onto the stack.
Enter your choice: 1
Enter the value to push: 20
Pushed 20 onto the stack.
Enter your choice: 1
Enter the value to push: 30
Pushed 30 onto the stack.
Enter your choice: 1
Enter the value to push: 40
Pushed 40 onto the stack.
Enter your choice: 3
Stack elements are:
40
30
20
10
Enter your choice: 2
Popped 40 from the stack.
Enter your choice: 3
Stack elements are:
30
20
10
Enter your choice: 4
Top element is 30
Enter your choice: 5
Exiting the program.
Program No:05
Queue implementation:
max_size = 5
queue = []
def enqueue(value):
if len(queue) >= max_size:
print(f"Queue Overflow! Cannot enqueue {value}.")
else:
queue.append(value)
print(f"Enqueued {value} into the queue.")
def dequeue():
if not queue:
print("Queue Underflow! Cannot dequeue.")
else:
print(f"Dequeued {queue.pop(0)} from the queue.")
def display():
if not queue:
print("Queue is empty.")
else:
print("Queue elements are:", *queue)
def main():
while True:
print("\nQueue Operations:")
print("1. ENQUEUE")
print("2. DEQUEUE")
print("3. DISPLAY")
print("4. EXIT")
choice = int(input("Enter your choice: "))
if choice == 1:
value = int(input("Enter the value to enqueue: "))
enqueue(value)
elif choice == 2:
dequeue()
elif choice == 3:
display()
elif choice == 4:
break
else:
print("Invalid choice! Please try again.")
main()
Output:
Queue Operations:
1. ENQUEUE
2. DEQUEUE
3. DISPLAY
4. EXIT
Enter your choice: 1
Enter the value to enqueue: 10
Enqueued 10 into the queue.
Enter your choice: 1
Enter the value to enqueue: 20
Enqueued 20 into the queue.
Enter your choice: 1
Enter the value to enqueue: 30
Enqueued 30 into the queue.
Enter your choice: 3
Queue elements are: 10 20 30
Enter your choice: 2
Dequeued 10 from the queue.
Enter your choice: 3
Queue elements are: 20 30
Program No:06
Single linked list:
class Node:
def __init__(self, data):
self.data = data
self.next = None
head = None
def insert(value):
global head
new_node = Node(value)
if not head: # If list is empty, new node becomes the head
head = new_node
else:
temp = head
while temp.next: # Traverse to the last node
temp = temp.next
temp.next = new_node
print(f"Inserted {value}.")
def delete(value):
global head
temp = head
prev = None
prev.next = temp.next
del temp
print(f"Deleted {value}.")
def display():
temp = head
if not head:
print("List is empty.")
return
while temp:
print(temp.data, end=" -> ")
temp = temp.next
print("NULL")
def main():
while True:
print("\nsingle linked list operation:")
print("1. Insert\n2. Delete\n3. Display\n4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
value = int(input("Enter value to insert: "))
insert(value)
elif choice == 2:
value = int(input("Enter value to delete: "))
delete(value)
elif choice == 3:
display()
elif choice == 4:
break
else:
print("Invalid choice, try again.")
if __name__ == "__main__":
main()
Output:
single linked list operation:
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter value to insert: 50
Inserted 50.
Enter your choice: 1
Enter value to insert: 60
Inserted 60.
Enter your choice: 1
Enter value to insert: 70
Inserted 70.
Enter your choice: 1
Enter value to insert: 80
Inserted 80.
Enter your choice: 3
50 -> 60 -> 70 -> 80 -> NULL
Enter your choice: 2
Enter value to delete: 70
Deleted 70.
Enter your choice: 3
50 -> 60 -> 80 -> NULL
Program No:07
Postfix expression:
def evaluate_postfix(expression):
stack = []
for token in expression.split():
if token.isdigit():
stack.append(int(token))
else:
b, a = stack.pop(), stack.pop()
if token == '+': stack.append(a + b)
elif token == '-': stack.append(a - b)
elif token == '*': stack.append(a * b)
elif token == '/': stack.append(a // b)
else: return f"Invalid operator: {token}"
return stack[0] if stack else "Error"
if __name__ == "__main__":
expression = input("Enter postfix expression: ").strip()
result = evaluate_postfix(expression)
print(f"The result is: {result}")
Output:
Enter postfix expression: 4 3 2 * + 5 -
The result is: 5
Program No:08
Tower of Hanoi:
def tower_of_hanoi(n, froms, to, via):
if n == 1:
print(f"Move disk 1 from rod {froms} to rod {to}")
else:
tower_of_hanoi(n - 1, froms, via, to)
print(f"Move disk {n} from rod {froms} to rod {to}")
tower_of_hanoi(n - 1, via, to, froms)
n = int(input("Enter the number of disks: "))
tower_of_hanoi(n, 'A', 'B', 'C')
Output:
Enter the number of disks: 3
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Program No:09
Stack using linked list:(method 1)
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def pop(self):
if self.is_empty():
print("Stack underflow")
else:
popped = self.stack.pop()
print(f"Popped: {popped}")
def peek(self):
if self.is_empty():
print("Stack is empty")
else:
print(f"Top element: {self.stack[-1]}")
def display(self):
if self.is_empty():
print("Stack is empty")
else:
print("Stack contents:", " -> ".join(map(str, self.stack)) + " ->
NULL")
# Main program
if __name__ == "__main__":
stack = Stack()
while True:
print("\n1. Push\n2. Pop\n3. Peek\n4. Display Stack\n5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
value = int(input("Enter value to push: "))
stack.push(value)
elif choice == 2:
stack.pop()
elif choice == 3:
stack.peek()
elif choice == 4:
stack.display()
elif choice == 5:
break
else:
print("Invalid choice")
(OR)
(method 2)
stack = []
while True:
print("\n1. Push\n2. Pop\n3. Peek\n4. Display Stack\n5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
value = int(input("Enter value to push: "))
stack.append(value)
print(f"{value} pushed to stack")
elif choice == 2:
if stack:
print(f"Popped: {stack.pop()}")
else:
print("Stack underflow")
elif choice == 3:
if stack:
print(f"Top element: {stack[-1]}")
else:
print("Stack is empty")
elif choice == 4:
if stack:
print("Stack contents:", " -> ".join(map(str, stack)) + " -> NULL")
else:
print("Stack is empty")
elif choice == 5:
break
else:
print("Invalid choice")
Output:
1. Push
2. Pop
3. Peek
4. Display Stack
5. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed to stack
Enter your choice: 1
Enter value to push: 20
20 pushed to stack
Enter your choice: 1
Enter value to push: 30
30 pushed to stack
Enter your choice: 3
Top element: 30
Enter your choice: 4
Stack contents: 10 -> 20 -> 30 -> NULL
Enter your choice: 2
Popped: 30
Enter your choice: 4
Stack contents: 10 -> 20 -> NULL
Program No:10
Stack using linked list:
queue = []
while True:
print("\n1. Enqueue\n2. Dequeue\n3. Display Queue\n4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
value = int(input("Enter value to enqueue: "))
queue.append(value)
print(f"{value} enqueued to queue")
elif choice == 2:
if queue:
print(f"Dequeued: {queue.pop(0)}")
else:
print("Queue underflow")
elif choice == 3:
if queue:
print("Queue contents:", " -> ".join(map(str, queue)) + " ->
NULL")
else:
print("Queue is empty")
elif choice == 4:
break
else:
print("Invalid choice")
Output:
1. Enqueue
2. Dequeue
3. Display Queue
4. Exit
Enter your choice: 1
Enter value to enqueue: 10
10 enqueued to queue
Enter your choice: 1
Enter value to enqueue: 20
20 enqueued to queue
Enter your choice: 1
Enter value to enqueue: 30
30 enqueued to queue
Enter your choice: 3
Queue contents: 10 -> 20 -> 30 -> NULL
Enter your choice: 2
Dequeued: 10
Enter your choice: 4
Program No:11
Selection sort:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
if __name__ == "__main__":
n = int(input("Enter the number of elements: "))
arr = [int(input("Enter element: ")) for _ in range(n)]
print("Original array:", arr)
selection_sort(arr)
print("Sorted array:", arr)
Output:
Enter the number of elements: 5
Enter element: 64
Enter element: 25
Enter element: 12
Enter element: 22
Enter element: 11
Original array: [64, 25, 12, 22, 11]
Sorted array: [11, 12, 22, 25, 64]
Merge sort:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
i=j=k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
arr = list(map(int, input("Enter elements separated by space:
").split()))
merge_sort(arr)
print("Sorted array:", arr)
Output:
Enter elements separated by space: 23 45 67 14 47
Sorted array: [14, 23, 45, 47, 67]
Program No:12
Double linked list:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def forward_traverse(head):
curr = head
while curr:
print(curr.data, end=" ")
curr = curr.next
print()
def backward_traverse(tail):
curr = tail
while curr:
print(curr.data, end=" ")
curr = curr.prev
print()
# Main program
head = Node(1)
second = Node(2)
third = Node(3)
# Linking nodes
head.next, second.prev = second, head
second.next, third.prev = third, second
print("Backward Traversal:")
backward_traverse(third)
Output:
Forward Traversal:
123
Backward Traversal:
321
Program No:13
Binary Tree Traversal:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def in_order_traversal(root):
if root:
in_order_traversal(root.left)
print(root.val, end=' ')
in_order_traversal(root.right)
def pre_order_traversal(root):
if root:
print(root.val, end=' ')
pre_order_traversal(root.left)
pre_order_traversal(root.right)
def post_order_traversal(root):
if root:
post_order_traversal(root.left)
post_order_traversal(root.right)
print(root.val, end=' ')
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("In-order Traversal:")
in_order_traversal(root)
print("\nPre-order Traversal:")
pre_order_traversal(root)
print("\nPost-order Traversal:")
post_order_traversal(root)
Output:
In-order Traversal:
42513
Pre-order Traversal:
12453
Post-order Traversal:
45231
Program No:14
Binary search Tree:
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
class BinarySearchTree:
def __init__(self):
self.root = None
def inorder(self):
return self._inorder_rec(self.root)
# Example usage:
if __name__ == "__main__":
bst = BinarySearchTree()
bst.insert(50)
bst.insert(30)
bst.insert(70)
bst.insert(20)
bst.insert(40)
bst.insert(60)
bst.insert(80)