You are on page 1of 41

ASSESSMENT 2

1. IMPLEMENT A STACK USING QUEUEE

CODE:

/* Program to implement a stack using 


two queue */
#include <bits/stdc++.h>
  
using namespace std;
  
class Stack {
    // Two inbuilt queues
    queue<int> q1, q2;
  
    // To maintain current number of
    // elements
    int curr_size;
  
public:
    Stack()
    {
        curr_size = 0;
    }
  
    void push(int x)
    {
        curr_size++;
  
        // Push x first in empty q2
        q2.push(x);
  
        // Push all the remaining
        // elements in q1 to q2.
        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--;
ASSESSMENT 2
    }
  
    int top()
    {
        if (q1.empty())
            return -1;
        return q1.front();
    }
  
    int size()
    {
        return curr_size;
    }
};
  
// Driver code
int main()
{
    Stack s;
    s.push(1);
    s.push(2);
    s.push(3);
  
    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;
}

2. IMPLEMENT A QUEUEE USING STACK

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;
}

3. Write a program which generates an array of 50 random


integers between 1 and 10 inclusive. Use pointer
ASSESSMENT 2
manipulation to traverse through the array and check and
display how many times a user chosen number appears in
the array.

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:

//WAP to create stack and push/pop operations on it and display it


#include <iostream>
#include <malloc.h>
#define MAX 10
using namespace std;
class Stack
{
int stack[MAX], top=-1;
public:
int l, b, h;

void push(int stack[], int val)


{
if(top == MAX - 1)
{
cout<<"Stack Is Overflow"<<endl;
}
else
{
top++;
stack[top] = val;
}
ASSESSMENT 2
}

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();

if(S1.l>=S2.l && S1.l>=S3.l) {l_1=S1.l;}


else if(S3.l>=S1.l && S2.l>=S3.l) {l_1=S2.l;}
else if(S3.l>=S3.l && S3.l>=S3.l) {l_1=S3.l;}
if(S1.b>=S2.b && S1.b>=S3.b) {b_1=S1.b;}
ASSESSMENT 2
else if(S3.b>=S1.b && S2.b>=S3.b) {b_1=S2.b;}
else if(S3.l>=S3.l && S3.l>=S3.l) {b_1=S3.b;}

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;
}

6. Implement a code to reverse a element stored in a stack

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;

if (node -> data == data)


return level;
ASSESSMENT 2
int downlevel = getLevelUtil(node -> left, data, level + 1);
if (downlevel != 0)
return downlevel;

downlevel = getLevelUtil(node->right, data, level + 1);


return downlevel;
}

int getLevel(struct node *node, char data)


{
return getLevelUtil(node, data, 1);
}

struct node* newNode(char data)


{
struct node *temp = new struct node;
temp -> data = data;
temp -> left = NULL;
temp -> right = NULL;

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;
};

Node* newNode(char item)


{
Node* temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
ASSESSMENT 2
}

void inorder(Node* root)


{
if (root != NULL) {
inorder(root->left);
printf("%c ", root->key);
inorder(root->right);
}
}

Node* insert(Node* node, char key)


{

if (node == NULL)
return newNode(key);

if (key < node->key)


node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

Node* deleteNode(Node* root, char k)


{

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 {

Node* succParent = root;

Node* succ = root->right;


while (succ->left != NULL) {
succParent = succ;
succ = succ->left;
}

if (succParent != root)
ASSESSMENT 2
succParent->left = succ->right;
else
succParent->right = succ->right;

root->key = succ->key;

delete succ;
return root;
}
}

int main()
{

Node* root = NULL;


root = insert(root, 'A');
root = insert(root,'B' );
root = insert(root, 'D');
root = insert(root, 'E');
root = insert(root, 'C');
root = insert(root, 'F');
root = insert(root, 'G');

inorder(root);

printf("\nDelete E\n");
root = deleteNode(root, 'E');

inorder(root);

return 0;
ASSESSMENT 2
}

10. "In order –D, G, B, H, E, A, F, I, C Pre order – A, B, D, G, E, H, C, F, I


Constructe a binary tree according to above mention In order and Pre
order squence"

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;

node* tNode = newNode(pre[preIndex++]);


if (inStrt == inEnd)
return tNode;
int inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in, pre, inStrt, inIndex - 1);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd);

return tNode;
}

void show(node* node)


{
if (node == NULL)
return;
show(node->left);
cout<<node->data<<" ";
show(node->right);
}
int main()
{
char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' };
char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' };
int len = sizeof(in) / sizeof(in[0]);
node* root = buildTree(in, pre, 0, len - 1);
cout << "constructed tree is \n";
show(root);
}
11. "Wap to covert infix to prefix for the given exp infix a+b-c/d&e|f
Prefix |&-+ab/cdef"

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
{

while (getpriority(infix[i]) <= getpriority(s.top())) //it will run till priority


//of infix[i] is
//less then or equal priority of top most
character
{
output += s.top();
s.pop();
}

}
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);

// it will reverse postfix


ASSESSMENT 2
reverse(prefix.begin(), prefix.end());

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();
}

//Driver program to test above functions


int main() {
string exp = "a+b*c+(d*e) ";
infixToPostfix(exp);

string pre_exp = "abc*+de*+";


string pretopost=preToInfix(pre_exp);

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;

for (int j = 0; j < 4; j++)


{
cout << "Enter value" << endl;
cin >> val;
push(val);
}
display();

return 0;
}

