Friday, December 27, 2013

Quiz

Viva Questions


Question : Why main function is special in C++ ?
Answer : Whenever a C++ program is executed, execution of the program starts and ends at main(). The main is the driver function of the program. If it is not present in a program, no execution can take place.

Question : What is run-time error, logical error and syntax error?
Answer : Syntax error - The errors which are traced by the compiler during compilation, due to wrong grammar for the language used in the program, are called syntax errors.
For example, cin<<a; // instead of extraction operator insertion operator is used.
Run time Error - The errors encountered during execution of the program, due to unexpected input or output are called run-time error.
For example - a=n/0; // division by zero 
Logical Error - These errors are encountered when the program does not give the desired output, due to wrong logic of the program.
For example : remainder = a+b // instead of using % operator + operator is used.

Question : What is the role of #include directive in C++?
Answer : The preprocessor directive #include tells the complier to insert another file into your source file. In effect, #include directive is replaced by the contents of the file indicated.

Question : What is compiler and linker?
Answer : Compiler - It is a program which converts the program written in a programming language to a program in machine language.
Linker - It is a program which links a complied program to the necessary library routines, to make it an executable program.

Question : Why is char often treated as integer data type in C++ ?
Answer : The memory implementation of char data type is in terms of the number code. Therefore, it is said to be another integer data type.

Question : What is type conversion in C++ ?
Answer : When two operands of different data types are encountered in the same expression, the variable of lower data type is automatically converted to the data tpes of variable with higher data type, and then the expression is calculated.
For example: int a=98; float b=5; cout<<a/3.0; //converts to float type, since 3.0 is of float type.
cout<<a/b; // converts a temporarily to float type, since b is of float type, and gives the result 19.6.

Question : What is type casting in C++ ?
Answer : Type casting refers to the data type conversions specified by the programmer, as opposed to the automatic type conversions. This can be done when the compiler does not do the conversions automatically. Type casting can be done to higher or lower data type.
For example : cout<<(float)12/5; //displays 2.4, since 12 is converted to float type.

Question : What is the effect of absence of break in switch case in C++ ?
Answer : The break keyword causes the entire switch statement to exit, and the control is passed to statement following the switch.. case construct. Without break, the control passes to the statements for the next case. The break statement is optional in switch..case construct.

Question : In control structure switch-case what is the purpose of default in C++ ?
Answer : This keyword gives the switch..case construct a way to take an action if the value of the switch variable does not match with any of the case constants. No break statement is necessary after default case, since the control is already at the end of switch..case construct. The default is optional in case of switch..case construct.

Question : What is the difference between while and do-while loop?
Answer : While is an Entry Controlled Loop, the body of the loop may not execute even once if the test expression evaluates to be false the first time, whereas in do..while, the loop is executed at least once whether the condition holds true the first time or not. 

Question : What is the difference between call by value and call by reference in a user defined function in C++?
Answer : The value of the actual parameters in the calling function do not get affected when the arguments are passed using call by value method, since actual and formal parameters have different memory locations.
The values of the formal parameters affect the values of actual parameters in the calling function, when the arguments are passed using call by reference method. This happens since the formal parameters are not allocated any memory, but they refer to the memory locations of their corresponding actual parameters.

Question : What is preprocessor directive?
Answer : A preprocessor directive is an instruction to the complier itself. A part of compiler called preprocessor deals with these directives, before real compilation process. # is used as preprocessor directive in C++.

Question : What is the difference between local variable and global variable?
Answer : Local variables are those variables which are declared within a function or a compound statement and these variables can only be used within that function/scope. They cannot be accessed from outside the function or a scope of it's declaration. This means that we can have variables with the same names in different functions/scope. Local variables are local to the function/scope in which they are declared.
Global variables are those variables which are declared in the beginning of the program. They are not declared within a function. So, these variables can be accessed by any function of the program. So, global variables are global to all the functions of the program.

Question : What is the role of #define in C++?
Answer : It is a preprocessor directive to define a macro in a C++ program. Macros provide a mechanism for token replacement with or without a set of formal, function line parameters. For example :
#define PIE 3.1416
#define AVG(A,B,C) (A+B+C)/3

