0% found this document useful (0 votes)
11 views62 pages

Ds Lab Final2

The document contains a series of programming exercises focused on array manipulation, searching algorithms, sorting techniques, and basic data structures in C and C++. It includes implementations for summing array elements, linear and binary search, sorting algorithms (selection, bubble, and insertion sort), matrix multiplication, and calculating factorials and Fibonacci numbers using recursion. Additionally, it covers the use of pointers and structures to manage student data and perform various operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views62 pages

Ds Lab Final2

The document contains a series of programming exercises focused on array manipulation, searching algorithms, sorting techniques, and basic data structures in C and C++. It includes implementations for summing array elements, linear and binary search, sorting algorithms (selection, bubble, and insertion sort), matrix multiplication, and calculating factorials and Fibonacci numbers using recursion. Additionally, it covers the use of pointers and structures to manage student data and perform various operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

DS LAB FINAL

LAB Day- 1
Q-3 Sum of numbers using array:
#include <stdio.h>
int main()
{
int i, n, sum = 0;
int sumEven = 0, sumOdd = 0;

printf("Number of elements in the array:\n");


scanf("%d", &n);

int arr[n];

printf("Enter elements in the array:\n");


for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

printf("Elements of given array:\n");


for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
for(i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of given array: %d\n", sum);

// sum of even and odd

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


if(arr[i] % 2 == 0) {
sumEven += arr[i];
} else {
sumOdd += arr[i];
}
}
printf("Sum of all even numbers in the array: %d\n", sumEven);
printf("Sum of all odd numbers in the array: %d\n", sumOdd);

return 0;
}
LAB Day- 2
Given an element k. Find if the k is present in the array, if YES, find its position,
otherwise -1. Linear Search
#include <stdio.h>

