NPTEL programming in c++ week 4 assignment solution 2021

 NPTEL programming in c++ week 4 assignment solution 2021

1. #include<iostream>
using namespace std;
class Test1{
    int x;
public:
    Test1(int _x) : x(_x) { cout << "Class 1: "; }
   friend void print(int,int);               //LINE-1
};
class Test2{
    int y;
public:
    Test2(int _y) : y(_y) { cout << "Class 2: "; }
   friend void print(int,int);                         //LINE-2
};
void print(int x, int y){
    if(x==1)
        cout << Test1(y).x;
    else
        cout << Test2(y).y;
}
int main(){
    int a,b;
    cin >> a >> b;
    print(a,b);
    return 0;
}


------------------------------------------------------------------------------------------------------------------------

2. #include<iostream>
using namespace std;
class positionVector{
    int x, y;
public:
    positionVector(int a, int b) : x(a), y(b) {}
    positionVector operator+ (const positionVector &c) {    //LINE-1
        positionVector p(0,0);
        p.x = x + c.x;                                     //LINE-2
        p.y = y + c.y;                                     //LINE-3
        return p;
    }
void print(){ cout << "(" << x << ", " << y << ")"; }
};
int main(){
    int x1,y1,x2,y2;
    cin >> x1 >> y1 >> x2 >> y2;
    positionVector p1(x1,y1), p2(x2,y2), p3(0,0);
    p3 = p1+p2;
    p3.print();
    return 0;
----------------------------------------------------------------------------------------------------------------


3. #include<iostream>
using namespace std;

class Student{
    const int id;
    string name;

    mutable int marks;                               //LINE-1

public:
    Student(int a, string b, int c) : id(a), name(b), marks(c) {}

    void updateMarks(int x) const{ marks += x; }     //LINE-2

    void print() const{                            //LINE-3
 cout << id << " : " << name << " : " << marks; 

} // End of Function print  
 
}; // End of class

int main(){
    string n;
    int i, m, u;
    cin >> i >> n >> m >> u;
    const Student s1(i, n, m);
    s1.updateMarks(u);
    s1.print();
    return 0;
}

---------------------------------------------------------------------------------------------------------------

4.#include<iostream>
using namespace std;

class database {
    int data;

    static database *dbObject;            //LINE-1 Complete the declaration
    database(int x) : data(x) {}
public:
    static database* connect(int x){      //LINE-2 Mention return type of the function
        if(!dbObject)

           dbObject=new database(x);   //LINE-3 Allocate memory to pointer dbObject
        return dbObject;
    }
void show(){
        cout << data;
    }
};

database *database::dbObject = 0;

int main() {
    int x, y;
    database *db1, *db2;
    cin >> x >> y;
    db1 = database::connect(x);
    db2 = database::connect(y);
    db1->show();
    db2->show();
    return 0;
}

No comments

Powered by Blogger.