Friday, 21 July 2017

PRACTICE EXERCISES

PRACTICE PAPER

1)a) Write and 2 characteristics of a constructor and a destructor.
b)     Are the default constructor and constructor with default parameter same?Give reason.
c)      Give any 2 differences between a constructor and a normal function.
d)     Given the following :

class Distance 
{
private:
int feet;
float inches;
public:
--------------
--------------
};
void main()
{
Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25); //define, initialize dist2
dist1.getdist(); //get dist1 from user
dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2
cout << “\ndist1 = “; dist1.showdist(); // print dist1
cout << “\ndist2 = “; dist2.showdist(); // print dist2
}
Complete the above class description with necessary constructors and member function definitions.



e)                     Answer the questions (a) and (b) after going through the class definition:
class Force
{
int power;
public:
Force()  // constructor 1
{power=0;}
Force(int z) // constructor 2
{
power=Z;
}
Force(Force &F) // constructor 3
{power=F.power;}};

a) What type of constructor is constructor 3? Explain.
b) Write statement to declare object for 'Force' so that it invokes constructor 2.

f)                      Answer the questions (a) and (b) after going through the following class:
class cars
{
int noofwheels,capacity;
float mileage;       
cars();              // function 1
cars(int x, int y, float z); // function 2
cars(cars &c); // function 3
};
a) Write the definition of function 1, function 2 and function 3.
b) Create object to invoke function 1, function 2, function 3.

2) a) Define the following terms:
i) Abstract class
ii) Containership
b) Assume there is a class pony derived from base class horse. Both classes contain a member function jump() that takes no arguments. Write a statement that calls the member function jump() of class horse from the object of class pony.
c) Consider the following declarations and answer the questions (i to ii) that follow:
class CUSTOMER
{
int Cust_no;
char Cust_Name[20];
protected: 
void Register();
public:
CUSTOMER();
void Status();};
class SALESMAN
{
int Salesman_no;
char Salesman_Name[20];
protected:
float Salary;
public:
SALESMAN();
void Enter();
void Show();
};
class SHOP:private CUSTOMER, public SALESMAN
{
char Voucher_No[10],Sales_Date[8];
public:
SHOP();
void Sales_Entry();
void Sales_Detail();};

i) Write the names of data members which are accessible from objects belonging to class CUSTOMER.
ii) Write the names of all the member functions which are accessible from objects belonging to class SALESMAN.
iii) Write the names of all the members which are accessible from member functions of class SHOP.
iv) How many bytes will be required by an object belonging to class SHOP?

d) Answer the question (i) to (iv) based on the following:  

class Organization
{
char Address[20];
double Budget, Income;
protected:
void Compute( );
public:
Organization( );
void Get( );
void Show( );
};

class WorkArea : public Organization
{
char Address[20];
int Staff;
protected:
double Pay;
void Calculate( );
public:
WorkArea( );
void Enter( );
void Display( );
};
class ShowRoom : private Organization
{
char Address[20];
float Area;
double Sale;
public:
ShowRoom( );
void Input( );
void Show( );
};
(i) Name the type of inheritance illustrated in the above C++ code.
(ii) Write the name of members, which are accessible from member function Input() of class ShowRoom.
(iii) Write the name of all the member functions, which are accessible from objects belonging to class WorkArea.
(iv) How many bytes will be required by an object of class ShowRoom?

3 a) Write a function AECount() in C++, which should read each character of a text file NOTES.TXT, should count and display the occurrence of alphabets A and E (including small cases a and e too).  
Example :
If the file content is as follows :
CBSE enhanced its CCE guidelines further.
The AECount() function should display the output as
A:1
E:7

b) Write a function in C++ to read the content of a text file “Place.TXT” and display all those lines on screen which are either starting with “P” or starting with “S”.

c) Write the command to place the file pointer at the 10th and 4th record starting position using seekp() or seekg() command. File object is ‘file’ and record name is ‘STUDENT’.

