C++

C++ Programming

Slip12

Q.1) Write a C++ program to accept length and width of a rectangle. Calculate and display
perimeter as well as area of a rectangle by using Inline function. [Marks 15]

Solution

#include<iostream.h>
#include<conio.h>
#include<math.h>
inline void perimeter(int l,int w)
{
 int p;
 p=2*(l+w);
 cout<<"Perimeter of rectangle:"<<p<<endl;
}
inline void area(int l,int w)
{
 int a;
 a=l*w;
 cout<<"Area of rectangle:"<<a<<endl;
}
void main()
{
 int l,w;
 clrscr();
 cout<<"Enter the value of l=length & w=width:";
 cin>>l>>w;
 perimeter(l,w);
 area(l,w);
 getch();
}


Output

Enter the value of l=length & w=width:
5
6
Perimeter of rectangle:22
Area of rectangle:30


Q.2) Create a class MyString which contains a character pointer (using new operator). Write a
C++ program to overload following operators:
> to compare length of two strings
!= to check equality of two strings
+ to concatenate two strings [Marks 25]

Solution

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>

class mystring
{
   char str[100];
   public:
       mystring(char *s)
       {
  strcpy(str, s);
       }
       void display()
       {
  cout<<"\n\tString :"<<str;
       }
       mystring operator +(mystring o)
       {

   char s[100];
   strcpy(s,str);
   strcat(s, o.str);
   mystring obj(s);
   return obj;
       }
       void operator !=(mystring o)
       {

  if(strcmp(str , o.str) != 0)
       cout<<"String is not equal";
  else
cout<<"String is equal";
      }
       void operator >(mystring o)
       {
   int len1,len2;
   len1=strlen(this->str);
   len2=strlen(o.str);
      if(len1>len2)
cout<<str<<" is greater"<<endl;
      else
cout<<o.str<<" is greater"<<endl;
       }
};

int main()
{
    char s[100];
   cout<<"\n\tEnter first string :"; fflush(stdin);
   gets(s);
   mystring s1(s);
   cout<<"\n\tEnter string string :"; fflush(stdin);
   gets(s);
   mystring s2(s);

   mystring s3 = s1 + s2;
   cout<<" \n\t s1 : " ;      s1.display();
   cout<<"\n\t s2 :" ;        s2.display();
   cout<<"\n\t s1 + s2 :";    s3.display();
   cout<<endl<<endl;
   s1>s2;
   cout<<endl;
   s1!=s2;
   getch();
   return 0;
}

Output

Enter first string :abc

Enter string string :xyz

s1 :
String :abc
s2 :
String :xyz
s1 + s2 :
String :abcxyz

xyz is greater

String is not equal
BCA Pratical Solution

My name is Vivek And I from Mumbai and Complete my Graduation Bca.my Age is 23 Years.

Post a Comment

Previous Post Next Post