Q.1) Write a C++ program to create a class which contains two dimensional integer array of size mXn. Write a member function to display sum of all elements of entered matrix. (Use Dynamic Constructor for allocating memory and Destructor to free memory of an object)
#include<conio.h>
#include<iostream.h>
main()
{
int r,c,sum=0;
clrscr();
cout<<"\n Enter dimension ";
cin>>r;
cin>>c;
int **a;
a=new int*[r];//[s];
for(int i=0;i<r;i++)
{ a[i]=new int[c];
}
for(i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cout<<"\n enter data : ";
cin>>a[i][j];
}
}
for(i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
cout<<"\t"<<a[i][j];
}
cout<<endl;
}
for(i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
sum=sum+a[i][j];
}
}
cout<<"\n sum of all elements of matrix : "<<sum;
getch();
}
Q.2) Create a class Time which contains data members as: Hours, Minutes and Seconds. Write C++ program to perform following necessary member functions:
i. To read time ii. To display time in format like: hh:mm:ss iii. To add two different times (Use Objects as argument)
#include<iostream.h>
#include<conio.h>
class Time
{
int hr,min,sec;
public:
void settime(int x,int y,int z)
{ hr=x;
min=y;
sec=z;
}
void showtime()
{ cout<<"\n"<<hr<<":"<<min<<":"<<sec<<endl;
}
Time add(Time t)
{
Time t1;
t1.sec=sec+t.sec;
t1.min=t1.sec/60;
t1.sec=t1.sec%60;
t1.min=t1.min+min+t.min;
t1.hr=t1.min/60;
t1.min=t1.min%60;
t1.hr=t1.hr+hr+t.hr;
return t1;
}
};
void main()
{
int h,m,s;
cout<<"\n Enter hr:\t";
cin>>h;
cout<<"\n Enter min:\t";
cin>>m;
cout<<"\n Enter sec:\t";
cin>>s;
Time t1;
t1.settime(h,m,s);
t1.showtime();
Time t2;
cout<<"\n Enter hr:\t";
cin>>h;
cout<<"\n Enter min:\t";
cin>>m;
cout<<"\n Enter sec:\t";
cin>>s;
t2.settime(h,m,s);
t2.showtime();
Time t3;
cout<<"\t Addition of 2 times : ";
t3=t1.add(t2);
t3.showtime();
getch();
}
i. To read time ii. To display time in format like: hh:mm:ss iii. To add two different times (Use Objects as argument)
#include<iostream.h>
#include<conio.h>
class Time
{
int hr,min,sec;
public:
void settime(int x,int y,int z)
{ hr=x;
min=y;
sec=z;
}
void showtime()
{ cout<<"\n"<<hr<<":"<<min<<":"<<sec<<endl;
}
Time add(Time t)
{
Time t1;
t1.sec=sec+t.sec;
t1.min=t1.sec/60;
t1.sec=t1.sec%60;
t1.min=t1.min+min+t.min;
t1.hr=t1.min/60;
t1.min=t1.min%60;
t1.hr=t1.hr+hr+t.hr;
return t1;
}
};
void main()
{
int h,m,s;
cout<<"\n Enter hr:\t";
cin>>h;
cout<<"\n Enter min:\t";
cin>>m;
cout<<"\n Enter sec:\t";
cin>>s;
Time t1;
t1.settime(h,m,s);
t1.showtime();
Time t2;
cout<<"\n Enter hr:\t";
cin>>h;
cout<<"\n Enter min:\t";
cin>>m;
cout<<"\n Enter sec:\t";
cin>>s;
t2.settime(h,m,s);
t2.showtime();
Time t3;
cout<<"\t Addition of 2 times : ";
t3=t1.add(t2);
t3.showtime();
getch();
}