c)Write a function LtoD() that that would display the corrected version of entire content of the file LINE.TXT with all alphabets  ‘D’ to be replaced as ‘L’, ‘d’ with ‘l’.
If the file contained the following text:
Dearn to dive and dive to dearn

Then it should display the following
Learn to live and live to learn

1) d)
class Distance 
{
private:
int feet;
float inches;
public:
Distance()
{
feet=12;inches=5.5;}
Distance(int x, float y)
{
feet=x;
inches=y;
}
void getdist()
{
cin>>feet>>inches;
}
Distance add_dist(Distance d2)
{Distance d3;
d3.feet=feet+d2.feet;
d3.inches=inches+d3.inches;
return d3;
}
void showdist()
{
cout<<feet<<" "<<inches;
}
};
void main()
{
Distance dist1, dist3; //define two objects
Distance dist2(11, 6.25); //define, initialize dist2
dist1.getdist(); //get dist1 from user
dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2
cout << “\ndist1 = “; dist1.showdist(); // print dist1
cout << “\ndist2 = “; dist2.showdist(); // print dist2
}

e)
a) Copy constructor because the object is passed by reference that is used to initialize another object with its values.
b) Force f(5) ;

f) a)cars::cars() // function 1
{
noofwheels=4;
capacity = 1500;
mileage = 5000;}
cars::cars(int x, int y, float z) // function 2
{
noofwheels=x;
capacity=y;
mileage=z;
}
cars::cars(cars &c) // function 3
{
noofwheels=c.noofwheels;
capacity=c.capacity;
mileage=c.mileage
}
void main()
{
cars c1, c2(5,1000,10000);  // object declaration
cars c3=c1;
}

2) c)
i) None
ii)Enter(), Show()
iii) Data Members: Voucher_No[10],Sales_Date[8],Salary
     Member functions : Register(), Enter(), Show(), Sales_Entry(),Sales_Detail()
iv) 66 bytes

d)
i) Hierarchical
ii) Data members -
    Address[20],Area,Sale
    Member functions - Compute(), Get(), Organization::Show(), Show()
iii)Enter(), Display()
iv)68 bytes


2. (a) Differentiate between protected and private members of a class in context of Object Oriented Programming. Also give a suitable example illustrating accessibility/non-accessibility of each using a class and an object in C++.
(b) Observe the following C++ code and answer the questions (i) and (ii).
Note : Assume all necessary files are included.

class TEST
{
long TCode;
char TTitle[20];
float Score;
public:
TEST() //Member Function 1
{
TCode=100;strcpy(TTitle,"FIRST Test");Score=0;
}
TEST(TEST &T) //Member Function 2
{
TCode=E.TCode+1;
strcpy(TTitle,T.TTitle);
Score=T.Score;
}
};
void main()
{
_______________ //Statement 1
_______________ //Statement 2
}
(i) Which Object Oriented Programming feature is illustrated by the Member Function 1 and the Member Function 2 together in the class TEST ?  
(ii) Write Statement 1 and Statement 2 to execute Member Function 1 and Member Function 2 respectively.




Answer the questions (i) to (iv) based on the following :  
class First
{
int X1;
protected:
float X2;
public:
First();
void Enter1(); void Display1();
};
class Second : private First
{
int Y1;
protected:
float Y2;
public:
Second();
void Enter2();
void Display();
};

class Third : public Second
{
int Z1;
public:
Third();
void Enter3();
void Display();
};
void main()
{
Third T; //Statement 1
___________________; //Statement 2
}



  

i)Which type of Inheritance out of the following is illustrated in the above example ?
Single Level Inheritance, Multilevel Inheritance, Multiple Inheritance
(ii) Write the names of all the member functions, which are directly accessible by the object T of class Third as declared in main() function.
(iii) Write Statement 2 to call function Display() of class Second from the object T of class Third.
(iv) What will be the order of execution of the constructors, when the object T of class Third is declared inside main() ?