int main(){

int i, n, k;

printf("Number of elements in the array :\n");


scanf("%d", &n);
int arr[n] ;
printf("Enter Elements of given array: \n");
for( i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
printf("Elements of given array: \n");
for ( i = 0; i <n; i++) {
printf("%d ", arr[i]);
}
printf("Enter any value of k: \n");
scanf("%d",&k);

int Flag = 0;
for (i= 0; i< n; i++){
if (arr[i] == k)
{
Flag= 1;
printf("%d is present in position:%d \n",k,i);
break;
}
}
if(Flag== 0){
printf("%d is not present\n",k);
}

return 0;
}
An array given. Q times Query. every time one integer will be given. If it is present
then answer will be YES. if not then NO.
#include <stdio.h>

int main(){

int i,j, n,k, q;

printf("Number of elements in the array :\n");


scanf("%d", &n);
int arr[n] ;
printf("Enter Elements of given array: \n");
for( i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
printf("Elements of given array: \n");
for ( i = 0; i <n; i++) {
printf("%d ", arr[i]);
}
printf("Enter the query times:\n");
scanf("%d" , &q);
for(j=0; j<q; j++){
printf("Enter any value of k: \n");
scanf("%d",&k);
int Flag = 0;
for (i= 0; i< n; i++){
if (arr[i] == k)
{
Flag= 1;
printf("%d is present\n",k);
break;
}
}
if(Flag== 0){
printf("%d is not present\n",k);
}

}
}
Position of minimum element of given array
#include <iostream>
#include <stack>
using namespace std;

int main() {
int position;
int arr[5]= {90,30,22,66,60};
int min_element = arr[0];

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


if(arr[i]< min_element){
min_element = arr[i];
position = i;
}
}

cout << "Position of minimum element in given array: "<< position;


return 0;
}

LAB Day- 3
Binary Search
#include<stdio.h>
int main()
{
int i,j,n,k, q;

printf("Number of elements in the array :\n");


scanf("%d", &n);
int arr[n] ;
printf("Enter Elements of given array: \n");
for( i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
printf("Elements of given array: \n");
for ( i = 0; i <n; i++)
{
printf("%d ", arr[i]);
}
int start= 0;
int end= n-1;
int mid;
printf("Enter the query times:\n");
scanf("%d", &q);
for(j=0; j<q; j++)
{
printf("Enter any value of k: \n");
scanf("%d",&k);

while(start<=end)
{
mid = (start+end)/2;
if(k== arr[mid])
{
printf("%d is present and position is %d\n",k, mid);
break;
}
if(k<arr[mid])
{
end=mid-1;
}
if(k>arr[mid])
{
start= mid+1;
}
}
if (start > end){
printf(" %d isn't present\n", k);
}
}
}

Q: Print the position of the first element of the array which is greater than k.
#include<stdio.h>
int main()
{
int arr[7]={20,30,40,50,60,70,80};
int k,i;
printf("Enter the value of K:");
scanf("%d",&k);
for(i=0;i<7;i++){
if (arr[i]>k){
printf("Position of the element:%d",i);
break;
}
}
}
LAB Day- 4
Selection Sorting:
#include<stdio.h>

// Function to swap two integers


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int i, j, n, step ;

printf("Number of elements in the array :\n");


scanf("%d", &n);
int arr[n];
printf("Enter Elements of given array: \n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Elements of given array: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
int f_pos, min_element, min_pos;

for (step = 0; step <= n - 2; step++) {


f_pos = step;
min_element = arr[f_pos];
min_pos = f_pos;
for (i = f_pos + 1; i < n; i++) {
if (arr[i] < min_element) {
min_element = arr[i];
min_pos = i;
}
}
swap(&arr[f_pos], &arr[min_pos]);
}

printf("\nSorted array: \n");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Bubble Sorting:
#include<stdio.h>
int main()
{
int i,j,n,step, temp=0;

printf("Number of elements in the array :\n");


scanf("%d", &n);
int arr[n] ;
printf("Enter Elements of given array: \n");
for( i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
printf("Elements of given array: \n");
for ( i = 0; i <n; i++)
{
printf("%d ", arr[i]);
}

for(step=1 ;step< n; step++){


for(i=0; i<=n-1- step; step++){
if(arr[i]> arr[i+1]){
temp= arr[i];
arr[i]= arr[i+1];
arr[i+1] = temp;
}
}
}

printf("Sorted array: \n");


for (int i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
LAB Day- 5
Q1. INSRTION SORT
#include<stdio.h>
int main()
{
int n, i, step, f_elm;
scanf("%d", &n);
int array[n];

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


scanf("%d", &array[i]);
}

for(step = 1; step <= n-1; step++){


f_elm = array[step];
i = step -1;

while(i >= 0 && f_elm < array[i]){


array[i+1] = array[i];
i--;
}

array[i+1] = f_elm;
}

printf("Sorted Array: ");


for(i = 0; i<n; i++){
printf("%d ", array[i]);
}
}

Q2. Multiplication of Two Matrices A(m x n) and B(n x p)


#include<stdio.h>
int main()
{
int i,j,k,m,n,o,p;
printf("Enter the Row and Column of A Matrix: ");
scanf("%d %d", &m, &n);
printf("Enter the Row and Column of B Matrix: ");
scanf("%d %d", &n, &p);

int A[m][n], B[n][p], C[m][p];


printf("Enter the elements of Array A\n");
for(i = 1; i<=m; i++){
for(j=1; j<=n; j++){
scanf("%d", &A[i][j]);
}
}

printf("Array A\n");
for(i = 1; i<=m; i++){
for(j=1; j<=n; j++){
printf("%d ", A[i][j]);
}
printf("\n");
}

printf("Enter the elements of Array B\n");


for(i = 1; i<=n; i++){
for(j=1; j<=p; j++){
scanf("%d", &B[i][j]);
}
}

printf("Array B\n");
for(i = 1; i<=n; i++){
for(j=1; j<=p; j++){
printf("%d ", B[i][j]);
}
printf("\n");
}

for(i = 1; i<=m; i++){


for(j=1; j<=p; j++){
C[i][j] = 0;
for(k=1; k<=n; k++){
C[i][j] += A[i][k]*B[k][j];
}
}
}

printf("Resultant Array C:\n");


for(i = 1; i<=m; i++){
for(j=1; j<=p; j++){
printf("%d ", C[i][j]);
}
printf("\n");
}
}

Q3. A Student has following four attributes/properties


i. Name
ii. ID
iii. CGPA
iv. Age
Now input n student's Information and calculate the average CGPA in the class.
#include <iostream>
using namespace std;
struct Student{
int ID;
double Age, CGPA;
string Name;
void input()
{
cout<<"Name, ID, Age, CGPA: ";
cin>>Name>>ID>>Age>>CGPA;
}
void give_introduction(){
cout<< "Name= " << Name << endl;
cout<< "ID= " << ID << endl;
cout<< "Age= " << Age << endl;
cout<< "CGPA= " << CGPA << endl;
}
};

int main(){
int n;
double TCGPA=0, ACGPA;
cout<<"Enter the Number of Students: ";
cin>>n;

Student s[n];

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


s[i].input();
s[i].give_introduction();
TCGPA += s[i].CGPA;
}
ACGPA = TCGPA/n;
cout<<"\nAverage CGPA: "<<ACGPA<<endl;
}
LAB Day- 6
1. Factorial of n.
Using recursion
#include<stdio.h>
int fact(int n){
if (n==1){
return 1;
}
return n * fact(n-1);
}

int main()
{
int num;
printf("Enter the number:");
scanf("%d", &num);

printf("Factorial of number %d = %d\n", num, fact(num));


return 0;
}

2. nth Fibonacci Number.


#include<iostream>
using namespace std;

int fib(int n){


if(n==0)
return 0;
if(n==1)
return 1;
return fib(n-1) + fib(n-2);
}

int main(){
int num;
cout<< "Enter the number:";
cin>> num;
int ans = fib(num);
cout<< num<<"th Fibonacci number is= "<< ans << endl;
}
Sum of N numbers using recursion
#include<iostream>
using namespace std;

int sum(int n){


if(n>0){
return n + sum(n-1);
}
else{
return 0;
}
}

int main(){
int num;
cout<< "Enter the number:";
cin>> num;
int ans = sum(num);
cout<< "Sum of first "<<num<<" number is= "<< ans << endl;
}

Take an Integer value x and assign some value to it taking user input. Now use a
level-1 pointer to point the value of x.
POINTER
#include <iostream>
using namespace std;

int main() {
int x;
cout << "Enter an integer value for x: ";
cin >> x;

int* ptr = &x;

cout << "The value of x is: " << *ptr << endl;
cout << "The address of x is: " << ptr << endl;
return 0;
}

#include<stdio.h>
int main()
{
int x = 10;
int *p, **q;

p = &x;
q = &p;

printf("%p\n", &p);
printf("%p\n", p);
printf("%d\n", *p);

*p = 20;
printf("%d\n", x);

printf("Enter a new value of x: ");


scanf("%d", &x);
printf("The new value of x is: %d\n", *p);

printf("%d\n", **q);

return 0;
}

Find the smallest and largest element in the array using pointers.
#include <stdio.h>

void min_max(int arr[], int n, int *min, int *max) {


*min = *max = arr[0];

for(int i = 1; i < n; i++) {


if (arr[i] < *min) {
*min = arr[i];
}
if (arr[i] > *max) {
*max = arr[i];
}
}
}
int main() {
int n;

printf("Number of elements in the array:\n");


scanf("%d", &n);
int arr[n];
printf("Enter elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int min, max;


min_max(arr, n, &min, &max);

printf("The smallest element is: %d\n", min);


printf("The largest element is: %d\n", max);

return 0;
}

|3. Student |
i) ID
ii) Age
iii) Name
iv) CGPA
take n students Inputs and do
- Print the students by their ID
- Print the students by their Age
- Print the students by their CGPA and Age

[Do using Bubble sort, Insertion sort, Selection sort]


#include <iostream>
using namespace std;

struct Student{
int ID;
double Age, CGPA;
string Name;

void input()
{
cout<<"Name, ID, Age, CGPA: ";
cin.ignore();
getline(cin,Name);
cin>>ID>>Age>>CGPA;
}

void print_info()
{
cout<<"Name: "<< Name<<", ID: "<< ID<<", CGPA: "<< CGPA<<", Age: "<< Age<<endl;
}

};

int main(){
int n, i, f_elm;

cout<<"Enter the Number of Students: ";


cin>>n;

Student s[n];

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


s[i].input();
}

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


s[i].print_info();
}

cout<<""<< endl;

cout<<"Printing the students by their ID using Insertion sort: "<< endl;

for (int step = 1; step < n; step++) {


Student temp = s[step];
int j = step - 1;
while (j >= 0 && s[j].ID > temp.ID) {
s[j + 1] = s[j];
j--;
}

s[j + 1] = temp;

}
for(int i = 0; i<n; i++){
s[i].print_info();
}
cout<<"\nPrinting the students by their Age using Bubble sort: "<< endl;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (s[j].Age > s[j + 1].Age) {
Student temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}

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