Question : What are the major differences between Object Oriented Programming and Procedural Programming?
Answer:
Object Oriented Programming
*Emphasis on data
*Follow bottom up approach in program design
*Concept of Data hiding prevents accidental change in the data
*Polymorphism, inheritance, Data Encapsulation possible
Procedural Programming
*Emphasis on doing things (function)
*Follow top-down approach in program design
*Due to presence of global variables, there are possibilities of accidental change in data.

Question : What are the basic concepts of OOP?
Answer :Data Abstraction, Data Hiding, Data Encapsulation, Inheritance and Polymorphism are the basic concepts of OOP.

Question : How is OOP implement in C++?
Answer : A class binds together data and its associated function under one unit thereby enforcing encapsulation.
The private and protected member remain hidden from outside world. Thus a class enforces data hiding
The outside world is given only the essential information through public members, thereby enforcing abstraction.

Question : What is abstract class?
Answer : A class with no instances (no objects) is known as abstract class.

Question : What is concrete class?
Answer : A class having objects is known as concrete class.

Question : What is a constructor? What are its features?
Answer : It is a member function of class with the following unique features. 
It has same name as the name of the class they belong to. 
It has no return type. 
It is defined in public visibility mode. 
It is automatically called & executed when an object is declared/created. 
Constructor can be overloaded.

Question : What does a destructor do?
Answer : A destructor deinitializes an object and deallocates all allocated resources.

Question : Define inheritance.
Answer : Inheritance is a process of creating new classes (derived classes) from existing classes (base classes). The derived classes not only inherit capabilities of the base class but also can add new features of own. The most important aspect of inheritance is that it allows reusability of code.

Question : Define Base class and derived class.
Answer : Base Class: A class from which another class inherits. 
Derived Class: A class inheriting properties from another class.

Question : What are the different forms of inheritance in C++ ?
Answer : Single level inheritance, Multilevel inheritance, Hierarchical inheritance, Multiple inheritance and Hybrid inheritance.
Question : What is virtual base class in C++ ? What is its significance?
Answer : Multipath inheritance may lead to duplication of inherited members from a grandparent base class. This may be avoided by making the common base class a virtual base class. When a class is made a virtual base class, C++ takes necessary care to see that only one copy of that class is inherited.

Question : How are binary files different from text files in C++?
Answer : A text file store information in ASCII characters. In text files, each line of text is terminated, with a special character known as EOL character. 
A binary file store information in the same format in which the information is held in memory. In binary file, there is no delimeter for a line.

Question : What is a stream? Name the streams generally used for file I/O.
Answer : A stream is a sequence of byte. 
ofstream: Stream class to write on files 
ifstream: Stream class to read from files 
fstream: Stream class to both read and write from/to files.

Question : Difference between get() and getline().
Answer : get() does not extract the delimeter newline character from input stream. On the other hand getline() does extract the delimeter newline character from the input stream so that the stream is empty after getline() is over.

Question : Difference between ios::app and ios::out.
Answer : The ios::out is the default mode of ofstream. With the mode of the file does not exist, it gets created but if the file exists then its existing contents get deleted.
The ios::app is output mode of ofstream. With the mode of the file does not exist, it gets created but if the file exists then its existing contents are retained and new information is appended to it.

Question : What is pointer?
Answer : Pointer is an address of a memory location. A variable, which holds an address of a memory location, is known as a Pointer variable (or Simply Pointer). For example int *P;

Question : What is pointer arithmetic ? How is it performed?
Answer : Some arithmetic operators can be used with pointers:
Increment and decrement operators ++, --
Integers can be added to or subtracted from pointers using the operators +, -, +=, and -=
Each time a pointer is incremented by 1, it points to the memory location of the next element of its base type.
If "p" is a character pointer then "p++" will increment "p" by 1 byte.
If "p" were an integer pointer its value on "p++" would be incremented by 2 bytes.

