Programming in C++ Week-3 programs
Programming in C++ Week-3 programs
1. Consider the following program. Fill in the blanks at LINE-1 and LINE-2 to complete parameterized and copy constructor and at LINE-3 to complete the return statement which calculates the Euclidean distance between two points (Use math library functions when needed). Please check the sample input and output.
#include<iostream>
#include<cmath>
using namespace std;
class Point{
const int x,y;
public:
Point(int _x=0, int _y=0) : x(_x),y(_y) {} //LINE-1
Point(const Point& p) :x(p.x),y(p.y) {} //LINE-2
double distance(Point p){
return sqrt(pow((p.x-x),2)+pow((p.y-y),2)); //LINE-3
}
void print(){ cout << "(" << x << "," << y << ")" << endl; }
};
int main(){
int x1,x2,y1,y2;
cin >> x1 >> y1 >> x2 >> y2;
Point p1(x1,y1), p2(x2,y2);
p1.print();
p2.print();
printf("Distance: %.2f", p1.distance(p2));
return 0;
}
2. Consider the following program. Fill in the blanks at LINE-1 to complete the parameterized constructor and at LINE-2 to complete the destructor which deletes the dynamically allocated memory to data member arr. Consider the following test cases.
#include<iostream>
using namespace std;
class IntArray{
int *arr;
int size;
public:
IntArray(int n) :arr(new int[n]),size(n){} //LINE-1
~IntArray(){delete[] arr; } //LINE-2
void EnterEle(){
for(int i=0;i<size;i++)
cin >> arr[i];
}
void FindMax(){
int max = -1;
for(int i=0;i<size;i++){
if(max < arr[i])
max = arr[i];
}
cout << "Max: " << max;
}
};
int main(){
int n;
cin >> n;
IntArray a(n);
a.EnterEle();
a.FindMax();
return 0;
}
3. Consider the following program. Fill in the blanks at LINE-1 and LINE-2 to complete the constructor and destructor and at LINE-3 to complete the copy assignment operator header and at LINE-4 to concatenate the function input with the class data member such that it satisfies the given test cases.
#include<iostream>
#include<malloc.h>
#include<string.h>
using namespace std;
class Myclass{
char *str;
public:
Myclass(char *s) :str(s) {} //LINE-1
~Myclass(){delete str; } //LINE-2
Myclass& operator=(Myclass& m){ //LINE-3
free(str);
str = strdup(m.str);
return *this;
}
void update(char* x){
strcat(str," ");
strcat(str,x); //LINE-4
}
void print(){
cout << str << endl;
}
};
int main(){
string str1,str2;
cin >> str1 >> str2;
Myclass m1(&str1[0]);
Myclass m2 = m1;
m2.update(&str2[0]);
m2.print();
return 0;
}
No comments