C++ Programming
Slip13
Q.1) Write a C++ program to calculate area of cone, sphere and circle by using function
overloading. [Marks 15]
Solution
#include<iostream.h>
#include<conio.h>
#include<math.h>
class shape
{
private:
int r,h; // A=ãr(r+h2+r2)
float A;
public:
void accept(int a,int b);
void area(int r,int h);
void area(int r);
void area();
};
void shape:: accept(int a,int b)
{
r=a;
h=b;
}
void shape:: area(int r,int h)
{
A=3.14*r*(r+sqrt(h*h+r*r));
cout<<"Area of cone:"<<A;
}
void shape:: area(int r)
{
A=4*3.14*r*r; //A=4ãr2
cout<<"\nArea of shpere:"<<A;
}
void shape:: area()
{
A=3.14*r*r; //A=ãr2
cout<<"\nArea of circle:"<<A;
}
void main()
{
shape s1;
int a,b;
clrscr();
cout<<"Enter the value:";
cin>>a>>b;
s1.accept(a,b);
s1.area(a,b);
s1.area(a);
s1.area();
getch();
}
Output
Enter the value:
3
2
Area of cone:62.224293
Area of shpere:113.040001
Area of circle:28.26
Q.2) Create a class Matrix and Write a C++ program with following functions:
i. To accept a Matrix
ii. To display a Matrix
iii. Overload unary minus ‘ – ‘ operator to calculate transpose of a Matrix
iv. Overload binary multiplication '*’ operator to calculate multiplication of two
matrices [Marks 25]
Solution
#include<iostream.h>
#include<conio.h>
class matrix
{
int a[3][3];
public:
matrix operator *(matrix);
void operator -();
void getdata();
void display();
};
void matrix::getdata()
{
int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
cout<<"Enter elements : ";
cin>>a[i][j];
}
}
void matrix::display()
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ cout<<" ";
cout<<a[i][j];
}
cout<<endl;
}
}
matrix matrix::operator *(matrix m2)
{
int i,j;
matrix m3;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
m3.a[i][j]=a[i][j] * m2.a[i][j];
return m3;
}
void matrix::operator -()
{
int i,j,temp;
for(i=0;i<3;i++)
for(j=i+1;j<3;j++)
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
int main()
{ clrscr();
int choice;
matrix m,m1,m2,m3;
do
{
cout<<"\n1: To accept a matrix \n2: To display a matrix"<<endl;
cout<<"3:Overload unary minus '-' operator to calculate transpose of matrix"<<endl;
cout<<"4:Overload binary operator '*' operator to multiplicatio of two matrix"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:cout<<"Enter Matrix for transpose : "<<endl;
m.getdata();
cout<<"Enter two Matrix for multiplication : "<<endl;
cout<<"First matrix: "<<endl;
m1.getdata();
cout<<"Second matrix: "<<endl;
m2.getdata();
break;
case 2:cout<<"Matrix for transpose : "<<endl;
m.display();
cout<<"Two Matrix for multiplication : "<<endl;
cout<<"First matrix: "<<endl;
m1.display();
cout<<"Second matrix: "<<endl;
m2.display();
break;
case 3: cout<<"Original matrix : "<<endl;
m.display();
-m;
cout<<"transpose of matrix : "<<endl;
m.display();
break;
case 4: m3=m1*m2;
cout<<"matrix 1 display : "<<endl;
m1.display();
cout<<"matrix 2 display : "<<endl;
m2.display();
cout<<"multiplication of matrix : "<<endl;
m3.display();
break;
}
}while(choice!=5);
getch();
return 0;
}
Tags:
c++