Question : Differentiate between static and dynamic allocation of memory.
Answer : In the static memory allocation, the amount of memory to be allocated is predicted and preknown. This memory is allocated during the compilation itself.
In the dynamic memory allocation, the amount of memory allocated is not known beforehead. This memory is allocated during run time as and when required.

Question : What do you understand by memory leaks? How can memory leaks be avoided?
Answer : Memory leak is a situation in which there lie so many orphaned memory blocks that are still allocated but no pointers are referencing to them.

Question : What is this pointer? What is its Significance?
Answer : The this pointer is an object pointer which points to the currently calling object, The this pointer is, by default, available to each called member function.

Question : What is the full form of LIFO? Give an example of LIFO list?
Answer : Full form of LIFO is LAST IN FIRST OUT. An example of LIFO list is stack. Stack is a linear data structure in which insertion and deletion of elements takes place only one end known as TOP.

Question : What is the full form of FIFO? What is FIFO list technically called?
Answer : Full form of FIFO is FIRST IN FIRST OUT. An example of FIFO list is Queue. Queue is a linear data structure in which insertion and deletion of elements takes place from two opposite ends rear and front respectively.

Question : What are the preconditions for Binary search to be performed on a single dimensional array?


Answer : Precondition for Binary search to be performed on a single dimensional array is array should be sorted.

Assignment 14: Data Structure - Stack and Queue

Data Structure - Stack and Queue

1
Complete the class with all function definitions for a stack
class stack
{
            int data[10];
            int top;
public :
            stack(){top=-1;}
            void push();
            void pop();
}
Question 2
Change the following infix expression postfix expression.                  
(A + B)*C+D/E-F
Question 3
Convert the expression (True && False) || !(False || True) to postfix expression. Show the contents of the stack at every step.
Question 4
Use a stack to evaluate the following postfix expression and show the content of the stack after execution of each operation. Don't write any code. Assume as if you are using push and pop member functions of the stack.
AB-CD+E*+ (where A=5, B=3, C=5, D =4, and E=2)
Question 5
Evaluate the following postfix expression using a stack and show the contents of stack after execution of each operation :
            50,40,+,18, 14,-, *,+
Question 6
Evaluate the following postfix expression using a stack and show the contents of stack after execution of each operation :
TRUE, FALSE, TRUE, FALSE, NOT, OR, TRUE, OR, OR, AND
Question 7
Complete the class with all function definitions for a circular queue
class queue
{
            int data[10];
            int front, rear;
public :
            queue(){front=-1;rear=-1}
            void add();
            void remove();
}
Question 8
Each node of a STACK contains the following information, in addition to required pointer field :
i) Roll number of the student
ii) Age of the student
Give the structure of node for the linked stack in question TOP is a pointer which points to the topmost node of the STACK. Write the following functions.
i) PUSH() - To push a node to the stack which is allocated dynamically
ii) POP() - To remove a node from the stack and release the memory.
Question 9
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();
};
Question 10
Give the necessary declaration of a linked list implemented queue containing float type values. Also write a user-defined function in C++ to delete a float type number from the queue.

Assignment 13: File Handling - Binary File