s[i].print_info();
}

cout<<"\nPrinting the students by their CGPA and Age using Selection sort: "<< endl;

for (int i = 0; i < n - 1; i++) {


int minIndex = i;
for(int j = i+1; j<n; j++){
if(s[j].CGPA < s[minIndex].CGPA || (s[j].CGPA == s[minIndex].CGPA && s[j].Age <
s[minIndex].Age)){
minIndex = j;
}
}

if(minIndex != i){
Student temp = s[i];
s[i] = s[minIndex];
s[minIndex] = temp;
}
}

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


s[i].print_info();
}
}

Linked list
#include<iostream>
using namespace std;

struct node{
int data;
node *next;
node(){
next= NULL;
}
};

int main(){
int n;
cout << "Number of elements" << endl;
cin >> n;
node *head, *previous_node;
head= new node;
cout << "First node element" << endl;
int x;
cin>> x;
head -> data=x;
previous_node= head;

for(int i=2; i<=n; i++){


cout << "Next node element: " << endl;
cin>> x;
node *new_node;
new_node = new node;
new_node -> data=x;
previous_node -> next= new_node;
previous_node = new_node;
}

cout << "Linked List:" << endl;


for(node* i = head; i != NULL; i = i-> next){
cout << "Data in : " << i->data << endl;
}

// sum
int sum =0;
for(node* i= head; i != NULL; i = i-> next){
sum = sum + i->data;
}

cout << "Sum of all data in the linked list: " << sum << endl;

// search

int y, flag=0 ;
cout << "Enter search element:" << endl;
cin>> y;
for(node* i= head; i != NULL; i = i-> next){
if(i-> data== y){
cout << "Number is present" << endl;
flag = 1;
}
}
if( flag== 0){
cout << "Number is not present" << endl;
}

// insert at beginning

node *new_element;
new_element = new node;
int key;
cout << "Enter the new element at beginning: " << endl;
cin>> key;
new_element-> data= key;
new_element-> next= head;
head = new_element;

cout << "New Linked List:" << endl;


for(node* i = head; i != NULL; i = i-> next){
cout << "Data in : " << i->data << endl;
}

// insert at last

node *new_element2;
new_element2 = new node;
int key2;
cout << "Enter the new element at end: " << endl;
cin>> key2;
new_element2-> data= key2;
node *i;

for(i=head; i->next!= NULL; i = i-> next){

}
i-> next= new_element2;

cout << "New Linked List:" << endl;


for(node* i = head; i != NULL; i = i-> next){
cout << "Data in : " << i->data << endl;
}

// insert at any position


node *new_element3;
new_element3 = new node;
new_element3-> data= 500;
node *i3;

for(i=head; i->next!= NULL; i = i-> next){


if(i-> data == 40){
new_element3 -> next = i3-> next;
i3-> next = new_element3;
break;
}
}

cout << "New Linked List:" << endl;


for(node* i = head; i != NULL; i = i-> next){
cout << "Data in : " << i->data << endl;
}

// delete
int position;
cout << "Position you want to delete: " << endl;
cin >> position;
if (position == 1){
node *temp;
temp =head;
head= head -> next;
delete temp;
}
else {
node *i,*pre_node, *next_node;
i= head;
for(int k=1; k<=position-1; k++){
pre_node= i;
i= i->next;
}
next_node= i->next;
delete i;
pre_node-> next =next_node;
}

cout << "New Linked List:" << endl;


for(node* i = head; i != NULL; i = i-> next){
cout << "Data in : " << i->data << endl;
}

}
Doubly Linked List
#include<iostream>
using namespace std;

// Node structure for doubly linked list


struct node {
int data;
node *next;
node *prev;
node() {
next = NULL;
prev = NULL;
}
};

int main() {
int n;
cout << "Number of elements: " << endl;
cin >> n;

node *head = NULL;


node *tail = NULL;

// Creating the doubly linked list


for(int i = 0; i < n; i++) {
cout << "Enter data for node " << i + 1 << ": ";
int x;
cin >> x;

node *new_node = new node;


new_node->data = x;
new_node->next = NULL;

if(head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
new_node->prev = tail;
tail = new_node;
}
}

// Displaying the doubly linked list forward


cout << "Linked List forward:" << endl;
for(node* i = head; i != NULL; i = i->next) {
cout << "Data in node: " << i->data << endl;
}

// Displaying the doubly linked list backward using the tail pointer
cout << "Linked List backward:" << endl;
for(node* i = tail; i != NULL; i = i->prev) {
cout << "Data in node: " << i->data << endl;
}

// Calculating the sum of all data in the linked list


int sum = 0;
for(node* i = head; i != NULL; i = i->next) {
sum += i->data;
}

cout << "Sum of all data in the linked list: " << sum << endl;

// Searching
int y, flag=0;
cout << "Enter Search element: "<< endl;
cin>> y;
for(node* i = head; i != NULL; i = i->next) {
if(i-> data==y){
cout<< "Number is present."<< endl;
flag= 1;
}
if(flag==0){
cout<< "Number is not present."<< endl;
}
}

//Insert at beginning
node *new_element;
new_element= new node;
int key;
cout<< "Enter new element at beginning:" << endl;
cin>> key;
new_element->data =key;
head->prev = new_element;
new_element-> next= head;
head= new_element;

cout<< "New linked list:"<< endl;


for(node* i = head; i != NULL; i = i->next) {
cout << "Data in node: " << i->data << endl;
}

// Insert at last index


node *new_element2;
new_element2= new node;
int key2;
cout<< "Enter new element at last:" << endl;
cin>> key2;
new_element2->data =key2;
tail->next = new_element2;
new_element2-> prev= tail;
tail= new_element2;

cout<< "New linked list:"<< endl;


for(node* i = head; i != NULL; i = i->next) {
cout << "Data in node: " << i->data << endl;
}

//Insert element at any specific position


node *new_element3;
new_element3= new node;
new_element3->data =50;
node* i;

for(i = head; i ->next!= NULL; i = i->next) {


if(i-> data== 40){
new_element3-> prev= i;
new_element3-> next= i-> next;
i->next= new_element3;
break;
}
}
cout<< "Insert element at any specific position after 40:"<< endl;
cout<< "New linked list:"<< endl;
for(node* i = head; i != NULL; i = i->next) {
cout << "Data in node: " << i->data << endl;
}

// delete
int position;
cout << "Position you want to delete: " << endl;
cin >> position;
if (position == 1){
node *temp;
temp= tail;
tail= tail->prev;
tail->next =NULL;
delete temp;
}
else {
node *i,*pre_node, *next_node;
i= head;
for(int k=1; k<=position-1; k++){
pre_node= i;
i= i->next;
}
next_node= i->next;
pre_node-> next = i->next;
next_node-> prev= i->prev;
delete i;
}

cout << "New Linked List:" << endl;


for(node* i = head; i != NULL; i = i-> next){
cout << "Data in : " << i->data << endl;
}

return 0;
}
Circular linked list
#include<iostream>
using namespace std;

