Search This Blog

Saturday, February 13, 2010

Stack and Queue - Revision Questions for Computer Science Class XII (83)

DELHI 2008


Q.1 Write a function in C++ to insert an element into a dynamically allocated Queue where each

node contains a name (of type string) as data.

Assume the following definition of THENODE for the same.

struct THENODE

{

char Name[20];

THENODE *Link;

};

Solution:

struct THENODE

{

char Name[20];

THENODE *Link;

};

class Queue

{

THENODE *front,*rear;

public:

Queue( )

{ front = rear = NULL; }

void Insert( );

void Delete( );

void Display( );

};

void Queue::Insert( )

{

THENODE *ptr;

ptr=new THENODE;

if(ptr= = NULL)

{

cout<<”\nNo memory to create a new node….”;

exit(1);

}

cout<<”\nEnter the name….”;

Name);gets(ptr

Link=NULL;ptr

if(rear= = NULL)

front=rear=ptr;

else

{

Link=ptr;rear

rear=ptr;

}

}

Q.2. Evaluate the following postfix notation of expression (Show status of stack after execution of each operation ). 4, 10, 5, +, *, 15, 3, /, -

OUTSIDE DELHI 2008

Q.3. Write a function in C++ to Delete an element into a dynamically allocated Queue where each node contains a real number as data. Assume the following definition of MYNODE for the same.



struct MYNODE

{

float NUM;

MYNODE * Link;

};



Solution:

struct MYNODE

{

float NUM;

MYNODE *Link;

};

class Queue

{

MYNODE *front,*rear;

public:

Queue( )

{ front=rear=NULL; }

void Insert( );

void Delete( );

void Display( );

};

void Queue::Delete( )

{

MYNODE *temp;

if(front= = NULL)

cout<<”Queue Underflow”;

else

{

cout<<”\nThe content of the element to delete: “<

temp=front;

Link;front=front

delete temp;

}

}

Q.4. Evaluate the following postfix notation of expression (Show status of stack after execution of each operations): 5, 20, 15, -, *,25, 2, *, + 2.

Ans:

Children, Try this answer as an assignment.

DELHI : 2007

Q.1. Write a function in C++ to delete a node containing Book’s information, from a dynamically allocated Stack of Books implemented with the help of the following structure.

struct Book

{ int BNo ;

char BName[20] ;

Book *Next ;

} ;

Solution:

struct Book

{ int BNo ;

char BName[20] ;

Book *Next ;

} ;

class Stack

{ Book *Top;

public:

Stack( )

{ Top = NULL; }

void Push( );

void Pop( );

void Display( );

};

void Stack::Pop( )

{ Book *Temp;

If( Top= = NULL)

cout<<”Stack Underflow…”;

else

{ cout<<”\nThe Book number of the element to delete: “<

cout<<”\nThe Book name of the element to delete: “<

Temp=Top;

Next;Top=Top

Delete Temp;

}

}

Q.2. Evaluate the following postfix notation of expression : 25 8 3 - / 6 * 10 + 2.

Ans:

Children, Try this answer as an assignment.

OUTSIDE DELHI 2007

Q.1. Write a function in C++ to delete a node containing customer’s information, from a dynamically allocated Queue of Customers implemented with the help of the following structure.

struct Customer

{ int CNo ;

char CName[20] ;

Customer *Link ;

} ;

Solution:

struct Customer

{ int CNo ;

char CName[20] ;

Customer *Link ;

} ;

class Queue

{ Customer *front,*rear;

public:

Queue( )

{ front=rear=NULL; }

void Insert( );

void Delete( );

void Display( );

};

void Queue::Delete( )

{ Customer *Temp;

if(front= =NULL)

cout<<”Queue Underflow. No element to delete”;

else

{ cout<<”\n The customer number for the element to delete”<

cout<<”\n The customer name for the element to delete”<

Temp=front;

Link;front = front

delete Temp;

}

}

Q.2. Evaluate the following postfixnotation of expression : 15 3 2 + / 7 + 2. * 2

Ans:

Children, Try this answer as an assignment.

DELHI . 2006

Q.1. class queue