Question 1
Assuming the class EMPLOYEE given below, write functions in C++ to perform following:
(i) Write the objects of EMPLOYEE to a binary file.
(ii) Read the objects of EMPLOYEE from binary file and display them on screen.
class EMPLOYEE
{
            int ENO;
            char ENAME[10];
            public :
            void GETIT()
            {
                        cin >> ENO;
                        gets (ENAME);
            }
            void SHOWIT()
           {
                        cout <<ENO << ENAME <<endl;
            }
};
Question 2
Assuming the class Computer as follows :
class computer
{
            char chiptype[10];
            int speed;
            public:
                        void getdetails()
                        {
                                    gets(chiptype);
                                    cin>>speed;
                        }
                        void showdetails()
                        {
                                    cout<<“Chip”<<chiptype<<“ Speed= “<<speed;
                        }
};
Write a function readfile( ) to read all the records present in an already existing binary file SHIP.DAT and display them on the screen, also count the number of records present in the file.
Question 3
Given a binary file STUDENT.DAT, containing records of the following class Student type
class Student
{
            char S_Admno[lO];    //Admission number of student
            char S_Name[30];       //Name of student
            int Percentage;            //Marks Percentage of student
            public:
                        void EnterData()
                        {
                                    gets(S_Admno);
                                    gets(S_Name);
                                    cin>>Percentage;
                        }
                        void DisplayData()
                        {
                                    cout<<setw(12)<<S_Admno;
                                    cout<<setw(32)<<S_Name;
                                   cout<<setw(3)<<Percentage<<endl;
                        }
                        int ReturnPercentage()
                        {return Percentage;}
};
Write a function in C++, that would read contents of file STUDENT.DAT and display the details of those Students whose Percentage is above 75.
Question 4
Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg() and tellg() functions for performing the required task.
#include <fstream.h>
class Employee
{
            int Eno;
            char Ename[20];
            public:
            //Function to count the total number of records
            int Countrec();
};
int Item::Countrec()
{
            fstream File;
            File.open("EMP.DAT",ios::binary|ios::in);
            ______________________ //Statement 1
            int Bytes =______________________ //Statement 2
            int Count = Bytes / sizeof(Item);
            File.close();
            return Count;
}
Question 5
Write a function in C++ to add new objects at the bottom of a binary file "STUDENT.DAT", assuming the binary file is containing the objects of the following class.
class STUD
{
            int Rno;
            char Name[20];
            public:
            void Enter()
            {cin>>Rno;gets(Name);}
            void Display()
            {cout<<Rno<<Name<<endl;}
};
Question 6
Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekp() and seekg() functions for performing the required task.
#include <fstream.h>
class Item
{
            int Ino;
            char Item[20];
            public:
            //Function to search and display the content from a particular record number 
            void Search(int );
           //Function to modify the content of a particular record number
            void Modify(int);
 };
 void Item::Search(int RecNo)
{
            fstream File;
            File.open(“STOCK.DAT”,ios::binary|ios::in);
            ______________________ //Statement 1
            File.read((char*)this,sizeof(Item));
            cout<<Ino<<”==>”<<Item<<endl;
            File.close();
}
void Item::Modify(int RecNo)
{
            fstream File;
            File.open(“STOCK.DAT”,ios::binary|ios::in|ios::out);
            cout>>Ino;
            cin.getline(Item,20);
            ______________________ //Statement 2
            File.write((char*)this,sizeof(Item));
            File.close();
}

Assignment 12: File Handling - Text File SOLUTION

File Handling - Text File 
[SET – 1]

1
Write a C++ program to write number 1 to 100 in a data file NOTES.TXT. 
#include<fstream.h>
  
int main()
{
 ofstream fout;
 fout.open("NOTES.TXT");
 for(int i=1;i<=100;i++)
  fout<<i<<endl;
 fout.close();
 return 0;
}

2
Write a C++ program, which initializes a string variable to the content "Time is a great teacher but unfortunately it kills all its pupils. Berlioz" and outputs the string to the disk file OUT.TXT. you have to include all the header files if required. 
#include<fstream.h>

int main()
{
 ofstream fout;
 fout.open("out.txt");
 char str[300]="Time is a great teacher but unfortunately it kills
  all its pupils. Berlioz";
 fout<<str;
 fout.close();
 return 0;
}
3
Write a user-defined function in C++ to read the content from a text file OUT.TXT, count and display the number of alphabets present in it
void alphabets()
{
 ifstream fin;
 fin.open("out.txt");
 char ch;
 int count=0;
 while(!fin.eof())
 {
  fin.get(ch);
  if(isalpha(ch))
   count++;
 }
 cout<<"Number of alphabets in file are "<<count;
 fin.close();
}


