Professional Documents
Culture Documents
Input-
output-
Algorithm-Each string contains a null at end so we iterate till the character is null updating the value of
length by 1 every time it moves ahead,then when iterator points to null we return length.
Flowchart
Code-
#include <iostream.h>
int main()
{
char s[100];
int i;
printf(“Enter a string: “);
scanf(“%s”, s);
for(i = 0; s[i] != ‘\0’; ++i);
printf(“Length of string: %d”, i);
return 0;
}
Conclusion-
We have calculated length of string using the method of accessing elements of string.
Learning-
We learnt to access an element of the string and computed its length which is number of elements in
string including the spaces and special characters.
1.2.
input-
input string 1
input string 2
output-
concatenated string
algorithm-Take a string and iterate over first string and push its element into a empty string.Now iterate
over the second string and push its characters into the same string in which first strings's character were
pushed.
flowchart-
code-
#include<bits/stdc++.h>
using namespace std;
bool subset(string a, string b) {
if(a == b)
return true;
int j = 0;
for(int i = 0; i < b.size(); i++){
if(a[j] == b[i])
{j++;}
if(j == a.size())
{
return true;}
}
return false;
}
int length(string s)
{
int cnt=0;
for(int i=0;s[i]!='\0';i++)
{
cnt++;
}
return cnt;
}
void compare(string a,string b)
{
int i=0;
if(length(a)==length(b))
{
if(a==b)
{
cout<<"equal";
return;
}
while(a[i]!='\0')
{
if(a[i]>b[i])
{
cout<<"a>b";
return;
}
else if(a[i]<b[i])
{
cout<<"b>a";
return;
}
else if(a[i]==b[i])
{
i++;
}
}
}
else if(length(a)!=length(b)){
int i=0;
int j=0;
while(a[i]!='\0'&&b[j]!='\0')
{
if(a[i]>b[j])
{
cout<<"a>b";
break;
return;
}
else if(a[i]<b[j]){
cout<<"b>a";
break;
return;
}
else if(a[i]==b[j])
{
i++;
j++;
}
}
if(subset(b,a)||subset(a,b))
{if(length(a)>length(b))
{
cout<<"a>b";
}
else{
cout<<"b>a";
}}
}
}
bool palindrome(string s)
{
bool flag;
int i=0;
int j=length(s)-1;
while(i<j){
if(s[i]==s[j])
{
flag=true;
}
else
{
flag=false;
}
i++;
j--;}
return flag;
}
string concatenate(string &a,string &b)
{
string s;
for(int i=0;i<length(a);i++)
{
s.push_back(a[i]);
}
for(int i=0;i<length(b);i++)
{
s.push_back(b[i]);
}
return s;
}
int main()
{
string s;
cin>>s;
cout<<length(s);
if(palindrome(s))
{
cout<<"yes palindrome";
}
else{
cout<<"not palindrome";
}
string a;
cin>>a;
if(subset(s,a))
{
if s is a subset of a
cout<<"yes subset"<<endl;
}
else{
cout<<"not subset"<<endl;
}
//cout<<length(s);
string b;
cin>>b;
cout<<concatenate(s,b);
compare(s,b);
return 0;
conclusion-
We hence concatenated 2 strings together by using length function already built by us and pushing both
strings together into a new string and returning the new string.
Learning-
We have accessed a string and added another at the end of it without making any new string.
1.3.
input-
output-
if a palindrome then yes a palindrome is printed else not palindrome is not printed.
algorithm-We take 2 pointers one at start and one at end of string then compare the 2 pointers. A
palindrome should have same characters at both ends since it reads same from both sides if we start
from either left or right its same .So we compare both pointers if they are same then first pointer is
iterates to next character and second pointer comes to previous and then they are again compared. If at
any point the characters for the 2 pointers are not equal then return false ,else the process is continued
till the start pointer exceeds the end pointer i.e. all elements have been compared. If all characters are
equal come out of loop and return true.
flowchart-
code-
#include <bits/
stdc+ +.h>
using na mespace s
td;
bool su bset(stri
ng a, st ring b) {
if (a == b)
re turn true
;
in t j = 0;
for(int i = 0; i < b.size(); i++){
if(a[j] == b[i])
{j++;}
if(j == a.size())
{
return true;}
}
return false;
}
int length(string s)
{
int cnt=0;
for(int i=0;s[i]!='\0';i++)
{
cnt++;
}
return cnt;
}
void compare(string a,string b)
{
int i=0;
if(length(a)==length(b))
{
if(a==b)
{
cout<<"equal";
return;
}
while(a[i]!='\0')
{
if(a[i]>b[i])
{
cout<<"a>b";
return;
}
else if(a[i]<b[i])
{
cout<<"b>a";
return;
}
else if(a[i]==b[i])
{
i++;
}
}
}
else if(length(a)!=length(b)){
int i=0;
int j=0;
while(a[i]!='\0'&&b[j]!='\0')
{
if(a[i]>b[j])
{
cout<<"a>b";
break;
return;
}
else if(a[i]<b[j]){
cout<<"b>a";
break;
return;
}
else if(a[i]==b[j])
{
i++;
j++;
}
}
if(subset(b,a)||subset(a,b))
{if(length(a)>length(b))
{
cout<<"a>b";
}
else{
cout<<"b>a";
}}
}
}
bool palindrome(string s)
{
bool flag;
int i=0;
int j=length(s)-1;
while(i<j){
if(s[i]==s[j])
{
flag=true;
}
else
{
flag=false;
}
i++;
j--;}
return flag;
}
string concatenate(string &a,string &b)
{
string s;
for(int i=0;i<length(a);i++)
{
s.push_back(a[i]);
}
for(int i=0;i<length(b);i++)
{
s.push_back(b[i]);
}
return s;
}
int main()
{
string s;
cin>>s;
cout<<length(s);
if(palindrome(s))
{
cout<<"yes palindrome";
}
else{
cout<<"not palindrome";
}
string a;
cin>>a;
if(subset(s,a))
{
if s is a subset of a
cout<<"yes subset"<<endl;
}
else{
cout<<"not subset"<<endl;
}
//cout<<length(s);
string b;
cin>>b;
cout<<concatenate(s,b);
compare(s,b);
return 0;
conclusion-
We learnt how to use 2 pointer approach in strings and also to use bool type functions. We also learnt
the concept of palindromes and checked if a string is palindrome.
aim-to find if a string is a subset of another string
input-
input string 1
input string 2
output-
if string 1 is a subset of string 2 print yes subset otherwise print not subset.
algorithm-
Take 2 pointers pointing to start of smaller and bigger string respectively. Now, the iterator pointing to
bigger string is updated to next for each string and the iterator for small iterator is updated to next only
if they point to same character and if the iterator for small string points to end of smaller string then its a
subset otherwise the loop for bigger string's iterator also ends without finding common elements and
hence come out of the loop and return false.
flowchart-
code-
#include<bits/stdc++.h>
using namespace std;
bool subset(string a, string b) {
if(a == b)
return true;
int j = 0;
for(int i = 0; i < b.size(); i++){
if(a[j] == b[i])
{j++;}
if(j == a.size())
{
return true;}
}
return false;
}
int length(string s)
{
int cnt=0;
for(int i=0;s[i]!='\0';i++)
{
cnt++;
}
return cnt;
}
void compare(string a,string b)
{
int i=0;
if(length(a)==length(b))
{
if(a==b)
{
cout<<"equal";
return;
}
while(a[i]!='\0')
{
if(a[i]>b[i])
{
cout<<"a>b";
return;
}
else if(a[i]<b[i])
{
cout<<"b>a";
return;
}
else if(a[i]==b[i])
{
i++;
}
}
}
else if(length(a)!=length(b)){
int i=0;
int j=0;
while(a[i]!='\0'&&b[j]!='\0')
{
if(a[i]>b[j])
{
cout<<"a>b";
break;
return;
}
else if(a[i]<b[j]){
cout<<"b>a";
break;
return;
}
else if(a[i]==b[j])
{
i++;
j++;
}
}
if(subset(b,a)||subset(a,b))
{if(length(a)>length(b))
{
cout<<"a>b";
}
else{
cout<<"b>a";
}}
}
}
bool palindrome(string s)
{
bool flag;
int i=0;
int j=length(s)-1;
while(i<j){
if(s[i]==s[j])
{
flag=true;
}
else
{
flag=false;
}
i++;
j--;}
return flag;
}
string concatenate(string &a,string &b)
{
string s;
for(int i=0;i<length(a);i++)
{
s.push_back(a[i]);
}
for(int i=0;i<length(b);i++)
{
s.push_back(b[i]);
}
return s;
}
int main()
{
string s;
cin>>s;
cout<<length(s);
if(palindrome(s))
{
cout<<"yes palindrome";
}
else{
cout<<"not palindrome";
}
string a;
cin>>a;
if(subset(s,a))
{
if s is a subset of a
cout<<"yes subset"<<endl;
}
else{
cout<<"not subset"<<endl;
}
//cout<<length(s);
string b;
cin>>b;
cout<<concatenate(s,b);
compare(s,b);
return 0;
}
outputs for diff inputs
conclusion-
We again used two pointer approach to check whether a string is palindrome or not.
Learning-
We learnt the concept of subset and hence checked if a string is subset of another string.
4.
input-
input string 1
input string 2
output-
a>b if a is larger
b>a if b is larger
algorithm-
first if length of 2 string is equal check whose character comes first in dictionary and that is larger, if both
strings are equal print equal. If lengths are not equal check whose character comes first in dictionary and
that is larger. Now, check if one string is a subset of another string then the string which is longer is
larger.
flowchart-
code-
#include<bits/stdc++.h>
using namespace std;
bool subset(string a, string b) {
if(a == b)
return true;
int j = 0;
for(int i = 0; i < b.size(); i++){
if(a[j] == b[i])
{j++;}
if(j == a.size())
{
return true;}
}
return false;
}
int length(string s)
{
int cnt=0;
for(int i=0;s[i]!='\0';i++)
{
cnt++;
}
return cnt;
}
void compare(string a,string b)
{
int i=0;
if(length(a)==length(b))
{
if(a==b)
{
cout<<"equal";
return;
}
while(a[i]!='\0')
{
if(a[i]>b[i])
{
cout<<"a>b";
return;
}
else if(a[i]<b[i])
{
cout<<"b>a";
return;
}
else if(a[i]==b[i])
{
i++;
}
}
}
else if(length(a)!=length(b)){
int i=0;
int j=0;
while(a[i]!='\0'&&b[j]!='\0')
{
if(a[i]>b[j])
{
cout<<"a>b";
break;
return;
}
else if(a[i]<b[j]){
cout<<"b>a";
break;
return;
}
else if(a[i]==b[j])
{
i++;
j++;
}
}
if(subset(b,a)||subset(a,b))
{if(length(a)>length(b))
{
cout<<"a>b";
}
else{
cout<<"b>a";
}}
}
}
bool palindrome(string s)
{
bool flag;
int i=0;
int j=length(s)-1;
while(i<j){
if(s[i]==s[j])
{
flag=true;
}
else
{
flag=false;
}
i++;
j--;}
return flag;
}
string concatenate(string &a,string &b)
{
string s;
for(int i=0;i<length(a);i++)
{
s.push_back(a[i]);
}
for(int i=0;i<length(b);i++)
{
s.push_back(b[i]);
}
return s;
int main()
{
string s;
cin>>s;
cout<<length(s);
if(palindrome(s))
{
cout<<"yes palindrome";
}
else{
cout<<"not palindrome";
}
string a;
cin>>a;
if(subset(s,a))
{
if s is a subset of a
cout<<"yes subset"<<endl;
}
else{
cout<<"not subset"<<endl;
}
//cout<<length(s);
string b;
cin>>b;
cout<<concatenate(s,b);
compare(s,b);
return 0;
}
output for different inputs-
conclusion-
We compared two strings using c++ without using inbuilt strcmp function in c++ libraries.
Learning-
We learnt how to compare two strings by first comparing their length and then comparing their each
element.
EXPERIMENT 2- SEARCHES IN AN ARRAY
2.1.
INPUT
Output
Algorithm
Iterate over each element of array. If any one element is equal to the key, print the index of that. Else
print not found.
Flowchart-
Code-
#include<bi ts/stdc++.h>
using names pace std;
int main()
{
int n,k ey;
cin>>n> >key;
int a[1 00];
for(in t i=0;i<n;i+
+)
{
cin >>a[i];
}
int flag=0;
for(in t i=0;i<n;i+
+)
{
if(a[i]==key)
{
cout<<i<<endl;
flag=1;
break;
}
}
if(flag==0){
cout<<"not found"<<endl;}
return 0;}
Conclusion-
We learnt to use for loop to iterate over an array and found index at which target is present. We also saw
that it iterates over array.
Learning-
2.2.
Output-
Algorithm-we divide array in 2 parts Then search for the element in smaller parts. We keep on dividing
into smaller parts till we reach single elements and there if our key to search matches we return the
position.
Flowchart-
Code-
#include<bits/stdc++.h>
using namespace std;
int binarysearch(int s,int e,int v[1000],int key)
{
if(s>e)
{
cout<<"element not found ";
return -1;
}
int mid=(s+e)/2;
if(v[mid]==key)
{
return mid;
}
else if(key>v[mid])
{
return binarysearch(mid+1,e,v,key);
}
else if(key<v[mid])
{
return binarysearch(s,mid-1,v,key);
}
}
int main()
{
vector<int>v;
cout<<"no of elements"<<endl;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int inp;
cin>>inp;
v.push_back(inp);
}
int arr[1000];
for(int i=0;i<n;i++)
{
cout<<v[i];
}
sort(v.begin(),v.end());
for(int i=0;i<n;i++)
{
arr[i]=v[i];
}
int key;
cin>>key;
cout<<binarysearch(0,n-1,arr,key);
return 0;
}
Output for different inputs-
Conclusion-
We understood algo of binary search to understand how to search for key in array.
Learning-
We learnt how to access an intermediate element of an array and how to divide the array in sub parts.
In every iteration of selection sort, the minimum element (considering ascending order) from
the unsorted subarray is picked and moved to the sorted subarray.
Flowchart:
Code:
#include<bits/stdc++.h>
using namespace std;
void selectionSort(int arr[], int n){
for(int i = 0; i < n; i++){
int min_ind = i;
for(int j = i + 1; j < n; j++){
if(arr[j] < arr[min_ind]){
min_ind = j;
}
}
swap(arr[i], arr[min_ind]);
}
}
int main() {
int capacity;
cout<<"Enter the capacity of array to be sorted"<<endl;
cin>>capacity;
int a[capacity];
cout<<"Add elements to array"<<endl;
for(int i=0; i<capacity; i++)
{
cin>>a[i];
}
selectionSort(a, capacity);
for(int i = 0;i < capacity; i++){
cout<<a[i]<<" ";
}
return 0;
}
Output:
Insertion Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array
Algorithm:
1.The first element in the array is assumed to be sorted. Take the second element and store it
separately in key. Compare key with the first element. If the first element is greater than key,
then key is placed in front of the first element.
2. Now, the first two elements are sorted. Take the third element and compare it with the
elements on the left of it. Placed it just behind the element smaller than it. If there is no
element smaller than it, then place it at the beginning of the array.
3. Similarly, place every unsorted element at its correct position.
Flowchart:
Code:
#include<bits/stdc++.h>
using namespace std;
void iSort(int arr[],int n){
for(int i=1;i<n;i++){
int key = arr[i];
int j=i-1;
while(j>=0 && arr[j]>key){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
}
}
int main() {
int capacity;
cout<<"Enter the capacity of array to be sorted"<<endl;
cin>>capacity;
int a[capacity];
cout<<"Add elements to array"<<endl;
for(int i=0; i<capacity; i++)
{
cin>>a[i];
}
iSort(a,capacity);
for(auto x: a)
cout<<x<<" ";
}
Output:
Bubble Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array.
Algorithm:
1. Starting with the first element (index = 0), compare the current element with the next
element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat
Step 1.
Flowchart:
Code:
#include<bits/stdc++.h>
using namespace std;
void bubbleSort(int arr[], int n){
bool swapped;
for(int i = 0;i < n; i++){
swapped = false;
for(int j = 0 ; j < n - i -1; j++){
if( arr[j] > arr[j+1]){
swap(arr[j], arr[j+1]);
swapped = true;
}
}
if( swapped == false)
break;
}
}
int main() {
int capacity;
cout<<"Enter the capacity of array to be sorted"<<endl;
cin>>capacity;
int a[capacity];
cout<<"Add elements to array"<<endl;
for(int i=0; i<capacity; i++)
{
cin>>a[i];
}
bubbleSort(a, capacity);
for(int i = 0; i < capacity; i++){
cout<<a[i]<<" ";
}
return 0;
}
Output
Merge Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array
Algorithm:
1. It works by recursively dividing an array into two equal halves, sorting and then merging
each sorted half.
2. Merge sort is example of a divide and conquer algorithm. Broadly speaking, a divide and
conquer algorithm has the following parts:
Divide: This involves dividing the problem into subproblems
Conquer: recursively process sub problems until each one is solved
Combine: combine solved sub problems to give a solution to the original problem
Flowchart:
Code:
#include <iostream>
#include <algorithm>
using namespace std;
void merge(int arr[], int l, int m, int h)
{
int n1 = m - l + 1, n2 = h - m;
int left[n1], right[n2];
for (int i = 0; i < n1; i++)
left[i] = arr[i + l];
for (int j = 0; j < n2; j++)
right[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2)
{
if (left[i] <= right[j])
arr[k++] = left[i++];
else
arr[k++] = right[j++];
}
while (i < n1)
arr[k++] = left[i++];
while (j < n2)
arr[k++] = right[j++];
}
void mergeSort(int arr[], int l, int r)
{
if (r > l)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main()
{
int capacity;
cout<<"Enter the capacity of array to be sorted"<<endl;
cin>>capacity;
int a[capacity];
cout<<"Add elements to array"<<endl;
for(int i=0; i<capacity; i++)
{
cin>>a[i];
}
int l = 0, r = capacity-1;
mergeSort(a, l, r);
for (int x : a)
cout << x << " ";
}
Output:
Quick Sort
Aim: To sort a given array containing integers in ascending order
Input: We make an array containing integer numbers and then insert integers in that array in
any order.
Output: Output will be Sorted array
Algorithm: Quicksort is a sorting algorithm based on the divide and conquer approach where:
1. An array is divided into subarrays by selecting a pivot element (element selected from the array).
While dividing the array, the pivot element should be positioned in such a way that elements
less than pivot are kept on the left side and elements greater than pivot are on the right side of
the pivot.
2. The left and right subarrays are also divided using the same approach. This process continues
until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to form a sorted array
Flowchart:
Code:
#include <bits/stdc++.h>
using namespace std;
int partition(int arr[], int l, int h)
{
int pivot = arr[l];
int i = l - 1, j = h + 1;
while (true)
{
do
{
i++;
} while (arr[i] < pivot);
do
{
j--;
} while (arr[j] > pivot);
if (i >= j)
return j;
swap(arr[i], arr[j]);
}
}
void qSort(int arr[], int l, int h)
{
if (l < h)
{
int p = partition(arr, l, h);
qSort(arr, l, p);
qSort(arr, p + 1, h);
}
}
int main()
{
int capacity;
cout<<"Enter the capacity of array to be sorted"<<endl;
cin>>capacity;
int a[capacity];
cout<<"Add elements to array"<<endl;
for(int i=0; i<capacity; i++)
{
cin>>a[i];
}
qSort(a, 0, capacity - 1);
for (int x : a)
cout << x << " ";
}
Output:
EXPERIMENT 4- STACKS
Aim: To make a stack data structure and implement push, pop functions in it.
Algorithm:
1. Making a structure named myStack.
2. Dynamically allocating space for array using a constructor.
3. Initialize the pointer position for array and capacity of array.
4. Making push function for inserting an element x, which moves the pointer 1 position
ahead and then put user provided element in that array.
5. Making pop function which just remove topmost element from the stack. And returns its
value.
Code:
#include<bits/stdc++.h>
using namespace std;
struct myStack
{
int *arr;
int top;
int cap;
myStack(int c)
{
cap = c;
top = -1;
arr = new int[cap];
}
void push( int x)
{
if(top==cap-1)
{
cout<<"overflow"<<endl;
}
else
{
top++;
arr[top] = x;
}
}
int pop()
{
if(top==(-1))
{
cout<<"Underflow"<<endl;
return INT_MAX;
}
else
{
int res = arr[top];
top--;
return res;
}
}
int peek()
{
return arr[top];
}
};
int main()
{
myStack s(5);
for(int i=0 ; i<5 ; i++)
{
cout<<"enter element to the stack"<<endl;
int n;
cin>>n;
s.push(n);
}
cout<<"Stack is : ";
for(int i=0 ; i<5 ; i++)
{
cout<<s.peek()<<" ";
s.pop();
}
}
Output:
Infix To Postfix
Aim: To convert expressions like a+b(infix) to ab+(postfix).
Input: An infix expression in the form of string.
Output: A resultant Postfix expression conversion of user provided infix expression.
Algorithm:
Code:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
//INFIX TO POSTFIX CONVERSION
int helper(char c)
{
if(c == '^')
return 3;
else if(c == '*' || c == '/')
return 2;
else if(c == '+' || c == '-')
return 1;
else
return 0;
}
string InfixToPostfix(string infix)
{
stack<char> s;
string postfix;
for(int i=0; i< infix.length(); i++)
{
if((infix[i] >= 'a' && infix[i] <= 'z') || (infix[i] >= 'A' && infix[i]
<= 'Z')){
postfix+=infix[i];
}
else if(infix[i] == '('){
s.push(infix[i]);
}
else if(infix[i] == ')'){
while((s.top()!='(') && (!s.empty())){
postfix+=s.top();
s.pop();
}
if(s.top()=='('){
s.pop();
}
}
else{
if(s.empty()){
s.push(infix[i]);
}
else
{
if(helper(infix[i])>helper(s.top())){
s.push(infix[i]);
}
else if((helper(infix[i])== helper(s.top())) && (infix[i]=='^'))
{
s.push(infix[i]);
}
else
{
while((!s.empty())&&( helper(infix[i])<=helper(s.top()))){
postfix+=s.top();
s.pop();
}
s.push(infix[i]);
}
}
}
}
while(!s.empty())
{
postfix+=s.top();
s.pop();
}
return postfix;
}
int main()
{
string infix, res;
cin>>infix;
res= InfixToPostfix(infix);
cout<<res;
return 0;
}
Conclusion: We can change infix to postfix that helps computer to operate faster.
Infix To Prefix
using namespace std;
//INFIX TO PREFIX CONVERSION
int helper(char c)
{
if (c == '^')
return 3;
else if (c == '*' || c == '/')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return 0;
}
string InfixToPrefix(string infix)
{
stack<char> s;
string prefix;
reverse(infix.begin(), infix.end());
for (int i = 0; i < infix.length(); i++)
{
if (infix[i] == '(')
{
infix[i] = ')';
}
else if (infix[i] == ')')
{
infix[i] = '(';
}
}
for (int i = 0; i < infix.length(); i++)
{
if ((infix[i] >= 'a' && infix[i] <= 'z') || (infix[i] >= 'A' && infix[i]
<= 'Z'))
{
prefix += infix[i];
}
else if (infix[i] == '(')
{
s.push(infix[i]);
}
else if (infix[i] == ')')
{
while ((s.top() != '(') && (!s.empty()))
{
prefix += s.top();
s.pop();
}
if (s.top() == '(')
{
s.pop();
}
}
else
{
if (s.empty())
{
s.push(infix[i]);
}
else
{
if (helper(infix[i]) > helper(s.top()))
{
s.push(infix[i]);
}
else if ((helper(infix[i]) == helper(s.top())) && (infix[i] == '
^'))
{
while ((helper(infix[i]) == helper(s.top())) && (infix[i] ==
'^'))
{
prefix += s.top();
s.pop();
}
s.push(infix[i]);
}
else if (helper(infix[i]) == helper(s.top()))
{
s.push(infix[i]);
}
else
{
while ((!s.empty()) && (helper(infix[i]) < helper(s.top())))
{
prefix += s.top();
s.pop();
}
s.push(infix[i]);
}
}
}
}
while (!s.empty())
{
prefix += s.top();
s.pop();
}
reverse(prefix.begin(), prefix.end());
return prefix;
}
int main()
{
string infix, res;
cin >> infix;
res = InfixToPrefix(infix);
cout << res;
return 0;
}
Conclusion: We can change infix to prefix that helps computer to operate faster.
EXPERIMENT 6- BALANCED PARENTHESIS USING STACKS
bool areBracketsBalanced(string str)
{
stack<char> s;
char x;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
s.push(str[i]);
continue;
}
if (s.empty())
return false;
switch (str[i])
{
case ')':
x = s.top();
s.pop();
if (x == '{' || x == '[')
return false;
break;
case '}':
x = s.top();
s.pop();
if (x == '(' || x == '[')
return false;
break;
case ']':
x = s.top();
s.pop();
if (x == '(' || x == '{')
return false;
break;
}
}
return (s.empty());
}
int main()
{
string str;
cin >> str;
if (areBracketsBalanced(str))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
Conclusion: We can check for parenthesis in any given string using the above code.
EXPERIMENT 7- QUEUE OPERATIONS
7.1.
Code-
#include <bits/stdc++.h>
using namespace std;
struct QNode
{
int data;
QNode *next;
QNode(int d)
{
data = d;
next = NULL;
}
};
struct Queue
{
QNode *front, *rear;
Queue()
{
front = rear = NULL;
}
void enQueue(int x)
{
QNode *temp = new QNode(x);
if (rear == NULL)
{
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
void deQueue()
{
if (front == NULL)
return;
QNode *temp = front;
front = front->next;
if (front == NULL)
rear = NULL;
delete (temp);
}
};
int main()
{
Queue q;
q.enQueue(100);
q.enQueue(200);
q.deQueue();
q.deQueue();
q.enQueue(130);
q.enQueue(400);
q.enQueue(5);
q.deQueue();
cout << "Queue Front : " << (q.front)->data << endl;
cout << "Queue Rear : " << (q.rear)->data;
}
Output-
Conclusion- We have stored integers using queue implemented through linked list.
Learning- We have learnt how to implement queue using stacks and retrieve first and last
element of queue.
7.2.
Code-
#include <bits/stdc++.h>
using namespace std;
class Stack
{
queue<int> q1, q2;
int curr_size;
public:
Stack()
{
curr_size = 0;
}
void push(int x)
{
curr_size++;
q2.push(x);
while (!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
// swap the names of two queues
queue<int> q = q1;
q1 = q2;
q2 = q;
}
void pop()
{
// if no elements are there in q1
if (q1.empty())
return;
q1.pop();
curr_size--;
}
int top()
{
if (q1.empty())
return -1;
return q1.front();
}
int size()
{
return curr_size;
}
};
int main()
{
Stack s;
s.push(6);
s.push(14);
s.push(30);
s.push(46);
s.push(25);
cout << "current size: " << s.size()
<< endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
cout << "current size: " << s.size()
<< endl;
return 0;
}
Output-
Conclusion- We have implemented queues using stacks and enqueued and dequeued
elements.
Learning- We have learnt how to implement queues using stacks and how to store elements in
a queue.
7.3.
Input- Giving numbers for a queue and performing queue operations in queue.
Code-
#include <bits/stdc++.h>
using namespace std;
class Queue
{
// Initialize front and rear
int rear, front;
// Circular Queue
int size;
int *arr;
public:
Queue(int s)
{
front = rear = -1;
size = s;
arr = new int[s];
}
void enQueue(int value);
int deQueue();
void displayQueue();
};
/* Function to create Circular queue */
void Queue::enQueue(int value)
{
if ((front == 0 && rear == size - 1) ||
(rear == (front - 1) % (size - 1)))
{
printf("\nQueue is Full");
return;
}
else if (front == -1) /* Insert First Element */
{
front = rear = 0;
arr[rear] = value;
}
else if (rear == size - 1 && front != 0)
{
rear = 0;
arr[rear] = value;
}
else
{
rear++;
arr[rear] = value;
}
}
// Function to delete element from Circular Queue
int Queue::deQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return INT_MIN;
}
int data = arr[front];
arr[front] = -1;
if (front == rear)
{
front = -1;
rear = -1;
}
else if (front == size - 1)
front = 0;
else
front++;
return data;
}
// Function displaying the elements
// of Circular Queue
void Queue::displayQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return;
}
printf("\nElements in Circular Queue are: ");
if (rear >= front)
{
for (int i = front; i <= rear; i++)
printf("%d ", arr[i]);
}
else
{
for (int i = front; i < size; i++)
printf("%d ", arr[i]);
for (int i = 0; i <= rear; i++)
printf("%d ", arr[i]);
}
}
/* Driver of the program */
int main()
{
Queue q(5);
// Inserting elements in Circular Queue
q.enQueue(23);
q.enQueue(12);
q.enQueue(123);
q.enQueue(-89);
// Display elements present in Circular Queue
q.displayQueue();
// Deleting elements from Circular Queue
printf("\nDeleted value = %d", q.deQueue());
printf("\nDeleted value = %d", q.deQueue());
q.displayQueue();
q.enQueue(9);
q.enQueue(21);
q.enQueue(53);
q.displayQueue();
q.enQueue(20);
return 0;
}
Output-
8.1
AIM: Pre-Order tree traversal
CODE:
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
Node* left ;
Node* right;
Node(int x)
{
key =x;
left = NULL;
right = NULL;
}
};
int main()
{
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(100);
root->left->right = new Node(200);
root->right->right = new Node(50);
preorder(root);
return 0;
}
OUTPUT:
8.2
AIM: In-Order tree traversal
CODE:
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
Node* left ;
Node* right;
Node(int x)
{
key =x;
left = NULL;
right = NULL;
}
};
inorder(root->left);
cout<< root->key<<" ";
inorder(root->right);
}
int main()
{
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(100);
root->left->right = new Node(200);
root->right->right = new Node(50);
inorder(root);
return 0;
}
OUTPUT:
8.3
AIM: Post-Order tree traversal
INPUT: No input Required by user
CODE:
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
Node* left ;
Node* right;
Node(int x)
{
key =x;
left = NULL;
right = NULL;
}
};
postorder(root->left);
postorder(root->right);
cout<< root->key<<" ";
}
int main()
{
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(100);
root->left->right = new Node(200);
root->right->right = new Node(50);
postorder(root);
return 0;
}
OUTPUT:
INPUT: We need to input an integer that will be key for inserted Node
CODE:
#include <bits/stdc++.h>
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int k)
{
key = k;
left = right = NULL;
}
};
cout << "Enter an integer value for Node To be Inserted" << endl;
cin >> x;
OUTPUT:
INPUT: The user should give key of pre-existing Node( Here done in main() )
CODE:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *left;
struct Node *right;
Node(int k){
key=k;
left=right=NULL;
}
};
OUTPUT:
CODE:
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node *left , *right;
Node(int x)
{
val = x;
left=NULL;
right=NULL;
}
};
if(root->val == x)
return true;
else if(root->val< x)
return isPresent(root->right, x);
else
return isPresent(root->left, x);
if(root->val==x)
{
return NULL;
}
return root;
}
}
bool isBST(Node* root , int lo , int
hi)//////////////////////////////////////////////////////////////////////
////////////////////////// 3
{
if(root==NULL) return true;
inorder(root);
cout<<"\n--------------------------------\n"<<endl;
cout<<"\n--------------------------------\n"<<endl;
OUTPUT:
CONCLUSION:
We can find leaf if both children of Node are NULL and delete that
particular node.
We can count Nodes of tree by traversing every node and on every non-
NULL node increasing counter.
Tree is BST if it have only 2 children or less than 2 children. Left child smaller
than parent and right child greater than parent.
EXPERIMENT 11- BINARY TREE TRAVERSAL
AIM: TO TRAVERSE A BINARY TREE WITHOUT USING RECURSION (Level Order
Traversal).
CODE:
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int val;
Node *left , *right;
Node(int x)
{
val = x;
left=NULL;
right=NULL;
}
};
int main()
{
Node* root = new Node(100);//level 1
100
root->left = new Node(50);// level
50 300
root->right = new Node(300);//
30 55 200 700
root->left->left = new Node(30);// level 3
10 35 51 70
root->left->right = new Node(55);//
root->right->left = new Node(200);//
root->right->right = new Node(700);//
root->left->left->left = new Node(10);// level 4
root->left->left->right = new Node(35);//
root->left->right->left = new Node(51);//
root->left->right->right = new Node(70);//
inorder(root);
cout<<"\
n-------------------------------------------------------------\n";
levelOrder(root);
return 0;
}
OUTPUT:
INPUT: Heaps are internally arrays hence we will have to pass array in each func.
CODE:
#include <bits/stdc++.h>
using namespace std;
OUTPUT:
INPUT: Heaps are internally arrays hence we will have to pass array in each func.
CODE:
#include <bits/stdc++.h>
using namespace std;
OUTPUT:
CONCLUSION: We can implement heap using arrays and heapify is used to make
Binary Heap Balanced. And we implement insert and delete with the help of
heapify .
EXPERIMENT 14 – M-WAY SEARCH TREE
AIM: To implement multi-way Search tree and perform the following operations-
Insertion
Deletion
Searching
Traversal
INPUT: User have to choose between all operations i.e., Insertion, Deletion,
Searching and Traversal. Based on choice specific task takes place.
CODE:
#include <bits/stdc++.h>
#define MAX 4
#define MIN 2
struct Node
{
int val[MAX + 1], count;
Node *link[MAX + 1];
};
Node *root;
int pos;
if (!node)
{
*pval = val;
*child = NULL;
return 1;
}
/* removes the value from the given node and rearrange values */
void removeVal(Node *myNode, int pos)
{
int i = pos + 1;
while (i <= myNode->count)
{
myNode->val[i - 1] = myNode->val[i];
myNode->link[i - 1] = myNode->link[i];
i++;
}
myNode->count--;
}
while (j > 0)
{
x->val[j + 1] = x->val[j];
x->link[j + 1] = x->link[j];
}
x->val[1] = myNode->val[pos];
x->link[1] = x->link[0];
x->count++;
x = myNode->link[pos - 1];
myNode->val[pos] = x->val[x->count];
myNode->link[pos] = x->link[x->count];
x->count--;
return;
}
x->count++;
x->val[x->count] = myNode->val[pos];
x->link[x->count] = myNode->link[pos]->link[0];
x = myNode->link[pos];
myNode->val[pos] = x->val[1];
x->link[0] = x->link[1];
x->count--;
x2->count++;
x2->val[x2->count] = myNode->val[pos];
x2->link[x2->count] = myNode->link[0];
j = pos;
while (j < myNode->count)
{
myNode->val[j] = myNode->val[j + 1];
myNode->link[j] = myNode->link[j + 1];
j++;
}
myNode->count--;
free(x1);
}
/* B-Tree Traversal */
void traversal(Node *myNode)
{
int i;
if (myNode)
{
for (i = 0; i < myNode->count; i++)
{
traversal(myNode->link[i]);
cout << myNode->val[i + 1] << ' ';
}
traversal(myNode->link[i]);
}
}
int main()
{
int val, opt;
while (true)
{
cout << "1. Insertion\t2. Deletion\n";
cout << "3. Searching\t4. Traversal\n";
cout << "5. Exit\nEnter your choice: ";
cin >> opt;
cout << endl;
switch (opt)
{
case 1:
cout << "Enter your input:";
cin >> val;
insertion(val);
break;
case 2:
cout << "Enter the element to delete:";
cin >> val;
deletion(val, root);
break;
case 3:
cout << "Enter the element to search:";
cin >> val;
searching(val, &opt, root);
break;
case 4:
traversal(root);
break;
case 5:
exit(0);
}
cout << endl;
}
return 0;
}
OUTPUT:
Insertion output
Traversal output
Deletion output
Searching output
CONCLUSION: M-way search is an extension of Binary search tree and hence most
implementation is similar where search, traverse, delete functions are
implemented by recursion. It have wide applications.