0% found this document useful (0 votes)
3 views66 pages

Algorithm and Python Lab

The document outlines various programming exercises conducted at SRI Aravindar Arts and Science College, including implementations of the Tower of Hanoi, Binary Search Tree, Stack using Linked List, Circular Queue, and Quick Sort in C++. Each exercise includes a clear aim, procedure, source code, and confirmation of successful execution. The document serves as a practical guide for students in the PG Department of Computer Science to understand and implement these data structures and algorithms in C++.
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)
3 views66 pages

Algorithm and Python Lab

The document outlines various programming exercises conducted at SRI Aravindar Arts and Science College, including implementations of the Tower of Hanoi, Binary Search Tree, Stack using Linked List, Circular Queue, and Quick Sort in C++. Each exercise includes a clear aim, procedure, source code, and confirmation of successful execution. The document serves as a practical guide for students in the PG Department of Computer Science to understand and implement these data structures and algorithms in C++.
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

SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 1 TOWER OF HANOI USING RECURSION

AIM : To write a program for Tower of hanoi in C++.

PROCEDURE :

1. Start the Program.


2. The tower Of Hanoi function is a recursive function that prints the steps to move n disks
from the source peg to the destination peg using the auxiliary peg.
3. In the main function, the user is prompted to input the number of disks.
4. The tower Of Hanoi function is then called with the number of disks and the names of the
source, auxiliary, and destination pegs.
5. Finally, the program waits for a key press before clearing the screen and exiting.
6. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
if (n == 1) {
cout << "Move disk 1 from " << source << " to " << destination << "\n";
return;
}

towerOfHanoi(n - 1, source, destination, auxiliary);


cout << "Move disk " << n << " from " << source << " to " << destination << "\n";
towerOfHanoi(n - 1, auxiliary, source, destination);
}

void main() {
int numDisks;
clrscr();
cout << "Enter the number of disks: ";
cin >> numDisks;

// Towers are named as 'A', 'B', and 'C'


towerOfHanoi(numDisks, 'A', 'B', 'C');

cout << "\nPress any key to exit...";


getch(); // Wait for a key press to exit

clrscr(); // Clear the screen before exiting


}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 2 BINARY SEARCH TREE USING TRAVERSAL

AIM : To write a program for binary search tree using traversal in c++.

PROCEDURE :

1. Start the Program.


2. TreeNode Structure (struct TreeNode): Represents a node in the binary tree.
3. BinaryTree Class (class BinaryTree): Represents a Binary Search Tree (BST) with insertion
and traversal methods.
4. Insertion (void insert(int val)): Public method to insert a value into the BST using a private
recursive helper function.
5. Traversals (void inorderTraversal(), void preorderTraversal(), void postorderTraversal()):
Public methods to initiate and display inorder, preorder, and postorder traversals,
respectively, using private recursive helper functions.
6. InsertRecursive (TreeNode* insertRecursive(TreeNode* node, int val)): Private helper
function for recursive insertion.
Main Function (int main()):
Creates a BinaryTree object (bst).
Inserts elements into the BST.
Performs and displays inorder, preorder, and postorder traversals.
Waits for a key press before exiting.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include<iostream.h>
#include<conio.h>

struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;