4
Write a function to count the number of blank present in a text file named "OUT.TXT". 
void blankspace()
{
 ifstream fin;
 fin.open("out.txt");
 char ch;
 int count=0;
 while(!fin.eof())
 {
  fin.get(ch);
  if(ch==' ')
   count++;
 }
 cout<<"Number of blank spaces in file are "<<count;
 fin.close();
}
5
Write a function to count number of words in a text file named "OUT.TXT". 
void countwords()
{
 ifstream fin;
 fin.open("out.txt");
 char word[30];
 int count=0;
 while(!fin.eof())
 {
  fin>>word;
  count++;
 }
 cout<<"Number of words in file are "<<count;
 fin.close();
}

6
Write a function in C++ to print the count of word the as an independent word in a text file STORY.TXT.
for example, if the content of the file STORY.TXT is
There was a monkey in the zoo. The monkey was very naughty.

Then the ouput of the program should be 2.
void countword()
{
 ifstream fin;
 fin.open("STORY.TXT");
 char word[30];
 int count=0;
 while(!fin.eof())
 {
  fin>>word;
  if(strcmpi(word,"the")==0)
   count++;
 }
 cout<<"Number of the word in file are "<<count;
 fin.close();
}

7
Write a function in C++ to count and display the number of lines not starting with alphabet 'A' present in a text file "STORY.TXT".
Example:
If the file "STORY.TXT" contains the following lines,
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.

The function should display the output as 3. 
void countlines()
{
 ifstream fin;
 fin.open("STORY.TXT");
 char str[80];
 int count=0;
 while(!fin.eof())
 {
  fin.getline(str,80);
  if(str[0]!='A')
   count++;
 }
 cout<<"Number of lines not starting with A are "<<count;
 fin.close();
}


8
Assuming that a text file named FIRST.TXT contains some text written into it, write a function named copyupper(), that reads the file FIRST.TXT and creates a new file named SECOND.TXT contains all words from the file FIRST.TXT in uppercase. 
void copyupper()
{
 ifstream fin;

 fin.open("FIRST.TXT");
 ofstream fout;
 fout.open("SECOND.TXT");
 char ch;
 while(!fin.eof())
 {
  fin.get(ch);
  ch=toupper(ch);
  fout<<ch;
 }
 fin.close();
 fout.close();
}

9
Assuming that a text file named FIRST.TXT contains some text written into it, write a function named vowelwords(), that reads the file FIRST.TXT and creates a new file named SECOND.TXT, to contain only those words from the file FIRST.TXT which start with a lowercase vowel (i.e., with 'a', 'e', 'i', 'o', 'u'). 
For example, if the file FIRST.TXT contains
Carry umbrella and overcoat when it rains
Then the file SECOND.TXT shall contain
umbrella and overcoat it 
void vowelwords()
{
 ifstream fin;
 fin.open("FIRST.TXT");
 ofstream fout;
 fout.open("SECOND.TXT");
 char word[30];
 while(!fin.eof())
 {
  fin>>word;
  if(word[0]=='a'||word[0]=='e'||word[0]=='i'||word[0]=='o'||word[0]=='u')
   fout<<word<<" ";
 }
 fin.close();
 fout.close();
}


Assignment 12: File Handling - Text File

File Handling - Text File 
[SET – 1]

1
Write a C++ program to write number 1 to 100 in a data file NOTES.TXT. solution
2
Write a C++ program, which initializes a string variable to the content "Time is a great teacher but unfortunately it kills all its pupils. Berlioz" and outputs the string to the disk file OUT.TXT. you have to include all the header files if required. solution
3
Write a user-defined function in C++ to read the content from a text file OUT.TXT, count and display the number of alphabets present in it. solution
4
Write a function to count the number of blank present in a text file named "OUT.TXT". solution
5
Write a function to count number of words in a text file named "OUT.TXT". solution
6
Write a function in C++ to print the count of word the as an independent word in a text file STORY.TXT.
for example, if the content of the file STORY.TXT is
There was a monkey in the zoo. The monkey was very naughty.

Then the ouput of the program should be 2. solution
7
Write a function in C++ to count and display the number of lines not starting with alphabet 'A' present in a text file "STORY.TXT".
Example:
If the file "STORY.TXT" contains the following lines,
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.