14. "Find the accepted output of this code.


include
int i, j; class India { public: India(int x = 0, int y = 0) { i = x; j = x;
Display(); } void Display() { cout<< j <<"" ""; } }; int main()
{ India obj(10, 20); int &s = i; int &z = j; i++; cout<< s-- << "" "" <<
++z; return 0; }"
ASSESSMENT 2
CODE:

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.

15. "Find the output of the given code

include

int main(int argc, char **argv) { std::cout << 25u - 50; return 0;
}"

ANSWER:

#include<iostream>
using namespace std;

int main(int argc, char **argv)


{
std::cout << 25u - 50;
return 0;
}

/*Expected Output is -25


Output we get is 4294967271

why because 25u is an unsigned integer which does not support


negative value and
has an approximate value to 4 bytes , its supporting range is from 0 to
4294967295

so "4294967271" is the value unsigned integer can bear when 25 is


being subtracted .
ASSESSMENT 2
25u -50
(25-25=0;
0-25=4294967271;
*/

//To get Expected output


/*#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; };

class B { public: B(int xx) : x(xx) {} operator A() const { return


A(x); } private: int x; };

void g(A a) { a.show(); }

int main() { B b(10); g(b); g(20); getchar(); return 0; } "

ANSWER:

/* output of this program is


10
20
ASSESSMENT 2
first we make the object of class b and call the parametrized
constructor
class B is overloaded by conversion operator in this operator an object
of class B converted into A
and class A also has a parametrized constructor which can be called by
single integer argument so 10 will be pass and print on the screen and
again for 20 again same process done */

17. "Find the output of the given code

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:

/* The program will generate compile time error


1. header file should be -- #include<iostream>
2. int &zarr = arr is not correct we are trying to change address into
int
instead we can use pointer-- int *zarr; zarr = arr;
3. in second for loop we have to again declare int i
4. at last no double quote should be there.*/

#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;
}

18. "Find the output of the given code

include

include

using namespace std;

int main () { //create a text file named file before running.


ofstream ofile; ofile.open (""file.txt"");

ofile<< ""hello"", 13; ofile.seekp (8); ofile<< "" how r u"", 6;

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
}

19. "Find the output of the given code


include
include
include
using namespace std;
int main () { ifstream ifile; ifile.open (""text.txt"");
char last;
ifile.ignore (256, ' ');
last = ifile.get();

cout << ""Your initial is "" << last << '\n';


ifile.close();
return 0;
}"

ANSWER :

19->#include <iostream>
#include <fstream>
#include <cctype>

using namespace std;

int main ()

{
ifstream ifile;
ifile.open ("text.txt");

//content of file: geeksfor geeks


char last;
ifile.ignore (256, ' '); //ignore(256,'') extracts
character from input stream
ASSESSMENT 2
//and discards them till all of
//256 characters are extracted
last = ifile.get();

cout << "Your initial is " << last << '\n';


ifile.close();
return 0;
}
//In the main block we declare the variable P of integer type and create
a try block.“Inside try” will always be printed as we just entering try
block then. Now as P < 0 therefore the try block will throw int P as
exception hence “After throw” will not be printed. Now this exception
will be caught by the catch handler printing “Exception caught” and at
last after terminating the program “After catch” will be printed./

20. "Find the output of the given code

include

using namespace std;

int main() { try { throw 10; } catch (char *excp) { cout <<
""Caught "" << excp; } catch (...) { cout << ""Default
Exception\n""; } return 0; }"

ANSWER:

OUTPUT: Default Exception

Because the try statement throws an exception of type integer. But


there is no catch block for int, so catch(...) block will be executed.
catch(...) means 'catch all' as it can catch all exception of any type.

21. "Find the output of the given code

include
ASSESSMENT 2
using namespace std;

void fun(int *ptr, int x) throw (int , int) // Dynamic Exception


specification { if (ptr == NULL) throw ptr; if (x == 0) throw
x; / Some functionality */ }

int main() { try { fun(NULL, 0); } catch(...) { cout << ""Caught


exception from fun()""; } return 0; }"

ANSWER:

#include <iostream>
using namespace std;

// Here we specify the exceptions that this function


// throws.
void fun(int *ptr, int x) throw (int *, int) // Dynamic Exception
specification
{
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x;
/* Some functionality */
}

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()*/

22. "Find the output of the given code

include

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:

/*the output of the given program is

Constructing an object of Test


Destructing an object of Test
Caught 10

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
*/

23. "Find the output of the given code

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

/* The program will generate compile time error


1. header file should be -- #include<iostream>
2. cout<<""Caught ""; is wrong only one double quote is required so
it should be cout<<"Caught ";
3. at last no double quote should be there.
4. we are throwing a char value but in catch block int value will be
caught so it would not generate compile time error but would
terminate the program so we can use char x.
*/ OR
In try block an object is created so it will call default constructor and as
object goes out of scope it will call destructor.
In try block it also throw int exception so catch block which is of type int
will catch the exception. So output is:

Constructor of test
Destructor of test
Caught 10

24. "Find the output of the given code

include

using namespace std;


ASSESSMENT 2
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:

#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();

cout << ""Your initial is "" << last << '\n';


ifile.close();
return 0;
}

/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;
}

You might also like