struct node {
int data;
node *next;
node() {
next = NULL;
}
};

// print the circular linked list


void printCircularList(node* head) {
if (head == NULL) return;

node* current = head;


do {
cout << "Data in node: " << current->data << endl;
current = current->next;
} while(current != head);
}

int main() {
int n;
cout << "Number of elements: ";
cin >> n;

node *head = NULL;


node *previous_node = NULL;

for(int i = 1; i <= n; i++) {


cout << "Enter data for node " << i << ": ";
int x;
cin >> x;

node *new_node = new node;


new_node->data = x;

if(head == NULL) {
head = new_node;
} else {
previous_node->next = new_node;
}
previous_node = new_node;

if(i == n) {
new_node->next = head; // connecting the last node to the head
}
}

cout << "Circular Linked List:" << endl;


printCircularList(head);

// Searching in Circular Linked List


int y, flag = 0;
cout << "Enter search element:" << endl;
cin >> y;

node *current = head;


do {
if (current->data == y) {
cout << "Number is present" << endl;
flag = 1;
break;
}
current = current->next;
} while (current != head);

if (flag == 0) {
cout << "Number is not present" << endl;
}
// Insertion
// Insert a new element at the beginning
int key;
cout << "Enter the new element at beginning: " << endl;
cin >> key;

node *new_element = new node;


new_element->data = key;
new_element->next = head;
previous_node->next = new_element;
head = new_element;

cout << "New Circular Linked List:" << endl;


printCircularList(head);

// Insert a new element at any specified middle position


int pos, key2;
cout << "Enter the position to insert: " << endl;
cin >> pos;
cout << "Enter the new element to insert: " << endl;
cin >> key2;

node *new_element2 = new node;


new_element2->data = key2;

current = head;
for (int i = 1; i < pos - 1; i++) {
current = current->next;
}
new_element2->next = current->next;
current->next = new_element2;

cout << "New Circular Linked List:" << endl;


printCircularList(head);

// Insert new element at the last position


int key3;
cout << "Enter the new element to insert at the last position: " << endl;
cin >> key3;

node *new_element3 = new node;


new_element3->data = key3;

new_element3->next = head;
previous_node->next = new_element3;
cout << "New Circular Linked List:" << endl;
printCircularList(head);

// Deletion
// Delete a node at a given position
int position;
cout << "Position you want to delete: ";
cin >> position;

if (position == 1) {
// Delete the first node
node *temp = head;
while(temp->next != head) {
temp = temp->next;
}
temp->next = head->next;
delete head;
head = temp->next;
} else {
// Delete any position other than the head
node *current = head;
node *previous = NULL;
for(int i = 1; i < position; i++) {
previous = current;
current = current->next;
}
previous->next = current->next;
delete current;
}

cout << "New Circular Linked List:" << endl;


printCircularList(head);

return 0;
}

LAB Day- 7
Calculate power a^b using Recursion
#include <iostream>
using namespace std;
long long int power(int base, int p) {
if (p == 0)
return 1;
return base * power(base, p- 1);
}

int main() {
int base, p;
cout << "Enter base: ";
cin >> base;
cout << "Enter power: ";
cin >> p;

cout << base << " power " << p << ": " << power(base, p) << endl;

return 0;
}

Prime Number using Recursion


#include<iostream>
using namespace std;

int checkPrime(int i, int n){


if(i == n){
return 0;
}
else if(n%i == 0){
return 1;
}
else{
return checkPrime(i+1, n);
}
}

int main(){
int num;
cout<< "Enter the number:";
cin>> num;
if (checkPrime(2,num) == 0){
cout<< "It is a prime number " << endl;
}
else{
cout<< "It is not a prime number " << endl;
}
}

Palindrome Number Check


#include <iostream>
using namespace std;

int main() {
int n, result=0,q, rem ;
cout << "Enter a number: ";
cin >> n;
q=n;

while (q> 0) {
rem = q % 10;
result = result * 10 + rem;
q = q/10;
}
if (result == n)
cout << n << " is a palindrome." << endl;
else
cout << n << " is not a palindrome." << endl;

return 0;
}

Reverse a Number
#include <iostream>
using namespace std;

int main() {
int n, result=0,q, rem ;
cout << "Enter a number: ";
cin >> n;
q=n;

while (q> 0) {
rem = q % 10;
result = result * 10 + rem;
q = q/10;
}
cout << result<< " is reversed." << endl;
return 0;
}
LAB Day- 8
Student using linked list to print avg cgpa and add a new student
#include<iostream>
using namespace std;

struct Student {
string Name;
int ID;
double cgpa, age;
Student* next;

Student(string name, int id, double cgpa, double age) {


Name = name;
ID = id;
this->cgpa = cgpa;
this->age = age;
next = NULL;
}

void print_info() {
cout << "Name: " << Name << ", ID: " << ID << ", CGPA: " << cgpa << ", Age: " << age << endl;
}
};

int main() {
int n;
cout << "Enter the number of students: ";
cin >> n;

Student* head = NULL;


Student* previous_node = NULL;

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


cout << "\nEnter details of student " << i + 1 << ":\n";
string name;
int id;
double cgpa, age;

cout << "Name: ";


cin.ignore();
getline(cin, name);
cout << "ID: ";
cin >> id;
cout << "Age: ";
cin >> age;
cout << "CGPA: ";
cin >> cgpa;

Student* s = new Student(name, id, cgpa, age);

if (head == NULL) {
head = s;
previous_node = s;
} else {
previous_node->next = s;
previous_node = s;
}
}

double total_cgpa = 0;
Student* current = head;
while (current != NULL) {
total_cgpa += current->cgpa;
current = current->next;
}
double average_cgpa = total_cgpa / n;