TreeNode(int val) : data(val), left(NULL), right(NULL) {}


};
class BinaryTree {
private:
TreeNode* root;

void inorderTraversal(TreeNode* node) {


if (node == NULL)
return;

inorderTraversal(node->left);
cout << node->data << " ";
inorderTraversal(node->right);
}

void preorderTraversal(TreeNode* node) {


if (node == NULL)
return;

cout << node->data << " ";


preorderTraversal(node->left);
preorderTraversal(node->right);
}

void postorderTraversal(TreeNode* node) {


if (node == NULL)
return;

postorderTraversal(node->left);
postorderTraversal(node->right);
cout << node->data << " ";
}public:
BinaryTree() : root(NULL) {}
void insert(int val) {
root = insertRecursive(root, val);
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

TreeNode* insertRecursive(TreeNode* node, int val) {


if (node == NULL)
return new TreeNode(val);

if (val < node->data)


node->left = insertRecursive(node->left, val);
else if (val > node->data)
node->right = insertRecursive(node->right, val);

return node;
}

void inorderTraversal() {
cout << "Inorder Traversal: ";
inorderTraversal(root);
cout << "\n";
}

void preorderTraversal() {
cout << "Preorder Traversal: ";
preorderTraversal(root);
cout << "\n";
} void postorderTraversal() {
cout << "Postorder Traversal: ";
postorderTraversal(root);
cout << "\n";
}};
int main() {
BinaryTree bst;
// Insert elements into the binary search tree
[Link](5);
[Link](3);
[Link](8);
[Link](1);
[Link](4);
[Link](7);
[Link](9);

// Perform traversals
[Link]();
[Link]();
[Link]();
getch(); // Wait for a key press before exiting
return 0;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 3 OPERATIONS ON STACK USING LINKED LIST

AIM : To write a program operations on stack using linked list in c++.

PROCEDURE :

1. Start the Program.


2. Node Structure (struct Node): Represents a node in the linked list, with an integer data field
and a pointer to the next node.
3. Stack Class (class Stack): Implements the stack data structure using a linked list. It includes
functions for pushing, popping, and displaying stack contents.
4. Push (`void push(int val)'): Adds a new node with the given value to the top of the stack.
5. Pop (`void pop()'): Removes the top node from the stack.
6. Display (void display()): Displays the current contents of the stack.
7. Display Stack Contents (void displayStackContents(Node* current)): Helper function to
recursively display the contents of the stack.
8. Main Function (int main()): Implements a simple user interface for interacting with the
stack operations. The user can push, pop, display the stack, or exit the program.
9. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include<iostream.h>
#include<conio.h>

struct Node {
int data;
Node* next;
Node(int val) : data(val), next(NULL) {}
};
class Stack {
private:
Node* top;
public:
Stack() : top(NULL) {}
void push(int val) {
Node* newNode = new Node(val);
if (top == NULL) {
top = newNode;
} else {
newNode->next = top;
top = newNode;
} cout << "Pushed " << val << " onto the stack.\n";
}
void pop() {
if (top == NULL) {
cout << "Stack is empty. Cannot pop.\n";
return;
}
Node* temp = top;
top = top->next;
cout << "Popped " << temp->data << " from the stack.\n";
delete temp;
}

void display();

void displayStackContents(Node* current);


};

void Stack::displayStackContents(Node* current) {


if (current != NULL) {
displayStackContents(current->next);
cout << current->data << " ";
}
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

void Stack::display() {
if (top == NULL) {
cout << "Stack is empty.\n";
return;
}
cout << "Stack contents:\n";
displayStackContents(top);
cout << "\n";
}
int main() {
Stack stack;
int choice, value;
cout << "Stack Operations:\n";
do {
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter value to push: ";
cin >> value;
[Link](value);
break;
case 2:
[Link]();
break;

case 3:
[Link]();
break;

case 4:
cout << "Exiting the program.\n";
break;

default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 4);

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE
getch(); // Wait for a key press before exiting
return 0;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 4 OPERATIONS IN CIRCULAR QUEUE

AIM : To write a program for operations in circular queue in c++.

PROCEDURE :

1. Start the Program.


2. Circular Queue Logic: The circular queue implementation ensures that the front and rear
pointers wrap around when reaching the end of the array.
3. Enqueue (void enqueue(int value)): Adds a new element to the circular queue.
4. Dequeue (void dequeue()): Removes the front element from the circular queue.
5. Display (void display()): Displays the current contents of the circular queue.
6. Main Function (void main()): Implements a simple user interface for interacting with
circular queue operations. The user can enqueue, dequeue, display the queue, or exit the
program.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include <iostream.h>
#include <conio.h>

const int MAX_SIZE = 5;


int queue[MAX_SIZE];
int front = -1, rear = -1;

void enqueue(int value) {


if ((front == 0 && rear == MAX_SIZE - 1) || (rear == (front - 1) % (MAX_SIZE - 1))) {
cout << "Queue is full. Cannot enqueue.\n";
return;
}
if (front == -1)
front = rear = 0;
else if (rear == MAX_SIZE - 1)
rear = 0;
else
rear++;

queue[rear] = value;
cout << "Enqueued " << value << " into the queue.\n";
}
void dequeue() {
if (front == -1) {
cout << "Queue is empty. Cannot dequeue.\n";
return;
}
cout << "Dequeued " << queue[front] << " from the queue.\n";

if (front == rear)
front = rear = -1;
else if (front == MAX_SIZE - 1)
front = 0;
else
front++;
}
void display() {
if (front == -1) {
cout << "Queue is empty.\n";
return;
} int i = front;
cout << "Queue contents:\n";
do {
cout << queue[i] << " ";
i = (i + 1) % MAX_SIZE;
PG DEPARTMENT OF COMPUTER SCIENCE
SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

} while (i != (rear + 1) % MAX_SIZE);


cout << "\n";
}

void main() {
int choice, value;

clrscr(); // Clear the screen

cout << "Circular Queue Operations:\n";

do {
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Display\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter value to enqueue: ";
cin >> value;
enqueue(value);
break;

case 2:
dequeue();
break;

case 3:
display();
break;

case 4:
cout << "Exiting the program.\n";
break;

default:
cout << "Invalid choice. Please try again.\n";
}

} while (choice != 4);

getch(); // Wait for a key press before exiting


}
PG DEPARTMENT OF COMPUTER SCIENCE
SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 5 SORTING USING QUICK SORT

AIM : To write a program for sorting using quick sort in c++.

PROCEDURE :

1. Start the Program.


2. Swap (void swap(int& a, int& b)): A simple function to swap two elements by reference.
3. Partition (int partition(int arr[], int low, int high)): This function chooses a pivot element (in
this case, the last element of the array) and rearranges the array elements such that elements
smaller than the pivot are on the left, and elements greater than the pivot are on the right.
The function returns the index of the pivot after partitioning.
4. Quick Sort (void quickSort(int arr[], int low, int high)): This recursive function implements
the Quick Sort algorithm. It calls the partition function to find the pivot index and then
recursively applies Quick Sort to the sub-arrays on the left and right of the pivot.
5. Display Array (void displayArray(int arr[], int size)): A function to display the contents of
an array.
6. Main Function (int main()):
Initializes an array.
Displays the array before sorting.
Calls the quickSort function to sort the array.
Displays the array after sorting.
Waits for a key press before exiting.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include <iostream.h>
#include <conio.h>
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
} }
swap(arr[i + 1], arr[high]);
return i + 1;
}void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}}
void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
clrscr();
int arr[] = {7, 2, 1, 6, 8, 5, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Array before sorting:\n";


displayArray(arr, n);

quickSort(arr, 0, n - 1);

cout << "Array after sorting using Quick Sort:\n";


displayArray(arr, n);

getch(); // Wait for a key press before exiting


return 0; }

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 6 SORTING USING HEAP SORT