{ int data[10] ;

int front, rear ;

public :

queue( ) { front = - 1 ; rear = - 1 ; }

void add( ) ; //to add an element into the queue

void remove( ) ; //to remove an element from the queue

void Delete(int ITEM( ) ; //to delete all elements which are equal to ITEM

} ;

Complete the class with all function definitions for a circular array Queue. Use another queue to

transfer data temporarily.

Solution:

void queue::add( )

{ if((front= = 0 && rear = = 9)

(front= =rear+1)

cout<<”\nQueue Overflow”;

else if (rear= = -1)

{ front=rear=0;

cout<<”\nEnter the element to be inserted”;

cin>>data[rear];

}

else if(rear= =9)

{ rear=0;

cout<<”\nEnter the element to be inserted”;

cin>>data[rear];

}

else

{ rear++;

cout<<”\nEnter the element to be inserted”;

cin>>data[rear];

}

}

void queue::remove( )

{ if(front= = -1)

cout<<”\nQueue Underflow…”;

else

{ cout<<”\nThe element to be deleted”<

if(front= =rear)

front=rear=-1;

else if (front= =9)

front=0;

else

front++;

}

}

void queue::Delete(int ITEM )

{

}

Q.3. Write a function in C++ to perform a PUSH operation on a dynamically allocated stack

containing real number.

struct Node

{ float Number ;

Node *Link ;

} ;

class STACK

{ Node *Top ;

public :

STACK( ) {Top = NULL ;}

void PUSH( ) ;

void POP( ) ;

~STACK( ) ;

} ;

Solution:

struct Node

{ float Number ;

Node *Link ;

} ;

class STACK

{ Node *Top ;

public :

STACK( ) {Top = NULL ;}

void PUSH( ) ;

void POP( ) ;

~STACK( ) ;

} ;

void STACK::PUSH( )

{ Node *Temp;

Temp=new Node;

if(Temp= =NULL)

{

cout<<”\nNo memory to create the node…”;

exit(1);

}

cout<<”\nEnter the Number to be inserted: “;

cin>>Number;Temp

Link=Top;Temp

Top=Temp;

}

Q.4. Write the equivalent infix expression for a, b, AND, a, c, AND, OR.

Ans) a, b, AND, a, c, AND, OR

(a AND b), (a AND c), OR

(a AND b) OR (a AND c)



OUTSIDE DELHI . 2006

Q.1. Introduction class stack

{ int data[10] :

int top ;

public :

stack( ) { top = - 1; }

void push( ) ; //to push an element into the stack

void pop( ) ; //to pop an element from the stack

void Delete(int ITEM) ; //To delete all elements which are equal to ITEM.

} ;

Complete the class with all function definitions. Use another stack to transfer data temporarily.

Solution:

void stack::push( )

{ if(top>=9)

cout<<”Stack Overflow…”;

else

{ top++;

cout<<”\nEnter the element to be inserted…”;

cin>>data[top];

}

}

void stack::pop( )

{ if(top= =-1)

cout<<”\nStack Underflow”;

else

{ cout<<”\nThe element to be deleted = “<

top--;

}

}

void stack::Delete(int ITEM)

{

}

Q.2. Write a function in C++ to perform Insert operation in dynamically allocated Queue containing

names of students.

struct NODE

{ char Name[20];

NODE *Link;

};

Solution:

class Queue

{

NODE *front,*rear;

public:

Queue( )

{ front = rear = NULL; }

void Insert( );

void Delete( );

void Display( );

};

void Queue::Insert( )

{

NODE *ptr;

ptr=new NODE;

if(ptr= = NULL)

{

cout<<”\nNo memory to create a new node….”;

exit(1);

}

cout<<”\nEnter the name….”;

Name);gets(ptr

Link=NULL;ptr

if(rear= = NULL)

front=rear=ptr;

else

{

Link=ptr;rear

rear=ptr;

}

}

Q.3. Write theequivalent infix expression for 10, 3, *, 7, 1, --,*, 23, +

Solution:

10, 3, *, 7, 1, - , *, 23, + This is in Postfix form( ie Operator will come after the operand(s));.

Infix form means Operator must come in between the operands.

10, 3, *, 7, 1, - , *, 23, +

Prefix: 10 * 3, 7 – 1,*,23,+

(10 * 3) * (7 – 1),23,+

(10 * 3) * (7 – 1) + 23

DELHI : 2005

Q.1. Write a function in C++ to perform a PUSH operation in a dynamically allocated stack considering the following :

struct Node

{

int X,Y ;

Node *Link ;

} ;

class STACK

{

Node *Top ;

public :

STACK( ) {Top = Null ;}

void PUSH( ) ;

void POP( ) ;

~STACK( ) ;

} ;

Solution:

struct Node

{

int X,Y ;

Node *Link ;

} ;

class STACK

{

Node *Top ;

public :

STACK( ) {Top = NULL ;}

void PUSH( ) ;

void POP( ) ;

~STACK( ) ;

} ;

void STACK::PUSH( )

{

Node *Temp;

Temp=new Node;

if(Temp= =NULL)

{

cout<<”\nNo memory to create the node…”;

exit(1);

}

cout<<”Enter the value of X and Y”;

cin>>XTemp>>Y;Temp

Link=Top;Temp

Top=Temp;

}

}

Q.2. Evaluate the following postfix notation of expression : 10 20 + 25 15 - * 30 /

Ans:

Children, Try this answer as an assignment.





OUTSIDE DELHI : 2005

Q.1. Write a function in C++ to perform a DELETE operation in a dynamically allocated queue considering the following description .

struct Node

{ float U, V ;

Node *Link ;

} ;

class QUEUE

{

Node *Rear, *Front ;

public :

QUEUE( ) {Rear = NULL ; Front = NULL ;}

void INSERT( ) ;

void DELETE( ) ;

~ QUEUE( ) ;

} ;

Solution: void Queue::DELETE( )

{

NODE *temp;

if(front= = NULL)

cout<<”\nQueue Underflow”;

else

{

cout<<”\nThe value of U of the element to delete: “<

cout<<”\nThe value of V of the element to delete: “<

temp=Front;

Link;Front=Front

delete temp;

}

}

Q.2. Evaluate the following postfix notation of expression : 20 10 + 5 2 * - 10 /

Ans:

Children, Try this answer as an assignment.

2004

Q.1. Obtain the postfix notation for the following infix notation of expression showing the contents of

the stack and postfix expression formed after each step of conversion : (P—Q)/(R*(S—T)+U)

Ans:

((P-Q)/((R*(S-T))+U)) S.No Symbol Scanned Stack Expression Y