cout << "\nAverage CGPA : " << average_cgpa << endl;

string newName;
int newID;
double newcgpa, newage;
cout << "\nNew Student Information : " << endl;
cout << "Name: ";
cin.ignore();
getline(cin, newName);
cout << "ID: ";
cin >> newID;
cout << "Age: ";
cin >> newage;
cout << "CGPA: ";
cin >> newcgpa;
Student* newStudent = new Student(newName, newID, newcgpa, newage);
newStudent->next = head;
head = newStudent;

cout << "\nUpdated student information:" << endl;


current = head;
while (current != NULL) {
current->print_info(); /
current = current->next;
}

return 0;
}

Student Using Linked list to print the n number of student average cgpa
#include<iostream>
using namespace std;

struct Student {
string Name;
int ID;
double cgpa, age;
Student* next;
};

int main() {
int n;
cout << "Enter the number of students: ";
cin >> n;

Student* head = nullptr;


Student* previous_node = nullptr;

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


cout << "\nEnter details of student " << i + 1 << ":\n";
Student* s = new Student;
cout << "Name: ";
cin.ignore();
getline(cin, s->Name);
cout << "ID: ";
cin >> s->ID;
cout << "Age: ";
cin >> s->age;
cout << "CGPA: ";
cin >> s->cgpa;
s->next = nullptr;

if (head == nullptr) {
head = s;
previous_node = s;
} else {
previous_node->next = s;
previous_node = s;
}
}

double total_cgpa = 0;
Student* current = head;
while (current != nullptr) {
total_cgpa += current->cgpa;
current = current->next;
}
double average_cgpa = total_cgpa / n;

cout << "\nAverage CGPA : " << average_cgpa << endl;

return 0;
}

LAB Day- 9
STL Stack
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack <int> Basket;
int n;
cout<< "Enter number of elements:"<< endl;
cin >> n;

for(int i =1; i<=n; i++){


int x;
cout<< "Enter new element:"<< endl;
cin >> x;
Basket.push(x);
}
cout<<" "<< endl;

cout<< "Size of the Stack:";


int size = Basket.size();
cout<< size << endl;

if (Basket.size() == n) {
cout << "Stack is full." << endl;
cout<< " " << endl;
}

int top_element = Basket.top();


cout<<"Top element: "<<top_element<<endl;
cout<< " " << endl;

while(Basket.empty()==0){
int top= Basket.top();
cout << "The popped element is " << top << endl;
Basket.pop();
}

if(Basket.empty()==1){
cout<<"Stack is empty"<<endl;
}
return 0;
}

Stack case
#include <iostream>
#include <stack>
using namespace std;

int main() {
stack<int> Basket;
int n;
int choice;

cout << "Enter maximum size of the stack: ";


cin >> n;

while (true) {
cout << "\nChoose an operation:\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Peek (Top element)\n";
cout << "4. Traverse\n";
cout << "5. Check if stack is Empty\n";
cout << "6. Check if stack is Full\n";
cout << "7. Size\n";
cout << "8. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1: {
if (Basket.size() < n) {
int x;
cout << "Enter new element: ";
cin >> x;
Basket.push(x);
cout << x << " pushed into the stack.\n";
} else {
cout << "Stack is full.\n";
}
break;
}
case 2: {
if (!Basket.empty()) {
int top = Basket.top();
Basket.pop();
cout << "The popped element is " << top << ".\n";
} else {
cout << "Stack is empty.\n";
}
break;
}
case 3: {
if (!Basket.empty()) {
cout << "Top element: " << Basket.top() << ".\n";
} else {
cout << "Stack is empty.\n";
}
break;
}
case 4: {
if (!Basket.empty()) {
stack<int> temp = Basket;
cout << "Stack elements: ";
while (!temp.empty()) {
cout << temp.top() << " ";
temp.pop();
}
cout << "\n";
} else {
cout << "Stack is empty.\n";
}
break;
}
case 5: {
if (Basket.empty()) {
cout << "Stack is empty.\n";
} else {
cout << "Stack is not empty.\n";
}
break;
}
case 6: {
if (Basket.size() == n) {
cout << "Stack is full.\n";
} else {
cout << "Stack is not full.\n";
}
break;
}
case 7: {
cout << "Size of the stack: " << Basket.size() << "\n";
break;
}
case 8: {
cout << "Exiting...\n";
return 0; // Exit the program
}
default: {
cout << "Invalid choice. Please try again.\n";
}
}
}

return 0;
}

Stack using Array


#include <iostream>
using namespace std;

int basket[100];
int n;
int top = 0;

void push(int x) {
if (top >= n)
cout << "Basket Overflow" << endl;
else {
basket[top] = x;
top++;
}
}

void pop() {
if (top <= 0)
cout << "Basket Underflow" << endl;
else {
top--;
cout << "The popped element is " << basket[top] << endl;
}
}

void traverse() {
if (top > 0) {
cout << "Basket elements are:";
for (int i = top - 1; i >= 0; i--)
cout << basket[i] << " "<< endl;
cout << "Top element is: " << basket[top - 1] << endl;
} else
cout << "Basket is empty" << endl;
}

int main() {
cout << "Enter the size of the basket: ";
cin >> n;

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


int x;
cout << "Enter " << i + 1 << " element: ";
cin >> x;
push(x);
}

traverse();

if (top == n) {
cout << "Stack is full." << endl;
cout<< " " << endl;
}

cout << "Pop the stack:" << endl;

int count=0;

while (top != 0) {
pop();
count++;
}

cout<< " " << endl;


cout << "Size of the Stack:";
cout<< count << endl;

if (top == 0) {
cout << "Stack is empty." << endl;
}

return 0;
}

Using case

#include <iostream>
using namespace std;

int basket[100];
int n;
int top = 0;

void push(int x) {
if (top >= n)
cout << "Basket Overflow" << endl;
else {
basket[top] = x;
top++;
}
}

void pop() {
if (top <= 0)
cout << "Basket Underflow" << endl;
else {
top--;
cout << "The popped element is " << basket[top] << endl;
}
}

void traverse() {
if (top > 0) {
cout << "Basket elements are:";
for (int i = top - 1; i >= 0; i--)
cout << basket[i] << " ";
cout << endl;
cout << "Top element is: " << basket[top - 1] << endl;
} else
cout << "Basket is empty" << endl;
}

bool isEmpty() {
return top == 0;
}

bool isFull() {
return top == n;
}

