Assessment 2: Implement A Stack Using Queuee Code
Assessment 2: Implement A Stack Using Queuee Code
Assessment 2: Implement A Stack Using Queuee Code
CODE:
CODE:
// CPP program to implement Queue using
// two stacks with costly enQueue()
#include <bits/stdc++.h>
using namespace std;
struct Queue {
stack<int> s1, s2;
void enQueue(int x)
ASSESSMENT 2
{
// Move all elements from s1 to s2
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
// Push item into s1
s1.push(x);
// Push everything back to s1
while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
}
// Dequeue an item from the queue
int deQueue()
{
// if first stack is empty
if (s1.empty()) {
cout << "Q is Empty";
exit(0);
}
// Return top of s1
int x = s1.top();
s1.pop();
return x;
}
};
// Driver code
int main()
{
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
return 0;
}
CODE:
#include <iostream>
using namespace std;
int main()
{
int arr[50],counter=0; //declaring size of array and initializing counter to zero//
int n;
cout<<"Here are the 50 random integers between 1&10:-"<<endl;
for(int i=0;i<50;i++) //for loop to iterate the random numbers upto 50 times.
{
arr[i]=(rand()%10)+1; //rand() function is used to generate random numbers
in the range [0, max].
//ar[i] will store the random number generated.
cout<<arr[i]<<endl; //To display the randomized integers b/w 1 and 10.
}
cout<<"Enter The Number You Want To Check:"<<endl;
cin>>n;
int *p=&arr[0]; //pointer p will point to the 1st elemtent of the array//
int *q; // New pointer q is created.//
q=&n; //q stores the address of the int n given by the user.//
for(int i=0; i<50; i++)
{
if(*q==*p) //if value pointed by *q = value pointed by *p//
counter++; // counting the value and incrementing in the count in array//
p++; //incrementing p
}
cout<<"\nThis Number "<<n<<" has been repeated "<<counter<<" times in the
array"; //displaying the count[] array//
ASSESSMENT 2
}
4. Write a function which asks the user for height, width and
length of a cuboid objects. This function should run 3 times.
These three cuboid shapes are due to be stacked on top of
each other in a packaging box Use another function to
determine and display the smallest size (by displaying height,
length and width) of the box which could be used for
packaging when these three boxes are stacked.
CODE:
void dimension()
{
cout<<"Enter Length - "; cin>>l;
cout<<"Enter Breadth - "; cin>>b;
cout<<"Enter Height - "; cin>>h;
}
void dim_stack_pushing()
{
push(stack,l);
push(stack,b);
push(stack,h);
}
};
int main()
{
Stack S1, S2, S3;
int l_1, b_1, h_1;
cout<<"\n\nEnter Dimensions Of Cubiod 1\n"; S1.dimension();
S1.dim_stack_pushing();
cout<<"\n\nEnter Dimensions Of Cubiod 2\n"; S2.dimension();
S2.dim_stack_pushing();
cout<<"\n\nEnter Dimensions Of Cubiod 3\n"; S3.dimension();
S3.dim_stack_pushing();
cout<<"\nThe Smallest Box Dimensions Required For Packaging All Three Boxes
When Joined In Stack Are As Follows\n";
cout<<"\nHeight - "<<l_1;
cout<<"\nBreadth - "<<b_1;
cout<<"\nHeight - "<<S1.h+S2.h+S3.h;
return 0;
}
5. "WAP to give the output if the following sequence of operation is
following on a stack push(A)push(B)push(c)pop(C)push(D)push(E)pop(E)"
CODE:
/* C++ program to implement basic stack
operations */
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
ASSESSMENT 2
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}
int Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
}
int Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
//print all elements in stack :
cout<<"Elements present in stack : ";
while(!s.isEmpty())
{
// print top element in stack
cout<<s.peek()<<" ";
// remove top element in stack
s.pop();
}
ASSESSMENT 2
return 0;
}
CODE:
// C++ code to reverse a
// stack using recursion
#include<bits/stdc++.h>
using namespace std;
// using std::stack for
// stack implementation
stack<char> st;
// initializing a string to store
// result of reversed stack
string ns;
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
char insert_at_bottom(char x)
{
if(st.size() == 0)
st.push(x);
else
{
// All items are held in Function Call
// Stack until we reach end of the stack
// When the stack becomes empty, the
// st.size() becomes 0, the above if
// part is executed and the item is
// inserted at the bottom
char a = st.top();
st.pop();
insert_at_bottom(x);
// push allthe items held in
// Function Call Stack
// once the item is inserted
// at the bottom
st.push(a);
}
}
ASSESSMENT 2
// Below is the function that
// reverses the given stack using
// insert_at_bottom()
char reverse()
{
if(st.size()>0)
{
// Hold all items in Function
// Call Stack until we
// reach end of the stack
char x = st.top();
st.pop();
reverse();
// Insert all the items held
// in Function Call Stack
// one by one from the bottom
// to top. Every item is
// inserted at the bottom
insert_at_bottom(x);
}
}
// Driver Code
int main()
{
// push elements into
// the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
cout<<"Original Stack"<<endl;
// print the elements
// of original stack
cout<<"1"<<" "<<"2"<<" "
<<"3"<<" "<<"4"
<<endl;
// function to reverse
// the stack
reverse();
cout<<"Reversed Stack"
<<endl;
// storing values of reversed
// stack into a string for display
while(!st.empty())
{
ASSESSMENT 2
char p=st.top();
st.pop();
ns+=p;
}
//display of reversed stack
cout<<ns[3]<<" "<<ns[2]<<" "
<<ns[1]<<" "<<ns[0]<<endl;
return 0;
}
7. WAP to find a duplicate entry in the stack and remove them and
display the final output
CODE:
// CPP program to remove duplicate character
// from character array and print in sorted
// order
#include <bits/stdc++.h>
using namespace std;
char *removeDuplicate(char str[], int n)
{
// Used as index in the modified string
int index = 0;
// Traverse through all characters
for (int i=0; i<n; i++) {
// Check if str[i] is present before it
int j;
for (j=0; j<i; j++)
if (str[i] == str[j])
break;
// If not present, then add it to
// result.
if (j == i)
str[index++] = str[i];
}
return str;
}
// Driver code
int main()
{
char str[]= "geeksforgeeks";
ASSESSMENT 2
int n = sizeof(str) / sizeof(str[0]);
cout << removeDuplicate(str, n);
return 0;
}
8. WAP to construct a static tree upto level 2 as shown in the above fig.
CODE:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
int getLevelUtil(struct node *node,char data, int level)
{
if (node == NULL)
return 0;
return temp;
}
int main()
{
struct node *root = new struct node;
char x;
root = newNode('A');
root->left = newNode('B');
root->right = newNode('C');
root->left->left = newNode('D');
root->left->right = newNode('E');
root->right->left = newNode('F');
root->right->right = newNode('G');
for (x = 1; x <= 7; x++)
{
int level = getLevel(root, x);
if (level)
ASSESSMENT 2
cout << "Level of "<< x << " is "
<< getLevel(root, x) << endl;
else
cout << x << "is not present in tree"
<< endl;
}
return 0;
}
9. WAP to remove node E as shown in the given fig
CODE:
#include <bits/stdc++.h>
using namespace std;
struct Node {
char key;
struct Node *left, *right;
};
if (node == NULL)
return newNode(key);
return node;
}
if (root == NULL)
return root;
ASSESSMENT 2
if (root->key > k) {
root->left = deleteNode(root->left, k);
return root;
}
else if (root->key < k) {
root->right = deleteNode(root->right, k);
return root;
}
if (root->left == NULL) {
Node* temp = root->right;
delete root;
return temp;
}
else if (root->right == NULL) {
Node* temp = root->left;
delete root;
return temp;
}
else {
if (succParent != root)
ASSESSMENT 2
succParent->left = succ->right;
else
succParent->right = succ->right;
root->key = succ->key;
delete succ;
return root;
}
}
int main()
{
inorder(root);
printf("\nDelete E\n");
root = deleteNode(root, 'E');
inorder(root);
return 0;
ASSESSMENT 2
}
CODE :
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
char data;
node* left;
node* right;
};
node* newNode(char data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
int search(char arr[], int strt, int end, char value)
{
int i;
for (i = strt; i <= end; i++)
if (arr[i] == value)
return i;
}
node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
static int preIndex = 0;
ASSESSMENT 2
if (inStrt > inEnd)
return NULL;
return tNode;
}
CODE:
ASSESSMENT 2
#include<iostream>
using namespace std;
#include<cstring>
#include <algorithm>
#include<stack>
bool isoperator(char c)
{
return(!isalpha(c)&&!isdigit(c)); //code to scan the characters
}
int getpriority(char C) //func. to check priotity or percedence of
oeprators
{
if(C=='-'||C=='+')
return 1;
else if (C == '*' || C == '/')
return 2;
else if (C == '^')
return 3;
return 0;
}
string intopost(string infix) //func. to convert infix to postfix
{
infix = '(' + infix + ')';
int l = infix.size();
stack<char> s;
string output;
for(int i=0;i<l;i++)
{
if (isalpha(infix[i]) || isdigit(infix[i]))
output += infix[i]; //if it is operand then it will be added to
output
else if (infix[i] == '(')
s.push('('); //IF IT is '(' it will be ADDED TO STACK
ASSESSMENT 2
else if (infix[i] == ')') //IF scanned character is ')'
// pop will be perfromed it will be output from
stack
//until '(' is encountered
{
while (s.top() != '(')
{
output += s.top();
s.pop();
}
s.pop(); // it will remove '(' from the stack
}
else // if the operator is found
{
if(isoperator(s.top()))
{
if(infix[i] == '^') //if infix equal to exponential
{
}
else
{
while (getpriority(infix[i]) <getpriority(s.top()))
ASSESSMENT 2
{
output += s.top();
s.pop();
}
s.push(infix[i]); //it will push
//current operator to stack
}
}
}
return output;
}
string intopre(string infix)
{
int a = infix.size();
reverse(infix.begin(), infix.end()); //reverse infix
for (int i = 0; i < a; i++) { //it will replace ( with ) and ) with (
if (infix[i] == '(') {
infix[i] = ')';
i++;
}
else if (infix[i] == ')')
{
infix[i] = '(';
i++;
}
}
string prefix = intopost(infix);
return prefix;
}
int main()
{
string s = (" a+b-c/d&e|f ");
cout << intopre(s) << endl;
return 0;
}
12. "Wap to covert infix to postfix for the given exp infix a+b*c+(d*e)
Prefix abc*+de*+"
CODE:
#include<bits/stdc++.h>
using namespace std;
//Function to return precedence of operators
int prec(char c) {
if(c == '^')
return 3;
else if(c == '/')
return 2;
else if(c=='*')
return 1;
else if(c == '+' || c == '-')
return -1;
else
return -2;
}
// The main function to convert infix expression
void infixToPostfix(string s) {
stack<char> st; //For stack operations, we are using C++ built in stack
ASSESSMENT 2
string result;
for(int i = 0; i < s.length(); i++) {
char c = s[i];
// If the scanned character is
// an operand, add it to output string.
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >=
'0' && c <= '9'))
result += c;
// If the scanned character is an
// ‘(‘, push it to the stack.
else if(c == '(')
st.push('(');
// If the scanned character is an ‘)’,
// pop and to output string from the stack
// until an ‘(‘ is encountered.
else if(c == ')') {
while(st.top() != '(')
{
result +=
st.top();
st.pop();
}
st.pop();
}
//If an operator is scanned
else {
while(!st.empty() && prec(s[i])
<= prec(st.top())) {
result +=
st.top();
st.pop();
}
st.push(c);
}
ASSESSMENT 2
}
// Pop all the remaining elements from the stack
while(!st.empty()) {
result += st.top();
st.pop();
}
cout << result << endl;
}
bool isOperator(char x) {
switch (x) {
case '+':
case '-':
case '/':
case '*':
return true;
}
return false;
}
// Convert prefix to Infix expression
string preToInfix(string pre_exp) {
stack<string> s;
// length of expression
int length = pre_exp.size();
// reading from right to left
for (int i = length - 1; i >= 0; i--) {
// check if symbol is operator
if (isOperator(pre_exp[i])) {
// pop two operands from stack
string op1 = s.top(); s.pop();
string op2 = s.top(); s.pop();
// concat the operands and operator
string temp = "(" + op1 + pre_exp[i] +
op2 + ")";
// Push string temp back to stack
ASSESSMENT 2
s.push(temp);
}
// if symbol is an operand
else {
// push the operand to the stack
s.push(string(1, pre_exp[i]));
}
}
// Stack now contains the Infix expression
return s.top();
}
return 0;
}
ASSESSMENT 2
13. Wap to create a stack according to the given diagram
CODE:
#include <iostream>
using namespace std;
int stack[5], n = 5, top = -1;
void push(int val)
{
if (top >= n - 1)
cout << "Stack Overflow" << endl;
else
{
top++;
stack[top] = val;
}
}
void display()
{
if (top >= 0)
ASSESSMENT 2
{
cout << "Stack elements are:"<<endl;
for (int i = top; i >= 0; i--)
cout << stack[i] << " "<< endl;
}
else
cout << "Stack is empty";
}
int main()
{
int val;
return 0;
}
There is a special catch block called 'catch all' catch (...) that can be used
to catch all types of exceptions. For example, in the following program,
an int is thrown as an exception, but there is no catch block for int, so
catch (...) block will be executed.
include
int main(int argc, char **argv) { std::cout << 25u - 50; return 0;
}"
ANSWER:
#include<iostream>
using namespace std;
int main()
{
int res=25u-50;
cout<<res;
return 0 ;
}
*/
16. "Find the output of the given code using namespace std;
class A { public: A(int ii = 0) : i(ii) {} void show() { cout << ""i = ""
<< i << endl;} private: int i; };
ANSWER:
include
int main() { int arr[] = {1, 2 ,3, 4, 5}; int &zarr = arr; for(int i = 0;
i <= 4; i++) { arr[i] += arr[i]; } for(i = 0; i <= 4; i++) cout<< zarr[i];
return 0; }"
ANSWER:
#include<iostream.h>
int main()
{
int arr[] = {1, 2 ,3, 4, 5}; // Crearting an array
int &zarr = arr; // an array of references is not acceptable.
Because (i is not initialized).
for(int i = 0; i <= 4; i++)b // For loop
{
arr[i] += arr[i]; // input Condition
}
ASSESSMENT 2
for(i = 0; i <= 4; i++)
cout<< zarr[i]; // Here the output of array gets
return 0;
}
include
include
ofile.close();
return 0; } "
ANSWER :
#include<iostream>
#include<fstream>
using namespace std;
int main () { //create a text file named file before running. ofstream
ofile; ofile.open (""file.txt"");
ofstream ofile;
ofile.open("file.txt");
ofile<< "hello", 13; ofile.seekp (8); ofile<< " how r u", 6;
ofile.close();
return 0;
ASSESSMENT 2
}
ANSWER :
19->#include <iostream>
#include <fstream>
#include <cctype>
int main ()
{
ifstream ifile;
ifile.open ("text.txt");
include
int main() { try { throw 10; } catch (char *excp) { cout <<
""Caught "" << excp; } catch (...) { cout << ""Default
Exception\n""; } return 0; }"
ANSWER:
include
ASSESSMENT 2
using namespace std;
ANSWER:
#include <iostream>
using namespace std;
int main()
{
try {
fun(NULL, 0);
}
catch(...) {
cout << "Caught exception from fun()";
}
return 0;
}
ASSESSMENT 2
/* Output we get is "Caught exception from fun()"
this is because Dynamic Exception specified i.e throw (int *, int) used
when a problem is expected
if not specified our program may abort beacuse by defalut the program
indirectly calls terminate() which
by default calls abort()*/
include
class Test { public: Test() { cout << ""Constructor of Test "" <<
endl; } ~Test() { cout << ""Destructor of Test "" << endl; } };
int main() { try { Test t1; throw 10; } catch (int i) { cout <<
""Caught "" << i << endl; } }"
ANSWER:
Reason:
This is because in this program we are creating the object of class Test
with te creation of object constructor automatically called but the scope
of destructor in the try block is about to end so destructor is also called
before throwing the value to the catch block and then caught 10
printed on the screen
*/
include
ASSESSMENT 2
using namespace std;
class Test { public: Test() { cout << ""Constructor of Test "" <<
endl; } ~Test() { cout << ""Destructor of Test "" << endl; } };
int main() { try { Test t1; throw 10; } catch (int i) { cout <<
""Caught "" << i << endl; } }"
ANSWER:
Catch block wasn't present for the character type thrown error… that's
why program terminates. OR
Constructor of test
Destructor of test
Caught 10
include
int main() { try { Test t1; throw 10; } catch (int i) { cout <<
""Caught "" << i << endl; } }"
ANSWER:
#include<iostream>
using namespace std;
class Test
{
public: Test()
{
cout << "Constructor of Test " << endl;
}
~Test()
{
cout << "Destructor of Test " << endl;
}
};
int main()
{
try
{
Test t1;
throw 10;
}
catch (int i)
{
cout << "Caught " << i << endl;
}
}
ASSESSMENT 2
25. "Find the output of the given code include using
namespace std;
int main() { int P = -1; try { cout << ""Inside try""; if (P < 0)
{ throw P; cout << ""After throw""; } } catch (int P ) { cout <<
""Exception Caught""; } cout << ""After catch""; return 0; }"
ANSWER 1:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
/* Enter your code here. Read input from STDIN. Print output to
STDOUT */
ifstream ifile;
ifile.open (""text.txt"");
char last;
ifile.ignore (256, ' ');
last = ifile.get();
/In the file 'text.txt' we have the input like Toshiba Ansari. So,
ignore(256,' ') Extracts characters from the input sequence and discards
ASSESSMENT 2
them, until either 256 characters have been extracted, or one compares
equal to ' '.This program prints the first character of the second word in
the file like 'A.'/
ANSWER 2:
#include <iostream>
#include <stack>
using namespace std;
class Stack
{
stack<int> st;
int a, b, c, d;
public:
//This function will Take entery
void Entery(int a, int b, int c, int d, int e, int f, int g)
{
st.push(a);
st.push(b);
st.push(c);
st.push(d);
st.push(e);
st.push(f);
st.push(g);
cout << "The member of stack are ::";
while (!st.empty())
{
cout << "\t" << st.top();
st.pop();
}
}
void printRepeating(int arr[], int size)
ASSESSMENT 2
{
int i;
cout << "\n The repeating elements are:" << endl;
for (i = 0; i < size; i++)
{
if (arr[abs(arr[i])] >= 0)
arr[abs(arr[i])] = -arr[abs(arr[i])];
else
cout << abs(arr[i]) << " ";
}
}
};
int main()
{
Stack a1;
a1.Entery(1, 2, 3, 1, 3, 6, 6);
int arr[] = {1, 2, 3, 1, 3, 6, 6};
int arr_size = sizeof(arr) / sizeof(arr[0]);
a1.printRepeating(arr, arr_size);
return 0;
}