1 ( (

2 ( ( (

3 P ( ( P

4 - ( ( - P

5 Q ( ( - P Q

6 ) ( P Q -

7 / ( / P Q -

8 ( ( / ( P Q -

9 ( ( / ( ( P Q -

10 R ( / ( ( P Q - R

11 * ( / ( ( * P Q - R

12 ( ( / ( ( * ( P Q - R

13 S ( / ( ( * ( P Q - R S

14 - ( / ( ( * ( - P Q - R S

15 T ( / ( ( * ( - P Q - R S T

16 ) ( / ( ( * P Q - R S T -

17 ) ( / ( P Q - R S T - *

18 + ( / ( + P Q - R S T - *

19 U ( / ( + P Q - R S T - * U

20 ) ( / P Q - R S T - * U +

21 ) P Q - R S T - * U + / Postfix Form: PQ-RST-*U+/

Q.2. Define member functions queins( ) to insert nodes and quedel ( ) to delete nodes of the linked list implemented class queue, where each node has the following structure.

struct node

{ char name[20] ;

int age ;

node *Link ;

} ;

class queue

{ node *rear, *front ;

public :

queue( ) { rear = NULL; front = NULL} ;

void queins( ) ;

void quedel( ) ;

} ;

Solution:

void queue::queins( )

{ node *ptr;

ptr=new node;

if(ptr= = NULL)

{

cout<<”\nNo memory to create a new node….”;

exit(1);

} cout<<”\nEnter the name….”;

name);gets(ptr

cout<<”\nEnter the age…”;

cin>>age;ptr

Link=NULL;ptr

if(rear= = NULL)

front=rear=ptr;

else

{

Link=ptr;rear

rear=ptr;

}

}

void queue::quedel( )

{ node *temp;

if(front= = NULL)

cout<<”Queue Underflow”;

else

{ cout<<”\nThe name of the element to delete: “<

cout<<”\nThe age of the element to delete: “<

temp=front;

Link;front=front

delete temp;

}

}

DELHI 2003

Q.1. Evaluate the following postfix expression using a stack and show the contents of stack after execution of each operation: 20, 45, +, 20, 10, -, 15, +, *

Ans:

Children, Try this answer as an assignment.

Q.2. Consider the following portion of a program, which implements passengers Queue for a train. Write the definition of function. Insert (whose prototype is shown below); to insert a new node in the queue with required information.

struct NODE

{ long Ticketno;

char PName[20];//Passengers Name

NODE * Next;

};

class Queueoftrain

{ NODE * Rear, * Front;

public :

Queueoftrain( ) { Rear = NULL; Front = NULL:}

void Insert( );

void Delete( );

~Queueoftrain( );

} ;

Solution:

void Queueoftrain::Insert( )

{ NODE *ptr;

ptr=new NODE;

if(ptr= = NULL)

{

cout<<”\nNo memory to create a new node….”;

exit(1);

}

cout<<”\nEnter the Ticket Number….”;

cin>>Ticketno;ptr

cout<<”\nEnter the Passenger Name..”;

PName);gets(ptr

Next=NULL;ptr

if(rear= = NULL)

front=rear=ptr;

else

{

Next=ptr;rear

rear=ptr;

}

}

DELHI . 2002

Q.1. Given the following class,

char *msg[ ]={“over flow”,”under flow”};

class Stack

{ int top; //the stack pointer

int stk[5]; //the elements

void err_rep(int e_num)

{ cout<

}

public:

void init( )

{ top=0;

} //initialize the stack pointer

void push(int); //put new value in stk

void pop( ); //get the top value.

};

Define pop outside the Stack. In your definition take care of under flow condition. Function pop

should invoke err_rep to report under flow.

Solution:

void Stack::pop( )

{

}

Q.2. Change the following infix expression into postfix expression. (A+B)*C+D/E-F .

Ans:

Children, Try this answer as an assignment.

DELHI : 2001

Q.1.Write an algorithm to convert an infix expression to postfix expression.

Ans:

The following algorithm transforms the infix expression X into its equivalent postfix expression Y. The algorithm uses a stack to temporarily hold operators and left parentheses. The postfix expression Y will be constructed from left to right using the operands from X and the operators which are removed from STACK. We begin by pushing a left parenthesis onto STACK and adding a right parenthesis at the end of X. The algorithm is completed when STACK is empty.

Algorithm: Suppose X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Y.

1. Push “(“ onto STACK, and add “)” to the end of X.

2. Scan X from left to right and REPEAT Steps 3 to 6 for each element of X UNTIL the STACK is empty.

3. If an operand is encountered, add it to Y.

4. If a left parenthesis is encountered, push it onto STACK.

5. If an operator is encountered, then:

(a) Repeatedly pop from STACK and add to Y each operator(on the top of STACK) which has the same precedence as or higher precedence than operator.

(b) Add operator to STACK. /* End of If structure */

6. If a right parenthesis is encountered, then:

(a) Repeatedly pop from STACK and add to Y each operator (on the top of STACK) until a left Parenthesis is encountered.

(b) Remove the left parenthesis. (Do not add the left parenthesis to Y). /* End of If structure */



Chapterwise Revision Questions - Computer Science XII (083)

Question 1. REVISION TOUR C++, OOPs Concepts & POINTERS




Q 1 WHAT WIIL BE OUTPUT OF FOLLOWING PROGRAM? 1

#include

# include

void main()

{

clrscr();

int sum(int(*)(int),int);

int square(int);

int cube(int);

cout<

cout<

getch();

}

int sum(int(*ptr)(int k),int n)

{

int s=0;

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

{

s+=(*ptr)(i);

}

return s;

}

int square(int k)

{ int sq;

sq=k*k;

return k*k;

}

int cube(int k)

{

return k*k*k;

}



ANS 1> OUTPUT WILL BE

30

100





Q2>How many times will the following program will print “examination”? 1

#include

void main( )

{

while(1)

{

cout<<”examination”

}

}



ANS 2>Unless ^C is pressed ,program will print “examination” infinitely.



Q 3> Will the following programs produce same output? 2

Program 1

# include

# include

void main()

{

int x,y=1;

if((x=y)!=0)

cout<

state state1(temp), state2("Mumbai"), state3("Nagpur"), s1,s2;

s1.replace(state1,state2);

s2.replace(s1,state3);

s1.display();

s2.display();

getch();

}



Ans.: DelhiMumbai

DelhiMumbaiNagpur

Q.3 Find out errors in the following program:-

class number

{

int x=10;

float y;

number(){ x=y=10;}

public:

number(number t)

{

x=t.x; y=t.y;

}

~ (){ cout<<"Object destroyed ";}

}

main()

{

number a1, a2(a1);

}

Ans.: error: int x=10; // class member can not be initialized in the class.

Constructor should be declared in public section of class.

Reference operator is missing in the definition of copy constructor

In destructor class name is missing.

Semicolon is missed after the definition of class.



Q.4 What is the difference between nesting or containership and inheritance? Explain with example?

Ans.: Containership or Nesting: When a class contains object of other class type as its data member is known as containership or nesting.

Inheritance: Inheritance is the process of creating new class by reusing the properties of an existing class by accessing them depending on different visibility mode. The new class is called derived and existing class is called base class.



Q.5 What will be the output of the program?

#include

class base

{ public:

void display()

{

cout<<"It is a base class "<

}

};

class derived: public base

{

public:

void display()

{ cout<<"It is a derived class "<

};

main()

{

derived ob1;

ob1.display();

}

Ans:- The output will be:

It is a derived class.

Q.6 Define a class named Tour in C++ with following description? 4

Private members:

tcode integer (Ranges 6 - 10)

adults, children, distance integer

totalfare float

AssignFare( ) A function which calculates and assign the value to data member

totalfare as follows:-

- For adults Fare Distance

Rs. 500 >=1500

And fare get reduced by 25% if distance is < 1500.

- For Children

For every child a fixed Rs. 50 is charged as fare.

Public members:

• A constructor which initialized initialize all data members with 0

• Function EnterTour() to input the values of the data members tcode, adults, children and call to AssignFare function.

• Function ShowTour() to print all the details of object of Travel type.

Ans.

class tour

{

int tcode,adults,children,distance;

float totalfare;

void assignfare()

{ float cfare=50, afare=1500;

if(distance<1500)

afare=afare-(afare*25/100);

totalfare=(children*cfare)+(adults*afare);

}

public:

travel()

{ tcode=adults=children=distance=totalfare=0; }

void entertour()

{

do

{ cout<<"Enter tcode between 6-10 ";

cin>>tcode;

if (tcode<6

tcode>10)

cout<<"Invalid tcode "<

}while(tcode<6

tcode>10);

cout<<"Enter children, adults, distance";

cin>>children>>adults>>distance;

assignfare();

}

void showtour()

{ cout<<"tcode:"<

cout<<"children:"<

cout<<"adults :"<

cout<<"distance:"<

cout<<"total fare:"<

}

};

Q.7. Define a class named Admission in C++ with following description? 4

Private members:

admno integer (Ranges 10-1500)

name string of 20 characters

cls integer

fees float

Public members:

A constructor which initialized admno with 10, name with “NULL”, cls with 0 & fees with 0

Function getdata() to read the object of Admission type.

Function putdata() to print the details of object of admission type.

Function draw_nos() to generate the admission no. randomly to match with admno and display the detail of object.

Ans.: class admission

{ int admno;

char name[20];

int cls;

float fees;

public:

admission()

{ admno=10;

strcpy(name,"NULL");

cls=0;

fees=0;

}

void getdata()

{

do

{ cout<<"Enter admno between 10-1500 ";

cin>>admn

if (admno<10

admno>1500)

cout<<"Invalid admission no !"<

}while(admno<10

admno>1500);

cout<<"Enter name ";

gets(name);

cout<<"Enter class and fees ";

cin>>cls>>fees;

}

void putdata()

{ cout<<"Admno :"<

cout<<"Name :"<

cout<<"Class :"<

cout<<"Fees :"<

}

void draw_nos()

{ int num;

randomize();

num=random(1491)+10;

if (num==admno)

putdata();

}

};

Q.8

Class testmeout

{ int rollno;

public:

~testmeout() //Function 1

{ cout<

}

testmeout() //Function 2

{ rollno=1;

cout<

}

testmeout(int n, char name[]) //Function 3

{ rollno=n;

cout<

}

testmeout(testmeout & t);//function 4

void mywork() //Function 5

{ cout<

}

};



i) In object oriented programming, what is Function 1 referred as and when does it get invoked?

ii) In object oriented programming, what is Function 2 referred as and when does it get invoked?

iii) In object oriented programming, what is Function 3 referred as and when does it get invoked?

iv) Write a statement so that function 3 gets executed?

Complete the definition of function 4

v) What will be the output of the above code if its main function definition is as given below (assumed the definition of Function 4 is completed ) :

main()

{testmeout ob1;

ob1.mywork();

}

vi) Which feature of object oriented programming is demonstrated using Function 2, Function 3 and Function 4 in the above class testmeout?

vii) What is the scope of data member (rollno) of class testmeout? What does the scope of data members depend upon?

Ans:-

i) It is referred as destructor. It is automatically invoked when an object of concerned class goes out of scope.

ii) It is referred as constructor. It is automatically invoked when an object of concerned class is declared / created.

iii) It is parameterized constructor and gets invoked when an object of concerned class is created / declared with the matched parameters.

iv) testmeout ob1(15, “Vicky”);

testmeout (testmeout & t) { rollno=t.rollno;}

v) output will be :

1 is appearing for examination

1 is attempting questions

1 is Leaving examination hall

vi) It is constructor overloading. It shows Polymorphism feature of the OOP.

vii) The rollno member of object can only be used by the concerned object where that object is declared. Its scope basically depends upon the concerned object.

Data Structure – Array, link List, Stack & Queue



Q. 1 Given two arrays of integers A and B of sizes M and N respectively. Write a function named MIX() which will produce a third array named C, such that the following sequence is followed :

All even numbers of A from left to right are copied into C from left to right.

All odd numbers of A from left to right are copied into C from right to left

All even numbers of B from left to right are copied into C from left to right.

All odd numbers of B from left to right are copied into C from right to left

A, B and C are passed as arguments to MIX().

e.g. : A is {3,2,1,7,6,3} and B is {9,3,5,6,2,8,10}, the resultant array C is {2,6,6,2,8,10,5,3,9,3,7,1,3}

Solution : void mix (int A[], int B[], int n, int m)

{ int c[20],i=0,j=0,k=0,l;

L=m+n-1;

while (i

{ if (A[i]%2==0)

C[k++] = A[i++];

else C[l--] = A[i++];

}

While (j

{ if (B[j]%2==0)

C[k++]=B[j++];

else C[l--]=B[j++];

}

cout<<” \nThe elements of an array C is :”;

for (i=0;i

cout<<”\n”<

}

void main()

{ int A[j= { 3,2,1,7,6,3}, B[]= {9,3,5,6,2,8,10};

Mix(A,B,6,7);

}



Q. 2. Suppose an array P containing float is arranged in ascending order. Write a user defined function in C++ to search for one float from P with the help of binary search method. The function should return an integer 0 to show absence of the number and integer 1 ti show presence of the number in the array. The function should have the parameters as (1) an array (2) the number DATA to be searched (3) number of element N.

Solution : int bsearch (float P[10], float DATA, int N)

{ int beg =0, end = N-1,mid, pos = -1;

while(beg<=end)

{ mid = ( beg+ end )/2;

if (P[mid] == DATA)

{ pos =mid +1;

Break;

}

else if (item > AE[mid] )

beg = mid +1;

else

end = mid-1;

}

return ((pos==-1)? 0:1);

}

Q. 3 Write a function in C++ which accepts an integer array and its size as arguments / parameters and assign the elements into a two dimensional array of integers in the following format :

If the array is 1, 2,3,4,5,6 If the array is 1,2,3



The resultant 2D array is given below The resultant 2D array is

1 2 3 4 5 6 given below

1 2 3 4 5 0 1 2 3

1 2 3 4 0 0 1 2 0

1 2 3 0 0 0 1 0 0

1 2 0 0 0 0

1 0 0 0 0 0



Solution :

void func(int arr[], int size)

{ int a2[20][20], i, j;

for (i=0;i

{ for (j=0;j

{ if ((i+j) >=size)

a2[i][j]=0;

else a2[i][j]= arr[j];

cout<

}

Cout<<”\n”;

}

}



Q-4 Write a function in C++ to perform a PUSH operations on a dynamically allocated stack containing real number?

Ans-

struct Node

{

float data;

Node * next;

};

Void push (Node*Top, float num)

{

Node*nptr = new Node;

nptr -> data = num;

nptr -> next = NULL;

if(Top == NULL)

Top = nptr;

else

{

nptr -> next = Top;

Top = nptr;

}

}









Q-5 Each node of a STACK containing the following information, in addition to required pointer field:

Roll no. of the student

Age of the student.

Gve the structure of node for the linked stack in question.

TOP is a pointer to the topmost node of the STACK. Write the following function:

PUSH() – TO push a node in to the stack which is allocated dynamically.

POP() – Te remove a node from the stack and to release the memory.

Ans-



struct STACK

{

int rollno, age;

STACK*next;

} *top, *nptr, *ptr;

void pop()

{

if (!pop) { cout << ”\nUnderflow!!” ; exit(1); }

else

{ cout << ’\n’ << top -> rollno << ’\t’ << top -> age;

ptr = top;

top = top -> next;

delete ptr;

}

}

Void push()

{

nptr = new stack; //allocate memory

cout << “\n Enter roll number and age to be inserted : “ ;

cin >> nptr-> rollno >> nptr->age ;

nptr -> next = NULL;

if (!top) top = nptr;

else

{

ptr -> next = top;

top = nptr

}

}



Q.6 Write a function MAX in C++ which will return the Largest number stored in a two dimensional array of Integers.

Ans

#include

#include

const r = 100, c = 100;

// Function to find the largest integer in a two-dimensional array

int MAX(int a[r][c], int m, int n)

{

int max = 0;

for(int i= 0;i

for(int j= 0;j

{

if (a[i][j] >max)

max = a[i][j];

}

return max;

}

void main()

{

clrscr();

int ar[r][c];

int rr, cc, mx = 0;

int i, j;

cout << "Enter no. of row : ";

cin >> rr;

cout << "Enter no. of column : ";

cin >> cc;

cout << "Enter the array elements : ";

for (i=0; i

for (j = 0; j

cin >> ar[i][j];

mx = MAX(ar, rr, cc);

cout << "Largest element is : " << max;

}





Q.7 Write a function in c++ which accepts a 2D array of integers and its size as arguments and displays the elements which lies on diagonals.

[ Assuming the2D array to be a square matrix with odd dimensions , i.e 3x3, 5x5,7x7, etc ]



Example if the array content is

5 4 3

6 7 8

1 2 9

Output through the function should be

Diagonal one : 5 7 9

Diagonal two : 3 7 1 .



Ans



// Function to display the elements which lie on diagonals

#include

#include

#include

const M = 10;

const N = 10;

void display_diagonals(int MATRIX[M][N], int r, int c)

{

clrscr();

// Finding the diagonal from left index to right

cout << "Diagonal One : ";

for(int i=0; i

for(int j=0; j

{

cout << MATRIX[i][j] << " ";

i++;

}

cout << endl;

// Finding the diagonal from right index to left

cout << "Diagonal Two : ";

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

{

for(int j=c-1; j>=0; j--)

{

cout << MATRIX[i][j] << " ";

i++;

}

}

getch();

}

void main()

{

int MATRIX[M][N];

int i, j;

int r, c;

cout << "Enter total no. of rows: ";

cin >> r;

cout << "Enter total no. of columns: ";

cin >> c;

if ((r == c) && ((r%2==1) && (c%2==1)))

{

cout << "Input steps";

cout << "\n\Enter the element in the array\n";

for(i=0; i

for(j=0; j

{

cin >> MATRIX[i][j];

}

}

else

return;

display_diagonals(MATRIX, r, c);

}























Q.8 Write a function in C++ which accepts a 2D array of integers and its size as arguments and displays the elements of the middle row and the elements of middle column.

Example if the array content is

3 5 4

7 6 9

2 1 8

Output through the function should be:

Middle row: 769 Middle column: 5 6 1

Ans

// Function to display the elements which lie on middle of row and column

#include

#include

#include

const M = 10;

const N = 10;

void display_RowCol(int Array[M][N], int r, int c)

{ int row = r / 2;

int col = c / 2;

// Finding the middle row

cout << "Middle Row : ";

for(int j=0; j

cout << Array[row][j] << " ";

cout << endl;

// Finding the middle column

cout << "Middle Column : ";

for(j=0; j

cout << Array[j][col] << " ";

getch();

}

void main()

{ int Array[M][N];

int i, j;

int r, c;

cout << "Enter total no. of rows: ";

cin >> r;

cout << "Enter total no. of columns: ";

cin >> c;

if ((r == c) && ((r%2==1) && (c%2==1)))

{ cout << "Input steps";

cout << "\n\Enter the element in the array\n";

for(i=0; i

for(j=0; j

{ cin >> Array[i][j]; }

}

else

{ cout << "Input row and column not valid";

getch();

return;

}

display_RowCol(Array, r, c);

}

Q. 9. Declare a stack using array that contains int type numbers and define pop and push function using C++ Syntax.

Ans

#include

#include

#include

#include

#include

#define MAX 100 // Shows maximum array length

int stack[MAX]; // Declares array global variable

int top; // Declares integer top

// Function prototypes of add stack, delete stack, and

// show stack in array implementation

void push(int stack[], int val, int &top); // Add stack

int pop(int stack[], int &top); // Delete stack

void show_Stack(int stack[], int top); // Show stack

void main()

{

int choice, val;

char opt = 'Y'; // To continue the do loop in case

top = -1; // Initialization of Queue

clrscr();

do

{

cout << "\n\t\t Main Menu";

cout << "\n\t1. Addition of Stack";

cout << "\n\t2. Deletion from Stack";

cout << "\n\t3. Traverse of Stack";

cout << "\n\t4. Exit from Menu";

cout << "\n\nEnter your choice from above -> ";

cin >> choice;

switch (choice)

{

case 1:

do

{ cout << "Enter the value to be added in the stack ";

cin >> val;

push(stack, val, top);

cout <<"\nDo you want to add more elements ? ";

cin >> opt;

} while (toupper(opt) == 'Y');

break;

case 2:

opt = 'Y'; // Initialize for the second loop

do

{ val = pop(stack, top);

if (val != -1)

cout << "Value deleted from statck is " << val;

cout <<"\nDo you want to delete more elements?";

cin >> opt;

} while (toupper(opt) == 'Y');

break;

case 3:

show_Stack(stack, top);

break;

case 4:

exit(0);

}

}

while (choice != 4);

}

// Function body for add stack with array

void push(int stack[], int val, int &top)

{

if (top == MAX - 1)

{ cout << "Stack Full ";

}

else

{ top = top + 1;

stack[top] = val;

}

}

// Function body for delete stack with array

int pop(int stack[], int &top)

{

int value;

if (top < 0)

{ cout << "Stack Empty ";

value = -1;

}

else

{ value = stack[top];

top = top - 1;

}

return (value);

}

// Function body for show stack with array

void show_Stack(int stack[], int top)

{

int i;

if (top < 0)

{ cout << "Stack Empty";

return;

}

i = top;

clrscr();

cout << "The values are ";

do

{ cout << "\n" << stack[i];

i = i - 1;

}while(i >= 0);

}

Q.10. Define functionstackpush( ) to insert nodes and stack pops ( ) to delete nodes . for a linked list implemented stack having the following structure for each node

struct Node

{

Char name [ 20 ]

Int age ;

Node * link ;

};

Class stuck {

Node * top ;

Public

Stack ( ) { top = null ;} ;

Void stackpush ( );

Void stack pop ( ) ;

}



Ans

#include

#include

#include

#include

#include

// Declares a stack structure

struct node

{

char name[20];

int age;

node *link;

};

class stack

{

node *top;

public :

stack() { top = NULL; }

void stackpush(); // Add stack

void stackpop(); // Delete stack

void show_Stack(); // Show stack

};

// Function body for adds stack elements

void stack::stackpush()

{

int val;

node *temp;

temp = new node;

cout << "Enter name : ";

gets(temp->name);

cout << "Enter age : ";

cin >> temp->age;

temp->link = NULL;

if(top ==NULL)

top = temp;

else

{

temp->link = top;

top = temp;

}

}

// Function body for delete stack elements

void stack::stackpop()

{

node *temp;

if (top == NULL)

{

cout << "Stack Empty ";

}

else

{

temp = top;

top = top->link;

temp->link = NULL;

delete temp;

}

}

// Function body for show stack elements

void stack :: show_Stack()

{

node *temp;

temp = top;

clrscr();

cout << "The values are \n";

while (temp != NULL)

{

cout << "\n" << temp->name << "\t" << temp->age;

temp = temp->link;

}

}

// Main programming logic

void main()

{



int choice;

stack STACK;

char opt = 'Y'; // To continue the do loop in case

clrscr();

do

{

cout << "\n\t\t Main Menu";

cout << "\n\t1. Addition of Stack";

cout << "\n\t2. Deletion from Stack";

cout << "\n\t3. Traverse of Stack";

cout << "\n\t4. Exit from Menu";

cout << "\n\nEnter your choice from above ";

cin >> choice;

switch (choice)

{

case 1:

do

{

STACK.stackpush();

cout<<"Do you want to add more elements?";

cin >> opt;

} while (toupper(opt) == 'Y');

break;

case 2:

opt = 'Y'; // Initialize for the second loop

do

{

STACK.stackpop();

cout<<"Do you want to delete more element?";

cin >> opt;

} while (toupper(opt) == 'Y');

break;

case 3:

STACK.show_Stack();

break;

case 4:

exit(0);

}

}

while (choice != 4);

}











































DATA FILE HANDLING



Q1, Assuming the class Vehicle as follows:

Class vehicle

{ char vehicletype[10];

int no_of wheels;

public:

void getdetials()

{ gets(vehicletype);

cin>>no_of_wheels;

}

void showdetails()]

{ cout<<”Vehicle Type”<

cout<<”Number of Wheels=”<

}

}

Write a function showfile() to read all the records present in an already exiting binary file SPEED.DAT and display them on the screen ,also count the number of records present in the file.

Answer:

Void showfile()

{ ifstream fin;

fin.open(“SPEED.DAT”,ios::in
ios::binary);

vehicle v1;

int count=0;

while (!fin.eof())

{ fin.read((char *)&v1,sizeof(v1));

count++;

v1.showdetails();

}

cout<<”Total number of records are “<

}

Q2. Write a program that prints a text file on the printer.

Answer:-

#include

#include

#include

int main()

{ char filename[13], ch;

cout<<”enter the text file name :”;

cin.getline(filename,13);

ifstream fin;

fin.open(filename);

if(!fin)

{cerr<<”\nFile can’t be opened !\n”;

exit(-1);

}

ofstream fout;

fout.open(“PRN”);

while(fin.get(ch)!=0)

fout.put(ch);

return 0;

}

Q3. Write a c++ program ,which initializes a string variable to the content.”Time is a grat teacher but unfortunately it kills all its pupils.Berlioz”and output the string one character at a time to the disk file OUT.TXT .You have to include all the header files required.

Answer:

#include

Int main()

{

ofstream fout(“OUT.TXT”);

Char*str=” Time is a grat teacher but unfortunately it kills all its pupils.Berlioz”;

Int i=0;

If(!fout)

{

cout<<”File cannot be opened “;

return 0;

}

While (str[i]!=’\0’)

{

fout<

i++;

}

fout.close();

}



Q4. Write a program that display the size of a file in bytes.

Answer:

#include

#include

#include

#include

int main()

{

char filename[13];

clrscr();

cout<”Enter Filename:\n”;

cin.getline(filename,13);

ifstream infile(filename);

if(!infile)

{

cout>>”sorry ! Can not open “<

Exit(-1);

}

int no_bytes=0;

char ch;

while(cin.get(ch))

{

no_bytes ++;

}

cout<<”File Size is”<

return 0;

}

Q5. What will be the output produced by the following code?

Answer:

#include

#include

#include

#include

int main()

{

clrscr()

char filename[13];

cout<<”Enter Filename:”;

cin.getline(filename,13);

ifstream in(filename);

if(!in)

{cout<<”Cannot open input file!\n”;

return (0)

}

Char str[255];

While(in)

{in.getline(str,255);

Cout<

}

in.close();

return 0;

}



Thursday, February 4, 2010

CBSE – Class XII Computer Science (083) Question- Answers for Viva

CBSE – Class XII Computer Science


Question-Answers for Viva

Classes:

1. What are inline member functions?

Ans. Functions defined inside a class are inline.

2. What is the difference between ordinary functions and inline functions?

Ans. No function call is made to inline functions as the source code is copied to the program during compilation whereas in ordinary functions, the control is switched over to the function block when function is called.

3. What are the situations where the inline functions do not work?

Ans. Inline functions does not work in the following situations

a. functions with return values,or having switch, goto, or loop

b. functions containing static variables

c. a recursive function

d. function having return statement (even if it does not return values)

4. What are the basic differences between a structure and a class?

Ans. Structure has only data members whereas class has both data member and member functions. By default all members of a structure are public whereas all members of a class are private by default.

5. What is a friend of a class?

Ans. Any ordinary function (non-member of a class) which has access privileges to the private members of a class are called friends of a class.

6. Which are the three types of (categories of ) a class function?

Ans. Accessor function – which can only access the data members(not edit it), mutator function – which can manipulate the data members (getdata(),calculate()), manager function – specific functions (constructor, destructor)

7. Explain Encapsulation, Data hiding, Data Abstraction with reference to classes.

8. What must be done to make the static data member of a class work?

Ans. Declaration within class and definition outside the class

9. What is the difference between static member function and ordinary member functions:

Ans. Static function of a class can access only the other static members of a class. Static function of a class is invoked by using the class name instead of object name.

10. How does the memory allocation for member functions and data members take place?

Ans. Member functions are created and placed in memory only once when the class is defined. The memory is allocated for objects’data members when the objects are declared. All objects share the same member functions.

11. Name the methods through which polymorphism is exhibited in C++?

Ans. Through operator overloading, function overloading and virtual functions.

12. What are overloaded functions?

Ans. Functions having the same name but which differs in number of type of arguments is called overloaded functions. It has nothing to do with return types( data type of functions)

13. What contributes to function overloading – function signatures or return type of function – Ans. function signature

14. Name the various types of constructors- default , parameterized, copy constructor

15. How is a copy constructor called ? Ans – It is called by call by reference only.

16. What is default constructor ?

Ans. A constructor with no arguments or all arguments having default values.

17. What are the uses of scope resolution?

Ans- used to defined methods of a class outside the class, to unhide global variable having the same name as the local variable in a block

18. What do you mean by temporary instance of a class?

Ans. Objects created for the purpose of execution only. …..

19. The differences between constructors and destructor are:

Ans. constructors can take arguments but destructor can't , constructors can be overloaded but destructors can't be overloaded.

20. Write a statement in C++ to prove that even primitive data types have constructors . Ans – int k(2).

21. What are the privileges of friend function of a class- to access the private and protected members of a class

22. What happens when constructor functions are invoked – objects are created.



Revision

23. How many ways of representing an integer – decimal, octal and hexadecimal

24. Which is the standard library –iostream.h

25. Difference between goto and gotoxy – goto is C++ statement and gotoxy () is a function defined in conio.h

26. Why is char treated as integer? –memory represents char in ASCII codes(numeric)

27. What is the length of escape sequences ? – 1 byte.

28. Name the only data type of which we cannot declare any variables?

Ans. Void

29. Name the fundamental data types of C++

Ans. Int, char, float, double, void.

30. What is the difference between Union and Enumeration?

Ans. Union is when two variables usually of different types sharing the same memory location ( any one occupies memory at a time). Enumeration is a way of declaring integer constants. Eg. Union share { int x, char y;};

Enum p{F, S, T};

31. Name an exit controlled and an entry controlled loop.

Ans. Exit controlled – do{…..}while(); Entry controlled – while(){….}

32. Which of the following is not a jump statement? Switch, goto, break, exit.

Ans. Switch.

33. Which of the following will work only in a loop – break, goto, continue, exit.

Ans. Continue and break.

34. Which is the default data type of C++? – Ans. Int

35. If a function does not have a data type specified which will be its datatype by default ? – Ans. Int

36. What is the default value of a static variable or global variable?

Ans – zero

37. Which are the storage class specifiers in C++?

Ans. Auto, register, extern, static.

38. A function that calls itself for its processing is known as – recursive function

39. Strings are character arrays. The last index of it contains the null-terminated character – ‘\0’.

40. What is the only function all C++ programs must contain? – main()

41. The directives for the preprocessors begin with - #

42. Differences between ‘a’ and “a”- ‘a’ is character of I byte whereas “a” is a string of 2 bytes.

43. What is the difference between int K[2] and int K(2) ? – first is in integer array of size 2 whereas second is declaring a variable K with initial value 2.

44. Differences between abort() and exit() – abort()- aborts “abnormal termination” exit()- closes all files and writes the buffered output before termination.

45. biggest number that can be represented by – int (32,767) and unsigned int (65,535)

46.







Structure:

47. What is the difference between a structure and an array?

Ans. Structures are heterogeneous collection of data whereas arrays are homogenous collection of data. Members of a structure are referred to by dot operator whereas array elements are referred to by subscript values.

48. What is the condition of assigning one structure to another?

Ans. Both structures must be of the same type ( same tag name)

49. What is the difference between typedef and reference variable?

Ans. Typedef creates an alternative name for a standard data type whereas reference creates an alternative name for a variable.

50. What is the function of #define?

Ans. Used to declare symbolic constants and macros.



Inheritance :

51. What is the default inheritance visibility mode? - private (if no visibility is specified it is private)

52. Can a derived class access the private members of the base class? If Yes, how? – can only access them through the nonprivate members.

53. What is inheritance graph? – derivation form multiple base classes.

54. what is order of constructor and destructor invocation in case of inheritance.?

When object of derived is inherited first the constructor of base class and then the derived class but for destructor first the destructor of derived class and then the base class is invoked.

55. What is the difference between protected and private members of class –

Ans. protected members are inheritable –private members are not.

56. What is the size of a class without any data member?

1 byte.

57. Which operator can be used prove that the private members of the base class are actually hidden in the derived (visible ) but not accessible?

Ans. Sizeof() operator on the object of the derived class will prove this.

58. What is Virtual Base classes?

Ans. In multiple bases classes are inherited.



59. What is containership or aggregation or containment?

Ans. When a class contains objects of other class types as its members it is called containership

60. Explain Has- A relationship, Is – A relationship.

Ans. When a class inherits from another class, the derived has a IS-A relationship with the base class. When a class contains the object of another class type – then the class containing the object has a HAS –A relationship with the contained class.

61. When a subclass is a base class of another class it is – multilevel inheritance.

62. What is function overriding ?

Ans. When a function of base class is re-defined in derived class – it is called function overriding.

63. What is the advantage of inheritance ? Ans – code reusability and saving of programming time.

64. Differentiate between ‘IS-A’ , ‘HAS-A’ and ‘HOLDS-A’ relationship in inheritance.

65. What are visibility modes ? Differentiate between them.

Ans. Private, protected, public.



File handling:

66. by default all files are treated as – text files in C++ ( not binary)

67. explain the file modes – ios::ate, ios::app, ios::noncreate….

68. difference between get() and getline().

69. use of seekg, seekp , tellg, tellp.

70. What is a stream ?

Ans. A sequence of bytes – flow of bytes into or out of a program.

71. Name the stream classes in C++ for I/O – ofstream, ifstream, fstream.

72. Name the member functions belonging to fstream class – get(), seekp(), seekg()

73. What is the difference between binary and text files?

74. Which functions can be used to manage binary files in C++ ?

Ans. Read and Write functions.

75. While writing class objects what is written to files data members or member functions?

Ans. Only data members.

76. How random access is is managed in C++?

Ans. Random access is managed by using seekg(), seekp(), tellg(), tellp() functions.









Pointers:

77. What is the difference between constant pointers and pointer to a constant?

78. What is the disadvantage of calling a function by reference?

Ans. When a function is called by reference method only variables can be passed not constants or expressions as in call by value method.

79. Which operator is used to refer to the object pointers(class and structure) ?

Ans. Arrow operators ->

80. What is this pointer? - explain

81. State two situations in which this pointer is not used in classes?

Ans. static member functions do not have this pointer and friend functions are not passed this pointer

82. Which are the two memory management operators in C++.

Ans. New and delete.

83. What is Static memory allocation and dynamic allocation ? static- at compilation time and dynamic at run time(using NEW operator)

84. What is life time of dynamically allocated memory variable ? – till it is de-allocated.

85. What is memory leak – if the no. of dynamically allotted memory variable are not deleted using delete –



Arrays ;

86. How are arrays passed to a function? – by reference/pointers and not by value method

87. What do you mean by traversal – processing all data elements of an array is called traversal.

88. What is the size of an array A [-10…..20] ? – 31

89. What is a vector – a numeric one dimensional array.

90. Which are the two ways of memory allocation of a 2-D array – row and column major

91. What is the precondition for a binary search ? – array should be sorted.

92. Stack is – LIFO and Queue is FIFO.

93. Which are the two types of queues ? circular and dequeue

94. Differentiate between arrays, stacks and queues.

95. Merits and demerits of linear and binary search.

Ans. Linear search – demerits takes more iterations to find an element especially if it is towards the end of array. Array need not be sorted.

96. If arr is an array of integer – is arr++ expression legal – why? (no- base address of a array cannot be changed)



UNIT –III SQL AND DATABASES

Q.1 Definition of database,relation,,DBMS,RDBMS, domain, field, tuple, attribute, cardinality, degree, primary key, alternate key.

Q.2 Operations on relation – selection, projection, union ,Cartesian product

Q.3.Difference between create table and alter table , create table and create view commands, delete table and drop table.

Q.4 Group functions – sum(), max(), min(), avg(), count()

Q.5 Differentiate between DDL and DML commands with example.



UNIT-IV BOOLEAN ALGEBRA

Q.1 Universal gates – NAND and NOR . Why are they called universal gates.

Q.2 Main theorems of Boolean Algebra, principle of duality



UNIT –V COMMUNICATION AND NETWORKING

Q.1 Definitions of network,Internet,switching techniques-Circuit, Message, Packet, Transmission media- Twisted, coaxial cable, optical fibre, micro wave, radio wave, satellite, buad rate, bandwidth,LAN,MAN,WAN,totplogies,hub,switch,router,bridge,repeater,firewall,cookies

Q.2 FULL forms of HTTP, FTP,TCP/IP,SLIP/PPP, MODEM,CDMA,WLL,SMS,WWW,URL