int size() {
return top;
}

int main() {
cout << "Enter the size of the basket: ";
cin >> n;

int choice;
while (true) {
cout << "\nChoose an operation:\n";
cout << "1. Push\n";
cout << "2. Pop\n";
cout << "3. Traverse\n";
cout << "4. Check if Empty\n";
cout << "5. Check if Full\n";
cout << "6. Get Size\n";
cout << "7. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch(choice) {
case 1: {
int x;
cout << "Enter element to push: ";
cin >> x;
push(x);
break;
}
case 2: {
pop();
break;
}
case 3: {
traverse();
break;
}
case 4: {
if (isEmpty())
cout << "Basket is empty" << endl;
else
cout << "Basket is not empty" << endl;
break;
}
case 5: {
if (isFull())
cout << "Basket is full" << endl;
else
cout << "Basket is not full" << endl;
break;
}
case 6: {
cout << "Size of the basket: " << size() << endl;
break;
}
case 7: {
cout << "Exiting..." << endl;
break;
}
default: {
cout << "Invalid choice. Please try again." << endl;
}
}
}

return 0;
}
LAB Day- 10
Infix to PostFix
#include <stack>
#include <string>
using namespace std;

bool isOperator(char c) {
return c == '^' || c == '*' || c == '/' || c == '+' || c == '-' || c == '=';
}

int getPrecedence(char op) {


if (op == '^')
return 3;
else if (op == '*' || op == '/')
return 2;
else if (op == '+' || op == '-')
return 1;
else // '='
return 0;
}

string infixToPostfix(string infix) {


stack<char> basket;
string postfix;

// Step 1: Push "(" into Basket and add ")" to the end of infix notation
infix = "(" + infix + ")";

for (int i = 0; i < infix.length(); ++i) {


char c = infix[i];
if (c == ' ')
continue;

else if (c == '(')
basket.push(c);

else if (isOperator(c)) {
while (!basket.empty() && basket.top() != '(' && getPrecedence(basket.top()) >=
getPrecedence(c)) {
postfix += basket.top();
basket.pop();
}
basket.push(c);
} else if (c == ')') {
while (!basket.empty() && basket.top() != '(') {
postfix += basket.top();
basket.pop();
}
basket.pop();

} else //operand - add to postfix


postfix += c;
}
return postfix;
}

int main() {
string infix;
cout << "Enter the infix expression: ";
getline(cin, infix);

string postfix = infixToPostfix(infix);


cout << "Postfix expression: " << postfix << endl;

return 0;
}

POSTFIX Evaluation
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <cmath>
using namespace std;

bool isOperator(char c) {
return c == '^' || c == '*' || c == '/' || c == '+' || c == '-' || c == '=';
}

int getPrecedence(char op) {


if (op == '^')
return 3;
else if (op == '*' || op == '/')
return 2;
else if (op == '+' || op == '-')
return 1;
else // '='
return 0;
}
string infixToPostfix(string infix) {
stack<char> basket;
string postfix;

for (int i = 0; i < infix.length(); ++i) {


char c = infix[i];
if (c == ' ')
continue;
else if (isdigit(c)) {
while (isdigit(c)) {
postfix += c;
i++;
if (i < infix.length()) {
c = infix[i];
} else {
break;
}
}
postfix += ' ';
i--;
} else if (c == '(') {
basket.push(c);
} else if (c == ')') {
while (!basket.empty() && basket.top() != '(') {
postfix += basket.top();
basket.pop();
}
basket.pop();
} else if (isOperator(c)) {
while (!basket.empty() && basket.top() != '(' && getPrecedence(basket.top()) >=
getPrecedence(c)) {
postfix += basket.top();
basket.pop();
}
basket.push(c);
}
}

while (!basket.empty()) {
postfix += basket.top();
basket.pop();
}
return postfix;
}

int evaluatePostfix(string postfix) {


stack<int> basket;
for (int i = 0; i < postfix.length(); ++i) {
char c = postfix[i];

if (isdigit(c)) {
int number = 0;
while (isdigit(c)) {
number = number * 10 + (c - '0');
i++;
if (i < postfix.length()) {
c = postfix[i];
} else {
break;
}
}
basket.push(number);
i--;
} else if (c == ' ') {
continue;
} else if (isOperator(c)) {
int operand2 = basket.top(); basket.pop();
int operand1 = basket.top(); basket.pop();
int result;
switch (c) {
case '^':
result = pow(operand1, operand2);
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '=':
result = operand2;
break;
}
basket.push(result);
}
}
return basket.top();
}
int main() {
string infix;
cout << "Enter the infix expression: ";
getline(cin, infix);

string postfix = infixToPostfix(infix);


cout << "Postfix expression: " << postfix << endl;

int result = evaluatePostfix(postfix);


cout << "Result after evaluation: " << result << endl;

return 0;
}

LAB Day- 11
QUEUE using Array
#include <iostream>
using namespace std;

int queue[100], n , front = - 1, rear = - 1;

void enqueue(int x) {
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else if (front == - 1 && rear== - 1){
front++;
rear++;
queue[rear] = x;
}
else{
rear++;
queue[rear] = x;
}
}

void dequeue() {
if (front == - 1 && rear== - 1) {
cout<<"Queue Underflow ";
}
else {
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;;
}
}

void traverse() {
if (front == - 1)
cout<<"Queue is empty"<<endl;
else {
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" "<<endl;
}

void empty() {
if (front > rear) {
cout<<"Queue is empty.";
}
else{
cout<<"Queue is not empty.";
}
}

int main() {
cout << "Enter the size of the queue: ";
cin >> n;

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


int x;
cout << "Enter " << i + 1 << " element: ";
cin >> x;
enqueue(x);
}

traverse();

cout << "Front element of the queue:";


int Front_element = queue[front];
cout << Front_element << endl;

cout << "Rear element of the queue:";


int Rear_element = queue[rear];
cout << Rear_element << endl;
cout << "Size of the queue:";
int size= (rear - front) + 1;
cout<< size << endl;
cout<<" "<< endl;

cout << "Dequeue the queue:" << endl;


while (front <= rear) {
dequeue();
}

empty();

return 0;
}

Queue using case


#include <iostream>
using namespace std;

int queue[100], n, front = -1, rear = -1;

void enqueue(int x) {
if (rear == n - 1)
cout << "Queue Overflow" << endl;
else if (front == -1 && rear == -1) {
front++;
rear++;
queue[rear] = x;
} else {
rear++;
queue[rear] = x;
}
}