AIM : To write a program for heap sort in c++.

PROCEDURE :

1. Start the Program.


2. Swap (void swap(int& a, int& b)): A simple function to swap two elements by reference.
3. Heapify (void heapify(int arr[], int n, int i)): This function is used to build and maintain the
max heap property. It compares the root with its left and right children, swapping with the
largest if necessary, and recursively calls heapify on the affected sub-tree.
4. Heap Sort (void heapSort(int arr[], int n)): The main sorting algorithm. It first builds a max
heap, then repeatedly extracts the maximum element (the root) and reconstructs the heap
until the entire array is sorted.
5. Display Array (void displayArray(int arr[], int size)): A function to display the contents of
an array.
6. Main Function (int main()):
Initializes an array.
Displays the array before sorting.
Calls the heapSort function to sort the array.
Displays the array after sorting.
Waits for a key press before exiting.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include <iostream.h>
#include <conio.h>

void swap(int& a, int& b) {


int temp = a;
a = b;
b = temp;
}

void heapify(int arr[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (i = n - 1; i > 0; i--) {


swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

void displayArray(int arr[], int size) {


for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

int main() {
clrscr();

int arr[] = {12, 11, 13, 5, 6, 7};


int n = sizeof(arr) / sizeof(arr[0]);

cout << "Array before sorting:\n";


displayArray(arr, n);

heapSort(arr, n);

cout << "Array after sorting using Heap Sort:\n";


displayArray(arr, n);

getch(); // Wait for a key press before exiting


return 0;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 7 KNAPSACK PROBLEM USING


GREEDY METHOD

AIM : To write a program for knapsack problem using greedy method in c++.

PROCEDURE :

1. Start the Program.


2. Item Structure (struct Item): Represents an item with its value and weight.
3. Fractional Knapsack (double fractionalKnapsack(int W, Item arr[], int n)): This function
sorts the items based on their value per unit weight and then selects items greedily until the
knapsack is full. If an item cannot be fully included, a fraction of it is taken.
4. Main Function (int main()):
Initializes the capacity of the knapsack (W).
Creates an array of items (arr) with their values and weights.
Calls the fractionalKnapsack function to find the maximum value.
Displays the maximum value that can be obtained in the knapsack.
5. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include <iostream.h>
#include <conio.h>

struct Item {
int value;
int weight;
};

double fractionalKnapsack(int W, Item arr[], int n) {


// Sort items by value per unit weight (value/weight)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
double ratio1 = (double)arr[i].value / arr[i].weight;
double ratio2 = (double)arr[j].value / arr[j].weight;

if (ratio1 < ratio2) {


Item temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

int curWeight = 0; // Current weight in knapsack


double finalValue = 0.0; // Resultant value

for (i = 0; i < n; i++) {


if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalValue += arr[i].value;
} else {
int remainingWeight = W - curWeight;
finalValue += arr[i].value * ((double)remainingWeight / arr[i].weight);
break;
}
}

return finalValue;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

int main()
{

clrscr();

int W = 50; // Capacity of knapsack


Item arr[] = {{60, 10}, {100, 20}, {120, 30}}; // {value, weight}
int n = sizeof(arr) / sizeof(arr[0]);

double maxValue = fractionalKnapsack(W, arr, n);

cout << "Maximum value we can obtain = " << maxValue << endl;

getch(); // Wait for a key press before exiting


return 0;

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 8 SEARCH USING DIVIDE AND CONQUER

AIM : To write a program for search elements using divide and conquer in c++.

PROCEDURE :

1. Start the Program.


2. TreeNode Structure (struct TreeNode): Represents a node in the binary search tree.
3. CreateNode (TreeNode* createNode(int data)): Allocates memory for a new node and
initializes its data.
4. Insert (TreeNode* insert(TreeNode* root, int data)): Inserts a new node with the given data
into the binary search tree.
5. DisplaySearchResult (void displaySearchResult(TreeNode* root, int data)): Searches for a
specific element in the binary search tree and displays whether it is present or not.
6. Main Function (int main()):
Initializes an empty BST (root).
Inserts a set of keys into the BST.
Specifies an element to search (elementToSearch).
Calls the displaySearchResult function to display whether the element is present in
the BST.
Waits for a key press before [Link] the Components and Format the
Components and run the program.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include <iostream.h>
#include <conio.h>

struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
};

TreeNode* createNode(int data) {


TreeNode* newNode = new TreeNode;
if (!newNode) {
cout << "Memory error\n";
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

TreeNode* insert(TreeNode* root, int data) {


if (root == NULL)
return createNode(data);

if (data < root->data)


root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);

return root;
}

void displaySearchResult(TreeNode* root, int data) {


if (root == NULL) {
cout << "Element " << data << " is not present in the tree.\n";
return;
}

if (root->data == data) {
cout << "Element " << data << " is present in the tree.\n";
return;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

if (data < root->data)


displaySearchResult(root->left, data);
else
displaySearchResult(root->right, data);
}

int main() {
clrscr();

TreeNode* root = NULL;


int keys[] = {20, 8, 22, 4, 12, 10, 14};

for (int i = 0; i < 7; i++)


root = insert(root, keys[i]);

int elementToSearch = 10;

displaySearchResult(root, elementToSearch);

getch(); // Wait for a key press before exiting


return 0;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 9 EIGHT QUEEN PROBLEM

AIM : To write a program for Eight queen problem in c++.

PROCEDURE :

1. Start the Program.


2. isSafe Function (int isSafe(int row, int col)): Checks if placing a queen at a specific position
(row, col) is safe, considering the current state of the board.
3. solveNQueens Function (int solveNQueens(int col)): Recursively tries to place queens in
each column. If a safe position is found, it continues to the next column. If no safe position
is found, it backtracks to the previous column.
4. displayBoard Function (void displayBoard()): Displays the solution board.
5. Main Function (int main()):
Initializes an 8x8 chessboard.
Calls solveNQueens to attempt to solve the N-Queens problem.
Displays the solution if one exists, otherwise, prints a message indicating no solution
Align the Components and Format the Components and run the program.
6. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

#include <iostream.h>
#include <conio.h>

const int N = 8;
int board[N][N] = {0};

int isSafe(int row, int col) {


int i, j;

for (i = 0; i < col; i++)


if (board[row][i])
return 0;

for (i = row, j = col; i >= 0 && j >= 0; i--, j--)


if (board[i][j])
return 0;

for (i = row, j = col; j >= 0 && i < N; i++, j--)


if (board[i][j])
return 0;

return 1;
}

int solveNQueens(int col) {


if (col >= N)
return 1;

for (int i = 0; i < N; i++) {


if (isSafe(i, col)) {
board[i][col] = 1;

if (solveNQueens(col + 1))
return 1;

board[i][col] = 0; // backtrack
}
}

return 0;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

void displayBoard() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << board[i][j] << " ";
cout << endl;
}
}

int main() {
clrscr();

if (solveNQueens(0))
displayBoard();
else
cout << "No solution exists.";

getch(); // Wait for a key press before exiting


return 0;
}

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 01 PROGRAMS USING ELEMENTARY DATA ITEMS, LISTS ,


DICTIONARIES ,TUPLES.

AIM :

To write a program to implement the data items, lists , dictionaries, tuples in python.

PROCEDURE :

1. Start the program

2. Lists (l): Lists are mutable sequences. You can add elements to the end using append()
and remove elements using pop().

3. Set (s): Sets are unordered collections of unique elements. You can add elements using add()
and remove elements using remove().

4. Tuple (t): Tuples are immutable sequences. In your code, you're creating a tuple from the list.

5. Dictionary (d): Dictionaries are unordered collections of key-value pairs. You can add
entries using square brackets (d[key] = value) and remove entries using del.

6. Stop the program

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

# Python 3 program for explaining


# use of List, Tuple, Set, and Dictionary
# ----- List -----
l = [] # creating empty list
# adding elements into list
[Link](5)
[Link](10)
print("Adding 5 and 10 in list:", l)
# popping element from list
[Link]()
print("Popped one element from list:", l)
print()
# ----- Set -----
s = set() # creating empty set
# adding elements into set
[Link](5)
[Link](10)
print("Adding 5 and 10 in set:", s)
# removing element from set
[Link](5)
print("Removing 5 from set:", s)
print()
# ----- Tuple -----
t = tuple(l) # creating tuple from list
print("Tuple created from list:", t)
print()
# ----- Dictionary -----
d = {} # creating empty dictionary
# adding key-value pairs
d[5] = "five"
d[10] = "ten"
print("Dictionary after adding elements:", d)
# removing key-value pair
del d[10]
print("Dictionary after deletion:", d)

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT:

RESULT : Thus the program was successfully executed and the output was verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 02 CONDITIONAL BRANCHES

AIM :

To write a program for implement the conditional branch statement in python.

PROCEDURE :
1. Start the Program.
2. Let initialize the variable in ‘ x’.
3. Check the loop condition statement.
4. Compare the string of vowels ‘aeiou’.
5. If the loop will continue to iterate each character in string until all character have been
processed
6. After the loop finishes , the program will exits.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

# Python program to check vowels using conditional branches

x = "helloadios"

for q in x:
if q in 'aeiou':
print(q, "is a vowel")
else:
print(q, "is not a vowel")

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT:

RESULT:

Thus the program is successfully executed and the output was verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 03 IMPLEMENTING LOOPS

AIM :

To write a program to implementing the concept of Loops using python.

PROCEDURE :
1. Start the Program.
2. Let initialize sum = 0.
3. Declaring numbers with some values and increment it.
4. Calculate sum = sum + num ** 2
5. Calculate the square of numbers.
6. Finally display the sum variable.

7. Intializing the value for I variable as 1.

8. Increments till the ith value reaches 10.

9. Display the ‘I’ value.


10. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

For Loop :

# Program to find the sum of squares of each element in a list using for loop
# creating the list of numbers
print("For Loop :")
numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
# initializing sum
sum_ = 0
# using for loop to iterate over the list
for num in numbers:
sum_ = sum_ + num ** 2
print("The sum of squares is:", sum_,"\n")

While Loop :

# Program to print numbers from 1 to 10 using while loop


print("While Loop :")
i=1
while i <= 10:
print(i)
i += 1
else:
print("Loop ended, i =", i)

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT :

Thus the program for implementing loops is successfully executed and output is
verified

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 04 PROGRAMS USING FUNCTIONS

AIM :

To write a program to implementing the concept of functions in python

PROCEDURE:
1. Start the Program.
2. Defining the functions add numbers
3. Let add the function call with two values.
4. Adding the two numbers and save it in ‘sum’ variable.
5. Print the value sum
6. Stop the program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

# Program to demonstrate functions in Python

def add_numbers(num1, num2):


sum_ = num1 + num2
print("The sum is:", sum_)

# function call
add_numbers(4, 25)

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT:

RESULT :
Thus the program for function is successfully executed and output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

EX NO :05 PROGRAM USING EXCEPTION HANDLING

AIM :

To write a program for implement the exception handling in python

PROCEDURE :

1. Start the Program.


2. Under the trader by try get the value for numerator,denominator and result .
3. Print the result value.
4. Execute the except function.
5. Print the error occurred.
6. Stop the Program

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

# Program to demonstrate exception handling in Python

try:
numerator = 10
denominator = 0
result = numerator / denominator
print(result)

except ZeroDivisionError:
print("Error: Denominator cannot be 0.")

finally:
print("This is the finally block.")

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT:

RESULT :

Thus the above program was successfully executed and the output was verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 06 PROGRAMS USING INHERITANCE

AIM :

To write a program to implementing the concept of inheritance in python

PROCEDURE :

1. Start the Program.


2. Call the function vehicle_info.
3. In called function vehicle_info it will print the message ‘Inside the vehicle class”.
4. Call the function car_info.
5. In called function car_info it will print the message.
6. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

# Program to demonstrate inheritance in Python

# Base class
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")

# Child class
class Car(Vehicle):
def car_info(self):
print("Inside Car class")

# Create object of Car


car = Car()

# Access methods
car.vehicle_info() # inherited from Vehicle
car.car_info() # defined in Car

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT :
Thus the program was successfully executed and the output was verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 07 PROGRAMS USING POLYMORPHISM

AIM :

To write a program for implementing t he concept of polymorphism in python

PROCEDURE :
1. Start the Program.
2. Defining the function self, a,b=0.
3. Assign (b>0)
4. If the condition is true,if statement will be executed.
5. Otherwise ,else statement will be executed.
6. Print the result
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

# Program to demonstrate polymorphism in Python

class Shape:
# function with two default parameters
def area(self, a, b=0):
if b > 0:
print("Area of Rectangle is:", a * b)
else:
print("Area of Square is:", a ** 2)

# Create objects and call methods


square = Shape()
[Link](5) # Square case

rectangle = Shape()
[Link](5, 3) # Rectangle case

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT:

Thus the program is successfully executed and the output was verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 08 PROGRAMS TO IMPLEMENT FILE OPERATIONS

AIM :

To write a program to implement file operations in python.

PROCEDURE :

1. Start the Program.


2. Let open the text file by calling the open()function .
3. Read all the lines from the text file and store them in a list by calling the ‘readline()’.
4. Iterate over each line in the ‘line_list’ using a for loop.
5. Print each line.
6. After close the file by calling the ‘close()’method on ‘text_file’
7. Stop the program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

# Program to demonstrate file operations in Python

# open the file in write mode and add content


with open("[Link]", "w") as f:
[Link]("Hello Python\n")
[Link]("File Handling Example\n")
[Link]("End of File\n")

# open the file in read mode


text_file = open("[Link]", "r")

# get the list of lines


line_list = text_file.readlines()

# print each line


for line in line_list:
print([Link]()) # strip() removes extra newline characters

# close the file


text_file.close()

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT :
Thus the program is successfully executed and the output was verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 09 PROGRAMS USING MODULES

AIM :
To write a program to implement the modules in python.

PROCEDURE :

1. Start the Program.


2. Defining two functions add and subtract the values.
3. Let the function take two parameters x and y and return the values..
4. Save the [Link] file.
5. And the line ‘import calc at the beginning of your code to import the ‘calc’ module..
6. Print the final value.
7. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE :

Module File: [Link]

# [Link] - user-defined module


def add(x, y):
return x + y
def subtract(x, y):
return x - y

Main Program: [Link]

# [Link] - program to use the calc module


import calc
print("Addition:", [Link](10, 2))
print("Subtraction:", [Link](10, 2))

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

Ex No : 10 DYNAMIC AND INTERACTIVE WEBPAGES

AIM :

To write a program for dynamic and interactive webpages in python.

PROCEDURE :

1. Start the Program.


2. Markdown and Text Output: Displays a markdown header and a text message.
3. Table Output: Displays a table with food items and prices.
4. Popup: Opens a popup for subscribing to the page.
5. User Input: Allows the user to choose their favorite food using the select function.
6. Process Bar: Displays a process bar to simulate the food preparation progress.
7. Image Output: Shows an image based on the selected food.
8. File Output: Provides a file for the user to download.
9. Stop the Program.

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

SOURCE CODE:

from [Link] import *


from [Link] import *
import time

# Greeting and menu


put_markdown('## Hello there')
put_text("I hope you are having a great day! Here is our menu")
put_table([
['Food', 'Price'],
['Noodle', 10],
['Chicken and rice', 11]
])

# Popup for subscription


with popup("Subscribe to the page"):
put_text("Join other foodies!")

# Ask user for their food choice


food = select("Choose your favorite food", ['Noodle', 'Chicken and rice'])

put_text(f"You chose {food}. Please wait until it is served!")

# Show progress bar


put_processbar('bar')
for i in range(1, 11):
set_processbar('bar', i / 10)
[Link](0.1)

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

put_markdown("### Here is your food! Enjoy!")

# Show appropriate image based on food choice


try:
if food == 'Noodle':
put_image(open('[Link]', 'rb').read())
else:
put_image(open('chicken_and_rice.webp', 'rb').read())
except FileNotFoundError:
put_text("Image not found. Please check the image file path.")

# Dummy file download link (replace with real content if needed)


put_file("Download [Link]", b"Thank you for your order!", '[Link]')

PG DEPARTMENT OF COMPUTER SCIENCE


SRI ARAVINDAR ARTS AND SCIENCE COLLEGE

OUTPUT :

RESULT : Thus the program is successfully executed and the output is verified.

PG DEPARTMENT OF COMPUTER SCIENCE

You might also like