Wednesday, 12 July 2017

Text File Handling

A file is a bunch of bytes stored on some storage device like disk.

Need: To store data permanently and in large quantities.

Types of data files:

Text file and binary file.

A text file is also called as an ascii file. Character conversions take place in the text file and it includes EOL end of line marker at the end of every line.

No such conversions take place in binary file. It saves data in binary form .A binary file is a file stored in binary format. A binary file is computer-readable but not human-readable. All executable programs are stored in binary files, as are most numeric data files. In contrast, text files are stored in a form (usually ASCII) that is human-readable.


Stream - sequence of bytes - acts as an interface between program and I/O devices.

Stream that reads data from the file - Input stream

Stream that writes data on to the file - output stream.

Classes for file stream operations

I/O system of C++ contain as set of classes that defines file handling methods. This includes fstream, ifstream, ofstream.

iostream.h -> related to console I/O
fstream.h-> related to file I/O

Declaring a file stream
File Stream is a data type which is used to declare an object of stream. It may be input file stream or output file stream.

Syntax
file_stream_class  stream_object;

eg:ifstream fin;// for input operation
     ofstream fout;// for outupt operation

Opening a file

Before a file is used, it should be opened. There are 2 methods to open a file.

i) By using constructor function of the class
       ifstream f1("story.txt");
ii) By using open method.

    ifstream f1;
    f1.open("story.txt");

Steps to read a text file and process it

i) Declare the stream(ifstream or fstream)
ii) Determine the buffer size
iii) Declare and initialize variables if any
iv) check if file exists, otherwise display error message
v) use while loop(to check end of file condition)
vi) determine the input method(to get the content into the buffer)
     for eg if f1 is the object
     f1.get(ch);// will get a single character from the file
     f1.get(ch,50);// will get ch as a string from the file
     f1>>ch;// will get ch as a string thereby ignoring space and other whiteline characters
     f1.getline(ch,50);// will get one line of content at a time in the buffer
v) check for condition if any and process(using ctr)
vi) end the loop
vii) Print the required output

Steps to write data on to text file  

i) Declare the stream(ofstream or fstream)
ii) Determine the buffer size
iii) Declare and initialize variables if any
iv) use do while loop
v) Input values from user within the body
vi) use one of the following to write the values into the file
    if f1 is the object
      f1<<str;// will write str as string into f1
      f1.put(str);// will write str as a single character into the file.
vii) input continue variable
viii) end the while loop


Different file modes

ios::in - to read the file
ios::out - to write the file
ios::app - to add data at the end of the file
ios::ate- to write data anywhere in the file
ios::nocreate - open fails if file does not exist
ios::noreplace - open fails if file already exists
ios::trunc - deletes contents of file if exists
ios::binary - opens file in binary mode

random reading of files

f1.seekg(5,ios::beg);// moves file pointer 5 bytes forward starting from the beginning of the file.
f1.seekg(-5,ios::cur); // moves file pointer backwards from the current position.
f1.seekg(0,ios::end); moves the file pointer to end of file position.
f1.tellg();// tells the location of the pointer in the file
f1.seekp();// places the file pointer before writing
f1.tellp();// tells the location of the pointer while writing (if the object is opened in the output mode)

Exercises:

1)       Write a program that accepts a file name as a variable and displays the size of a file in bytes.    
2)       Write a function COUNT() to count the presence of a word “to” as independent word in a text file “NOTES.TXT”.                                                       
For eg: if the content of the file contains
It is very important to know that
Smoking is an injurious tool to health
Let us take initiative to stop it.

The output should be:
Count of “to”: 3    

3)       Write a program using a  function to count the number of alphanumeric words present in a text file:             
For eg, if the file contains
Attention 12C students, the vehicle no TN9022 is parked wrongly at B3.
The output should be :3