void dequeue() {
if (front == -1 && rear == -1) {
cout << "Queue Underflow" << endl;
} else {
cout << "Element deleted from queue is: " << queue[front] << endl;
front++;
}
}

void traverse() {
if (front == -1)
cout << "Queue is empty" << endl;
else {
cout << "Queue elements are: ";
for (int i = front; i <= rear; i++)
cout << queue[i] << " ";
cout << endl;
}
}

void empty() {
if (front > rear || (front == -1 && rear == -1)) {
cout << "Queue is empty." << endl;
} else {
cout << "Queue is not empty." << endl;
}
}

void frontElement() {
if (front == -1 || front > rear)
cout << "Queue is empty." << endl;
else
cout << "Front element of the queue: " << queue[front] << endl;
}

void rearElement() {
if (rear == -1 || front > rear)
cout << "Queue is empty." << endl;
else
cout << "Rear element of the queue: " << queue[rear] << endl;
}

bool isFull() {
return rear == n - 1;
}

int size() {
return (rear - front) + 1;
}

int main() {
cout << "Enter the size of the queue: ";
cin >> n;

while (true) {
int choice;
cout << "\nQueue Operation:\n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Traverse\n";
cout << "4. Check if Queue is Empty\n";
cout << "5. Check if Queue is Full\n";
cout << "6. Front Element\n";
cout << "7. Rear Element\n";
cout << "8. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
int x;
cout << "Enter element to enqueue: ";
cin >> x;
enqueue(x);
break;
}
case 2:
dequeue();
break;
case 3:
traverse();
break;
case 4:
empty();
break;
case 5:
if (isFull())
cout << "Queue is full." << endl;
else
cout << "Queue is not full." << endl;
break;
case 6:
frontElement();
break;
case 7:
rearElement();
break;
case 8:
cout << "Exiting..." << endl;
return 0;
default:
cout << "Invalid choice. Please try again." << endl;
}
}

return 0;
}
Queue using STL
#include<iostream>
#include<queue>

using namespace std;

int main()
{
queue<int> Queue;

int n;
cout << "Enter the size of Queue:";
cin >> n;
cout << "Enter elements in Queue - " << endl;

for(int i = 1; i<= n; i++){


int x;
cin >> x;
Queue.push(x);
}

cout << "Front Element: " << Queue.front() << endl;


cout << "Size: " << Queue.size() << endl;

cout << "Dequeuing"<< endl;


while(Queue.empty() == 0){
cout << Queue.front() << endl;
Queue.pop();
}

CIRCULAR Queue
#include<iostream>
using namespace std;

int front = -1, rear = -1;


int queue[1000];
int n, count = 0;

void enqueue(int x)
{
if ((rear + 1) % n == front)
{
cout << "Overflow" << endl;
return;
}
else if (front == -1 && rear == -1)
{
front= rear=0;
queue[rear] = x;
}
else
{
rear = (rear + 1) % n;
queue[rear] = x;
}
}

void dequeue()
{
if (front == -1 && rear == -1)
{
cout << "Underflow" << endl;
return;
}
else if (front == rear)
{
front = rear = -1;
}
else
{
front = (front + 1) % n;
}
}

void traverse()
{
if (front == -1 && rear == -1)
{
cout << "Queue is empty" << endl;
return;
}
else {
cout<<"Queue elements are : ";
for (int i = front; i!=(rear+1);i=(i+1)%n){
cout<<queue[i]<<" "<<endl;
}
}
}
bool empty()
{
return (front == -1 && rear == -1);
}
int main()
{
cout << "Enter the size of Queue: ";
cin >> n;

int choice;
do {
cout << "Circular Queue Operation: \n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Traverse\n";
cout << "4. Check if Queue is Empty\n";
cout << "5. Check if Queue is Full\n";
cout << "6. Front Element\n";
cout << "7. Rear Element\n";
cout << "8. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
int x;
cout << "Enter the element to enqueue: ";
cin >> x;
enqueue(x);
break;
}
case 2:
dequeue();
break;
case 3:
traverse();
break;
case 4:
if (empty())
cout << "Queue is empty.";
else
cout << "Queue is not empty.";
break;
case 5:
if ((rear + 1) % n == front)
cout << "Queue is full.";
else
cout << "Queue is not full.";
break;
case 6:
cout << "Front element: " << queue[front] << endl;
break;
case 7:
cout << "Rear element: " << queue[rear] << endl;
break;
case 8:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice";
}
} while (choice != 8);

return 0;
}

