Friday, 19 January 2018

CPP-Slip18



Slip18
Q.1)Write a C++ program to create a class Integer. Write necessary member functions to overload the operator unary pre and post increment ‘++’ for an integer number.

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
class integer
{
int no;
public:
integer(){}
integer(int num)
{
no=num;
}
integer operator++()
{
++no;
return *this;
}
integer operator++(int) //post increment
{
integer temp=*this;
no++;
return temp;
}
void display()
{
cout<<"\nNo = "<<no;
}
};
void main()
{
integer i(10),i1(10),i3;
clrscr();
cout<<"\nAfter post increment = ";
i3=i++;
i3.display();
cout<<"\nAfter pre increment = ";
i3=++i1;
i3.display();
getch();
}
    

Another way



#include<iostream.h>
#include<conio.h>
 class Integer
   {
    int a;
    public:
    void accept();
    void show();
    void operator++();
   };
 void Integer::accept()
   {
    cout<<"\nEnter a Number:";
    cin>>a;
   }
 void Integer::show()
   {
    cout<<"\nEntered number is:"<<a;
   }
 void Integer::operator++()
   {
    int temp;
    temp=a;
    cout<<"\nPre increment of the given number is:"<<++temp;
    cout<<"\nPost increment of the given number is:"<<a++;
   }
 int main()
   {
    clrscr();
    Integer i;
    i.accept();
    i.show();
    i.operator++();
    getch();
    return 0;
   }
     

Q.2)  Write a C++ program to read the contents of a text file. Count and display number of characters, words and lines from a file. Find the number of occurrences of a given word  present in a file.

#include <iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<string.h>

main()
{
char character,file[20],word[20];
ifstream in;
int charcnt,wcnt,lcnt; //clrscr();
cout<<"\n Enter file name : ";
cin>>file;

in.open(file);
if(in.fail())
{
cout<<"\n file does not exists :"<<endl;
exit(1);
}

charcnt = 0;
lcnt = 0;
wcnt = 0;
           
char ch;
while(!in.eof())
{
ch=in.get();
if(ch == '\n')
{
lcnt++; wcnt++;
}
else if(ch==' ' ||ch=='\t' )
{
wcnt++;
charcnt++;
}
else charcnt++;
}
cout << "Characters: " << charcnt << endl;
cout << "Lines: " << lcnt << endl;
cout << "Words: " << wcnt << endl;
in.close();

cout<<"\n Enter word yo be search : ";
cin>>word;
in.open(file);
char str[20];int f=0;
while(!in.eof())
{
in>>str;
if(strcmp(str,word)==0)
{
f++;
}
}
if(f!=0)
{cout<<"\n word found : "<<f;}
else cout<<"\n NOT found";  
getch();
}