4)       Write programs(using functions) to
a)       Read a text file story.txt and count no of alphabets, digits and special characters in that file and display the same.
b)       Read a text file lines.txt and prints count of lines that has the word “you” in a line.
For eg:
If the file has
Take risks in life.
If you win, you can lead!
If you lose, you can guide!

Output: 2

#include <fstream.h>
#include <string.h>
#include <conio.h>
void main()
{
ifstream f1("dream.txt");
char str[25];
int ctr=0;
while(!f1.eof())
{f1>>str;
 if(strcmpi(str,"you")==0)
 {
 ctr++;
 f1.getline(str,25);
 }
}
cout<<ctr;

}

c)       Read a text file case.txt and convert all the text to upper case and write it in another file uppercase.txt
For eg if the file contains following text:
Dream, dream, dream
Dreams transform into thoughts and thoughts result in action.

The output file should contain
FOR EG IF THE FILE CONTAINS FOLLOWING TEXT:
DREAM, DREAM, DREAM DREAMS TRANSFORM INTO THOUGHTS AND THOUGHTS RESULT IN ACTION.  

Solution:
#include <fstream.h>
#include <string.h>
#include <conio.h>
void main()
{
ifstream f1("dream.txt");
ofstream f2("out.txt");
char str[25];
while(!f1.eof())
{f1>>str;
 f2<<strupr(str)<<" ";
}}


d)       Read the text file WORDS.TXT and print those words that does not end with a vowel.
Eg: If the file contains

If you want to shine like a sun, first burn like a sun.

Output:
If want sun first burn sun

e)       Read a text file story.txt and print all three letter words starting with a capital letter.
f)        Read  a text file called lines.txt and print all the strings that are palindromes.
        (Hint: Use strrev() function)

Note: A palindrome is a string that is same as its reverse. Eg: madam


Predict the output problem given the following code assuming the text file contains the following content:

she sells sea shells in the sea shore.

The code:

#include <fstream.h>
#include <string.h>
#include <conio.h>
void main()
{
clrscr();
ifstream f1("dream.txt");
char s[20],ch;
f1.seekg(1);
f1>>ch;
cout<<ch<<endl;
f1.seekg(4);
f1.seekg(10);
f1.get(s,10);
cout<<s<<endl;
f1.seekg(-15,ios::end);
f1.getline(s,20);
cout<<s<<endl;

}

Output:


h

sea shell

 the sea shore.

Identify the errors in the following code and rewrite the corrected code and underline it.
(Assume necessary header files are included).

void main()
{
clrscr();
ifstream f1("dream.txt",ios::in);
char s[30]="Honesty is the best policy";
f1<<s;
f1.seekg(0);
f1.gets(s);
while(f1)
{
f1.get(s);
if(strcmp(s,"to")==0) ctr++;
}

}

Solution


void main()
{
clrscr();
fstream f1("dream.txt",ios::in|ios::out);
char s[30]="Honesty is the best policy";
int ctr=0;
f1<<s;
f1.seekg(0);
f1.get(s,20);
while(f1)
{
f1.get(s,20);
if(strcmp(s,"to")==0) ctr++;
}
}

BOARD PAPER - 2017

Write function definition for SUCCESS( ) in C++ to read the content of a text file
STORY.TXT, count the presence of word SUCCESS and display the number of
occurrence of this word. 2
Note :
– The word SUCCESS should be an independent word
– Ignore type cases (i.e. lower/upper case)
Example :
If the content of the file STORY.TXT is as follows :
Success shows others that we can do it. It is possible to achieve success with hard work. Lot of money does not mean SUCCESS.
The function SUCCESS( ) should display the following :

3

Ans:

void SUCCESS()
{
int count=0;
ifstream f("STORY.TXT");
char s[20];
while (!f.eof())
{

f>>s;
count++;
}
cout<<count;
f.close();

}