LAB Day- 12
Graph
Unweighted Directed List Representation
#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main()
{
int M= 10000;
vector< int > G[M+1];
int ne;
cout<< "Number of edge:" ;
cin>> ne;
for (int i=1; i<=ne; i++)
{
int u,v;
cout<< "Enter the value of u, v:";
cin >> u>> v;
G[u].push_back(v);
}
for (int u=0; u<=M; u++)
{
int l =G[u].size();

if(l!=0){
cout << u << " - ";
for (int i=0; i<=l-1; i++)
{
cout<< G[u][i] << " " ;
}
cout << endl;

}
}
Unweighted Undirected List Representation
#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main()
{
int M= 10000;
vector< int > G[M+1];
int ne;
cout<< "Number of edge:" ;
cin>> ne;
for (int i=1; i<=ne; i++)
{
int u,v;
cout<< "Enter the value of u, v:";
cin >> u>> v;
G[u].push_back(v);
G[v].push_back(u);
}
for (int u=0; u<=M; u++)
{

int l =G[u].size();

if(l!=0){
cout << u << " - ";
for (int i=0; i<=l-1; i++)
{
cout<< G[u][i] << " " ;
}
cout << endl;
}

}
}

Weighted Directed List Representation


#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main()
{
int M= 100000000;
vector< pair<int, int> > G[M+1];
int ne;
cout<< "Number of edge:" ;
cin>> ne;
for (int i=1; i<=ne; i++)
{
int u,v, w;
cout<< "Enter the value of u, v, w:";
cin >> u>> v>> w;
G[u].push_back(make_pair (v,w));
}

for (int u=0; u<=M; u++)


{
cout << u;
int l =G[u].size();
for (int i=0; i<=l-1; i++)
{
cout<< " ( " << G[u][i].first<< " , " << G[u][i].second << " )";
}
cout << endl;
}
}

Weighted Undirected List Representation


#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main(){
int M= 10000;
vector< pair<int, int> > G[M+1];
int ne;
cout<< "Number of edge:" ;
cin>> ne;
for (int i=1; i<=ne; i++){
int u,v, w;
cout<< "Enter the value of u, v, w:";
cin >> u>> v>> w;
G[u].push_back(make_pair (v,w));
}
for (int u=0; u<=M; u++){
int l =G[u].size();

if(l!=0){
cout << u << "-";
for (int i=0; i<=l-1; i++){
cout<< " ( " << G[u][i].first<< " , " << G[u][i].second << " )";
}
cout << endl;
}
}

Graph Adjacency matrix – Undirected Unweighted


#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main(){
int M= 10000;
vector< pair<int, int> > G[M+1];
int ne;
cout<< "Number of edge:" ;
cin>> ne;
for (int i=1; i<=ne; i++){
int u,v, w;
cout<< "Enter the value of u, v, w:";
cin >> u>> v>> w;
G[u].push_back(make_pair (v,w));
G[v].push_back(make_pair (u,w)); // remove for directed
}
for (int u=0; u<=M; u++){
int l =G[u].size();
if(l!=0){
cout << u << "-";
for (int i=0; i<=l-1; i++){
cout<< " ( " << G[u][i].first<< " , " << G[u][i].second << " )";
}
cout << endl;
}
}

Graph Adjacency matrix – Undirected weighted


#include<iostream>
#define inf (1<<31) - 1
using namespace std;
int main(){
int M = 8;
int G[M+1] [M+1];
for( int i=0; i<=M; i++){
for (int j=0; j<=M; j++){
if(i == j){
G[i][j]=0;
}
else{
G[i][j]=inf;
}
}
}
int ne;
cout<< "Number of edges: "<< endl;
cin>> ne;

for(int i=1; i<=ne; i++){


int u,v,w;
cout<< "Input u, v, w: " << endl;
cin>> u >> v >> w;
G[u][v] = w;
G[v][u] = w; // remove for directed
}

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


for (int j = 0; j <= M; j++){
cout << G[i][j] << " ";
}
cout << endl;
}
return 0;
}

LAB Day- 13
BFS
#include<iostream>
#include<vector>
#include<queue>
#include<fstream>
using namespace std;

int main(){

int M= 1000;
vector<int>G[M+1];
int color[M+1];
int level[M+1];

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


color[i] = 0;
level[i] = -1;
}

int ne;
cout<<"Total number of edges:";
cin>> ne;

cout<<"Enter the vertices : "<<endl;


for(int i=1; i<=ne; i++)
{
int u,v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}

int src;
cout<<"Enter source :";
cin>>src;

queue<int> Q;
color[src] = 1;
level[src] = 0;
Q.push(src);

while(!Q.empty()){

int u = Q.front();
int l = G[u].size();
for(int i = 0; i<l; i++){
int v = G[u][i];
if(color[v] == 0){
color[v] = 1;
level[v] = level[u] + 1;
Q.push(v);
}
}
cout<< " The order of vertices is =" << u <<endl;
cout<< " The level of " <<u <<" is =" << level[u]<<endl;
Q.pop();

DFS
#include <iostream>
#include <vector>

using namespace std;

vector<int> G[1001];
int color[1001];
int entry[1001];
int finish[1001];
int order[1001];
int order_index = 0;

void DFS(int u, int &stop_watch) {


color[u] = 1;
stop_watch++;
entry[u] = stop_watch;
order[order_index] = u;
order_index++;
int l = G[u].size();
for(int i = 0; i < l; i++) {
int v = G[u][i];
if(color[v] == 0) {
DFS(v, stop_watch);
}
}
stop_watch++;
finish[u] = stop_watch;
}

int main() {
int M = 1000;

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


color[i] = 0;
entry[i] = -1;
finish[i] = -1;
order[i] = -1;
}

int ne;
cout << "Total number of edges: ";
cin >> ne;

cout << "Enter the vertices: " << endl;


for(int i = 0; i < ne; i++) {
int u, v;
cin >> u >> v;
G[u].push_back(v);
G[v].push_back(u);
}

int src;
cout << "Enter source: ";
cin >> src;

int stop_watch = 0;
DFS(src, stop_watch);

cout << "The order of vertices is: ";


for(int i = 0; i < order_index; i++) {
cout << order[i] << " ";
}
cout << endl;

cout << "Entry times: ";


for(int i = 0; i < order_index; i++) {
cout << "Vertex " << order[i] << ": " << entry[order[i]] << ", ";
}
cout << endl;

cout << "Finish times: ";


for(int i = 0; i < order_index; i++) {
cout << "Vertex " << order[i] << ": " << finish[order[i]] << ", ";
}
cout << endl;

return 0;
}

Back To Under World


#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

vector<int> adj_list[20009];
bool color[20009] = {};
bool type[20009] = {};

int main() {
int T;
scanf("%d", &T); // test cases

for (int case_num = 1; case_num <= T; ++case_num) {


// Reset arrays for each test case
for (int i = 0; i < 20009; i++) {
color[i] = false;
type[i] = false;
adj_list[i].clear();
}

int n, u, v;
scanf("%d", &n); // Read number of dual fights

// Read each dual fight and build the graph


for (int i = 0; i < n; ++i) {
scanf("%d %d", &u, &v);
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}

long long int max_count = 0; // Initialize max_count to zero

// Process each node to find connected components


for (int i = 1; i <= 20000; ++i) {
if (!color[i] && !adj_list[i].empty()) { // If node is not visited and has edges
long long int lykan_num = 0, vampire_num = 0;
queue<int> q;

// Start BFS from this node


q.push(i);
color[i] = 1;
type[i] = 1; // Assume the first node is a Lykan
++lykan_num;

while (!q.empty()) {
int u = q.front();
q.pop();

// Explore all neighbors


for (int j = 0; j < adj_list[u].size(); ++j) {
int v = adj_list[u][j];
if (!color[v]) {
q.push(v);
color[v] = 1;

// Alternate types between Lykan and Vampire


if (type[u] == 1) {
type[v] = 0;
++vampire_num;
} else {
type[v] = 1;
++lykan_num;
}
}
}
}
// Update max_count with the maximum count from this connected component
max_count += max(vampire_num, lykan_num);
}
}
// Output the result for this test case
cout << "Case " << case_num << ": " << max_count << '\n';
}
return 0;
}

You might also like