The function should display the output as 3. solution
8
Assuming that a text file named FIRST.TXT contains some text written into it, write a function named copyupper(), that reads the file FIRST.TXT and creates a new file named SECOND.TXT contains all words from the file FIRST.TXT in uppercase. solution
9
Assuming that a text file named FIRST.TXT contains some text written into it, write a function named vowelwords(), that reads the file FIRST.TXT and creates a new file named SECOND.TXT, to contain only those words from the file FIRST.TXT which start with a lowercase vowel (i.e., with 'a', 'e', 'i', 'o', 'u').
For example, if the file FIRST.TXT contains
Carry umbrella and overcoat when it rains
Then the file SECOND.TXT shall contain
umbrella and overcoat it solution

Assignment 11: Inheritance

Inheritance

1
Consider the following declaration and answer the questions given below :
class PPP
{
            int H: 
            protected :
                        int S;
            public :
                        void INPUT (int);
                        void OUT();
};
class QQQ : private PPP
{
            int T;
            protected :
                        int U;
            public :
                        void INDATA(int, int);
                        void OUTDATA();
};
class RRR : public QQQ
{
            int M;
            public :
                        void DISP( void );
};
(i) Name the base class and derived class of the class QQQ. 
(ii) Name the data member(s) that can be accessed from function DISP(). 
(iii) Name the member function(s), which can be accessed from the objects of class RRR. 
(iv)Is the member function OUT() accessible by the object of the class QQQ? 
Question 2
Answer the questions (i) to (iv) based on the following:
class PUBLISHER
{
            char Pub[12];
            double Turnover;
protected:
            void Register();
public:
            PUBLISHER();
            void Enter();
            void Display();
};
class BRANCH
{
            char CITY[20];
protected:
            float Employees;
public:
            BRANCH();
            void Haveit();
            void Giveit();
};
class AUTHOR : private BRANCH, public PUBLISHER
{
            int Acode;
            char Aname[20];
            float Amount;
public:
            AUTHOR();
            void Start();
            void Show();
};

i) Write the names of data members, which are accessible from objects belonging to class AUTHOR.
ii) Write the names of all the member functions which are accessible from objects belonging to class BRANCH.
iii) Write the names of all the members which are accessible from member functions of class AUTHOR.
iv) How many bytes will be required by an object belonging to class AUTHOR?
Question 3
Consider the following declarations and answer the question given below : 
class vehicle
{
private:
            int wheels;
protected :
            int passenger:
public :
            void inputdata (int, int);
            void outputdata();
};
class heavyvehicle : protected vehicle
{
            int diesel_petrol;
protected :
            int load;
public:
            void readdata(int, int);
            void writedata();
};
class bus : private heavyvehicle
{
            char make[20];
public :
            void fetchdata(char);
            void displaydata();
};
(i) Name the base class and derived class of the class heavy_vehicle.
(ii) Name the data member(s) that can be accessed from function displaydata().
(iii) Name the data member's that can be accessed by an object of bus class.
(iv) Is the member function outputdata() accessible to the objects of heavy_vehicle class.
Question 4
Answer the questions (i) to (iv) based on the following code :
class Drug
{
            char Category[10];
            char Date_of_manufacture[10];
            char Company[20];
public:
            Drug();
            void enterdrugdetails();
            void showdrugdetails();
};
class Tablet : public Drug
{
            protected:
            char tablet_name[30];
            char Volume_label[20];
public:
            float Price;
            Tablet();
            void entertabletdetails();
            void showtabletdetails ();
};
class PainReliever : public Tablet
{
            int Dosage_units;
            char Side_effects[20];
            int Use_within_days;
public:
            PainReliever();
            void enterdetails();
            void showdetails();
};
(i) How many bytes will be required by an object of class Drug and an object of class PainReliever respectively ?
(ii) Write names of all the data members which are accessible from the object of class PainReliever.
(iii) Write names of all the members accessible from member functions of class Tablet.
(iv) Write names of all the member functions which are accessible from objects of class PainReliever.